def test_authenticate_and_request(self): if is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if is_mongos(self.client): raise SkipTest("Auth fails on sharding due to write concern race, see Tokutek/mongo#77") if not server_started_with_auth(self.client): raise SkipTest("Authentication is not enabled on server") # Database.authenticate() needs to be in a request - check that it # always runs in a request, and that it restores the request state # (in or not in a request) properly when it's finished. self.assertFalse(self.client.auto_start_request) db = self.client.pymongo_test db.add_user("mike", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) try: self.assertFalse(self.client.in_request()) self.assertTrue(db.authenticate("mike", "password")) self.assertFalse(self.client.in_request()) request_cx = get_client(auto_start_request=True) request_db = request_cx.pymongo_test self.assertTrue(request_db.authenticate("mike", "password")) self.assertTrue(request_cx.in_request()) finally: db.authenticate("mike", "password") db.remove_user("mike") db.logout() request_db.logout()
def test_authenticate_and_safe(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if is_mongos(self.client): raise SkipTest("Auth fails on sharding due to write concern race, see Tokutek/mongo#77") if not server_started_with_auth(self.client): raise SkipTest('Authentication is not enabled on server') db = self.client.auth_test db.add_user("bernie", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) db.authenticate("bernie", "password") try: db.test.remove({}) self.assertTrue(db.test.insert({"bim": "baz"})) self.assertEqual(1, db.test.count()) self.assertEqual(1, db.test.update({"bim": "baz"}, {"$set": {"bim": "bar"}}).get('n')) self.assertEqual(1, db.test.remove({}).get('n')) self.assertEqual(0, db.test.count()) finally: db.remove_user("bernie") db.logout()
def test_authenticate_and_request(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if is_mongos(self.client): raise SkipTest("Auth fails on sharding due to write concern race, see Tokutek/mongo#77") if not server_started_with_auth(self.client): raise SkipTest('Authentication is not enabled on server') # Database.authenticate() needs to be in a request - check that it # always runs in a request, and that it restores the request state # (in or not in a request) properly when it's finished. self.assertFalse(self.client.auto_start_request) db = self.client.pymongo_test db.add_user("mike", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) try: self.assertFalse(self.client.in_request()) self.assertTrue(db.authenticate("mike", "password")) self.assertFalse(self.client.in_request()) request_cx = get_client(auto_start_request=True) request_db = request_cx.pymongo_test self.assertTrue(request_db.authenticate("mike", "password")) self.assertTrue(request_cx.in_request()) finally: db.authenticate("mike", "password") db.remove_user("mike") db.logout() request_db.logout()
def test_copy_db(self): c = Connection(self.host, self.port) self.assertTrue(c.in_request()) self.assertRaises(TypeError, c.copy_database, 4, "foo") self.assertRaises(TypeError, c.copy_database, "foo", 4) self.assertRaises(InvalidName, c.copy_database, "foo", "$foo") c.pymongo_test.test.drop() c.drop_database("pymongo_test1") c.drop_database("pymongo_test2") c.pymongo_test.test.insert({"foo": "bar"}) # Due to SERVER-2329, databases may not disappear from a master in a # master-slave pair if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) self.assertFalse("pymongo_test2" in c.database_names()) c.copy_database("pymongo_test", "pymongo_test1") # copy_database() didn't accidentally end the request self.assertTrue(c.in_request()) self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) c.end_request() self.assertFalse(c.in_request()) c.copy_database("pymongo_test", "pymongo_test2", "%s:%d" % (self.host, self.port)) # copy_database() didn't accidentally restart the request self.assertFalse(c.in_request()) self.assertTrue("pymongo_test2" in c.database_names()) self.assertEqual("bar", c.pymongo_test2.test.find_one()["foo"]) if version.at_least(c, (1, 3, 3, 1)): c.drop_database("pymongo_test1") c.pymongo_test.add_user("mike", "password") self.assertRaises( OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******" ) if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) self.assertRaises( OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******" ) if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) if not is_mongos(c): # See SERVER-6427 c.copy_database("pymongo_test", "pymongo_test1", username="******", password="******") self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])
def setUp(self): client = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(client) and not version.at_least(client, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(client): raise SkipTest('Authentication is not enabled on server') response = client.admin.command('ismaster') self.set_name = str(response.get('setName', '')) client.admin.add_user('admin', 'pass', roles=['userAdminAnyDatabase', 'dbAdminAnyDatabase', 'readWriteAnyDatabase', 'clusterAdmin']) client.admin.authenticate('admin', 'pass') client.pymongo_test.add_user('user', 'pass', roles=['userAdmin', 'readWrite']) if self.set_name: # GLE requires authentication. client.admin.authenticate('admin', 'pass') # Make sure the admin user is replicated after calling add_user # above. This avoids a race in the MRSC tests below. Adding a # user is just an insert into system.users. client.admin.command('getLastError', w=len(response['hosts'])) self.client = client
def test_copy_db(self): authed_client = auth_context.client if is_mongos(authed_client): raise SkipTest("SERVER-6427") c = MongoClient(host, port) authed_client.admin.add_user("admin", "password") c.admin.authenticate("admin", "password") c.drop_database("pymongo_test") c.drop_database("pymongo_test1") c.pymongo_test.test.insert({"foo": "bar"}) try: c.pymongo_test.add_user("mike", "password") self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") self.assertFalse("pymongo_test1" in c.database_names()) self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") self.assertFalse("pymongo_test1" in c.database_names()) c.copy_database("pymongo_test", "pymongo_test1", username="******", password="******") self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) finally: # Cleanup remove_all_users(c.pymongo_test) c.admin.remove_user("admin") c.disconnect()
def test_profiling_info(self): if is_mongos(self.client): raise SkipTest('profile is not supported by mongos') db = self.client.pymongo_test db.set_profiling_level(ALL) db.test.find_one() db.set_profiling_level(OFF) info = db.profiling_info() self.assertTrue(isinstance(info, list)) # Check if we're going to fail because of SERVER-4754, in which # profiling info isn't collected if mongod was started with --auth if server_started_with_auth(self.client): raise SkipTest( "We need SERVER-4754 fixed for the rest of this test to pass" ) self.assertTrue(len(info) >= 1) # These basically clue us in to server changes. if version.at_least(db.connection, (1, 9, 1, -1)): self.assertTrue(isinstance(info[0]['responseLength'], int)) self.assertTrue(isinstance(info[0]['millis'], int)) self.assertTrue(isinstance(info[0]['client'], basestring)) self.assertTrue(isinstance(info[0]['user'], basestring)) self.assertTrue(isinstance(info[0]['ns'], basestring)) self.assertTrue(isinstance(info[0]['op'], basestring)) else: self.assertTrue(isinstance(info[0]["info"], basestring)) self.assertTrue(isinstance(info[0]["millis"], float)) self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
def test_auth_from_uri(self): c = Connection(self.host, self.port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") c.admin.system.users.remove({}) c.pymongo_test.system.users.remove({}) c.admin.add_user("admin", "pass") c.admin.authenticate("admin", "pass") c.pymongo_test.add_user("user", "pass") self.assertRaises(ConfigurationError, Connection, "mongodb://*****:*****@%s:%d" % (self.host, self.port)) self.assertRaises(ConfigurationError, Connection, "mongodb://*****:*****@%s:%d" % (self.host, self.port)) self.assertRaises(ConfigurationError, Connection, "mongodb://*****:*****@%s:%d" % (self.host, self.port)) Connection("mongodb://*****:*****@%s:%d" % (self.host, self.port)) self.assertRaises(ConfigurationError, Connection, "mongodb://*****:*****@%s:%d/pymongo_test" % (self.host, self.port)) self.assertRaises(ConfigurationError, Connection, "mongodb://*****:*****@%s:%d/pymongo_test" % (self.host, self.port)) Connection("mongodb://*****:*****@%s:%d/pymongo_test" % (self.host, self.port)) c.admin.system.users.remove({}) c.pymongo_test.system.users.remove({})
def test_authenticate_and_request(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") # Database.authenticate() needs to be in a request - check that it # always runs in a request, and that it restores the request state # (in or not in a request) properly when it's finished. self.assertFalse(self.client.auto_start_request) db = self.client.pymongo_test remove_all_users(db) db.add_user("mike", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) self.assertFalse(self.client.in_request()) self.assertTrue(db.authenticate("mike", "password")) self.assertFalse(self.client.in_request()) request_cx = get_client(auto_start_request=True) request_db = request_cx.pymongo_test self.assertTrue(request_cx.in_request()) self.assertTrue(request_db.authenticate("mike", "password")) self.assertTrue(request_cx.in_request()) # just make sure there are no exceptions here db.remove_user("mike") db.logout() request_db.logout()
def find_slow(): if use_request: cx.start_request() history.append('find_slow start') # Javascript function that pauses N seconds per document fn = delay(10) if (is_mongos(db.connection) or not version.at_least(db.connection, (1, 7, 2))): # mongos doesn't support eval so we have to use $where # which is less reliable in this context. self.assertEqual(1, db.test.find({"$where": fn}).count()) else: # 'nolock' allows find_fast to start and finish while we're # waiting for this to complete. self.assertEqual({ 'ok': 1.0, 'retval': True }, db.command('eval', fn, nolock=True)) history.append('find_slow done') if use_request: cx.end_request()
def test_authenticate_and_safe(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") db = self.client.auth_test remove_all_users(db) db.add_user("bernie", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) db.authenticate("bernie", "password") db.test.remove({}) self.assertTrue(db.test.insert({"bim": "baz"})) self.assertEqual(1, db.test.count()) self.assertEqual(1, db.test.update({"bim": "baz"}, {"$set": {"bim": "bar"}}).get('n')) self.assertEqual(1, db.test.remove({}).get('n')) self.assertEqual(0, db.test.count()) db.remove_user("bernie") db.logout()
def test_only_secondary_ok_commands_have_read_prefs(self): c = get_connection(read_preference=ReadPreference.SECONDARY) is_mongos = utils.is_mongos(c) if not is_mongos: raise SkipTest("Only mongos have read_prefs added to the spec") # Ensure secondary_ok_commands have readPreference for cmd in secondary_ok_commands: if cmd == 'mapreduce': # map reduce is a special case continue command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) command['$readPreference'] = {'mode': 'secondary'} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce inline should have read prefs command = SON([('mapreduce', 'test'), ('out', {'inline': 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) command['$readPreference'] = {'mode': 'secondary'} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce that outputs to a collection shouldn't have read prefs command = SON([('mapreduce', 'test'), ('out', {'mrtest': 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec()) # Other commands shouldn't be changed for cmd in ('drop', 'create', 'any-future-cmd'): command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec())
def test_fsync_lock_unlock(self): c = get_client() if is_mongos(c): raise SkipTest('fsync/lock not supported by mongos') if not version.at_least(c, (2, 0)) and server_started_with_auth(c): raise SkipTest('Requires server >= 2.0 to test with auth') res = c.admin.command('getCmdLineOpts') if '--master' in res['argv'] and version.at_least(c, (2, 3, 0)): raise SkipTest('SERVER-7714') self.assertFalse(c.is_locked) # async flushing not supported on windows... if sys.platform not in ('cygwin', 'win32'): c.fsync(async=True) self.assertFalse(c.is_locked) c.fsync(lock=True) self.assertTrue(c.is_locked) locked = True c.unlock() for _ in xrange(5): locked = c.is_locked if not locked: break time.sleep(1) self.assertFalse(locked)
def test_authenticate_and_safe(self): if (is_mongos(self.connection) and not version.at_least(self.connection, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") db = self.connection.auth_test db.system.users.remove({}) db.add_user("bernie", "password") db.authenticate("bernie", "password") db.test.remove({}) self.assertTrue(db.test.insert({"bim": "baz"}, safe=True)) self.assertEqual(1, db.test.count()) self.assertEqual( 1, db.test.update({ "bim": "baz" }, { "$set": { "bim": "bar" } }, safe=True).get('n')) self.assertEqual(1, db.test.remove({}, safe=True).get('n')) self.assertEqual(0, db.test.count()) self.connection.drop_database("auth_test")
def test_only_secondary_ok_commands_have_read_prefs(self): c = get_connection(read_preference=ReadPreference.SECONDARY) is_mongos = utils.is_mongos(c) if not is_mongos: raise SkipTest("Only mongos have read_prefs added to the spec") # Ensure secondary_ok_commands have readPreference for cmd in secondary_ok_commands: if cmd == "mapreduce": # map reduce is a special case continue command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) # White-listed commands also have to be wrapped in $query command = SON([("$query", command)]) command["$readPreference"] = {"mode": "secondary"} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce inline should have read prefs command = SON([("mapreduce", "test"), ("out", {"inline": 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) # White-listed commands also have to be wrapped in $query command = SON([("$query", command)]) command["$readPreference"] = {"mode": "secondary"} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce that outputs to a collection shouldn't have read prefs command = SON([("mapreduce", "test"), ("out", {"mrtest": 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec()) # Other commands shouldn't be changed for cmd in ("drop", "create", "any-future-cmd"): command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec())
def test_only_secondary_ok_commands_have_read_prefs(self): c = get_client(read_preference=ReadPreference.SECONDARY) is_mongos = utils.is_mongos(c) if not is_mongos: raise SkipTest("Only mongos have read_prefs added to the spec") # Ensure secondary_ok_commands have readPreference for cmd in secondary_ok_commands: if cmd == 'mapreduce': # map reduce is a special case continue command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) # White-listed commands also have to be wrapped in $query command = SON([('$query', command)]) command['$readPreference'] = {'mode': 'secondary'} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce inline should have read prefs command = SON([('mapreduce', 'test'), ('out', {'inline': 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) # White-listed commands also have to be wrapped in $query command = SON([('$query', command)]) command['$readPreference'] = {'mode': 'secondary'} self.assertEqual(command, cursor._Cursor__query_spec()) # map_reduce that outputs to a collection shouldn't have read prefs command = SON([('mapreduce', 'test'), ('out', {'mrtest': 1})]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec()) # Other commands shouldn't be changed for cmd in ('drop', 'create', 'any-future-cmd'): command = SON([(cmd, 1)]) cursor = c.pymongo_test["$cmd"].find(command.copy()) self.assertEqual(command, cursor._Cursor__query_spec())
def setUpModule(): if not auth_context.auth_enabled: raise SkipTest("Server not started with --auth.") if (is_mongos(auth_context.client) and not version.at_least(auth_context.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") auth_context.add_user_and_log_in()
def test_authenticate_and_request(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") # Database.authenticate() needs to be in a request - check that it # always runs in a request, and that it restores the request state # (in or not in a request) properly when it's finished. self.assertFalse(self.client.auto_start_request) db = self.client.pymongo_test db.system.users.remove({}) db.remove_user("mike") db.add_user("mike", "password") self.assertFalse(self.client.in_request()) self.assertTrue(db.authenticate("mike", "password")) self.assertFalse(self.client.in_request()) request_cx = get_client(auto_start_request=True) request_db = request_cx.pymongo_test self.assertTrue(request_cx.in_request()) self.assertTrue(request_db.authenticate("mike", "password")) self.assertTrue(request_cx.in_request()) # just make sure there are no exceptions here db.logout() db.collection.find_one() request_db.logout() request_db.collection.find_one()
def test_authenticate_and_request(self): if (is_mongos(self.connection) and not version.at_least(self.connection, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") # Database.authenticate() needs to be in a request - check that it # always runs in a request, and that it restores the request state # (in or not in a request) properly when it's finished. self.assertTrue(self.connection.auto_start_request) db = self.connection.pymongo_test db.system.users.remove({}) db.remove_user("mike") db.add_user("mike", "password") self.assertTrue(self.connection.in_request()) self.assertTrue(db.authenticate("mike", "password")) self.assertTrue(self.connection.in_request()) no_request_cx = get_connection(auto_start_request=False) no_request_db = no_request_cx.pymongo_test self.assertFalse(no_request_cx.in_request()) self.assertTrue(no_request_db.authenticate("mike", "password")) self.assertFalse(no_request_cx.in_request()) # just make sure there are no exceptions here db.logout() no_request_db.logout()
def test_profiling_levels(self): if is_mongos(self.client): raise SkipTest('profile is not supported by mongos') db = self.client.pymongo_test self.assertEqual(db.profiling_level(), OFF) # default self.assertRaises(ValueError, db.set_profiling_level, 5.5) self.assertRaises(ValueError, db.set_profiling_level, None) self.assertRaises(ValueError, db.set_profiling_level, -1) self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, 5.5) self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, '1') db.set_profiling_level(SLOW_ONLY) self.assertEqual(db.profiling_level(), SLOW_ONLY) db.set_profiling_level(ALL) self.assertEqual(db.profiling_level(), ALL) db.set_profiling_level(OFF) self.assertEqual(db.profiling_level(), OFF) db.set_profiling_level(SLOW_ONLY, 50) self.assertEqual(50, db.command("profile", -1)['slowms']) db.set_profiling_level(ALL, -1) self.assertEqual(-1, db.command("profile", -1)['slowms']) db.set_profiling_level(OFF, 100) # back to default self.assertEqual(100, db.command("profile", -1)['slowms'])
def test_errors(self): if is_mongos(self.connection): raise SkipTest('getpreverror not supported by mongos') db = self.connection.pymongo_test db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) self.assertTrue(db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) prev_error = db.previous_error() self.assertEqual(prev_error["nPrev"], 1) del prev_error["nPrev"] prev_error.pop("lastOp", None) error = db.error() error.pop("lastOp", None) # getLastError includes "connectionId" in recent # server versions, getPrevError does not. error.pop("connectionId", None) self.assertEqual(error, prev_error) db.test.find_one() self.assertEqual(None, db.error()) self.assertTrue(db.previous_error()) self.assertEqual(db.previous_error()["nPrev"], 2) db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error())
def test_auth_from_uri(self): c = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") c.admin.system.users.remove({}) c.pymongo_test.system.users.remove({}) c.admin.add_user("admin", "pass") c.admin.authenticate("admin", "pass") c.pymongo_test.add_user("user", "pass") self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) c.admin.system.users.remove({}) c.pymongo_test.system.users.remove({})
def test_authenticate_and_safe(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(self.client): raise SkipTest('Authentication is not enabled on server') db = self.client.auth_test db.add_user("bernie", "password", roles=["userAdmin", "dbAdmin", "readWrite"]) db.authenticate("bernie", "password") try: db.test.remove({}) self.assertTrue(db.test.insert({"bim": "baz"})) self.assertEqual(1, db.test.count()) self.assertEqual(1, db.test.update({"bim": "baz"}, {"$set": {"bim": "bar"}}).get('n')) self.assertEqual(1, db.test.remove({}).get('n')) self.assertEqual(0, db.test.count()) finally: db.remove_user("bernie") db.logout()
def test_profiling_levels(self): if is_mongos(self.connection): raise SkipTest('profile is not supported by mongos') db = self.connection.pymongo_test self.assertEqual(db.profiling_level(), OFF) # default self.assertRaises(ValueError, db.set_profiling_level, 5.5) self.assertRaises(ValueError, db.set_profiling_level, None) self.assertRaises(ValueError, db.set_profiling_level, -1) self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, 5.5) self.assertRaises(TypeError, db.set_profiling_level, SLOW_ONLY, '1') db.set_profiling_level(SLOW_ONLY) self.assertEqual(db.profiling_level(), SLOW_ONLY) db.set_profiling_level(ALL) self.assertEqual(db.profiling_level(), ALL) db.set_profiling_level(OFF) self.assertEqual(db.profiling_level(), OFF) db.set_profiling_level(SLOW_ONLY, 50) self.assertEqual(50, db.command("profile", -1)['slowms']) db.set_profiling_level(ALL, -1) self.assertEqual(-1, db.command("profile", -1)['slowms']) db.set_profiling_level(OFF, 100) # back to default self.assertEqual(100, db.command("profile", -1)['slowms'])
def test_errors(self): if is_mongos(self.client): raise SkipTest('getpreverror not supported by mongos') db = self.client.pymongo_test db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) self.assertTrue(db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) prev_error = db.previous_error() self.assertEqual(prev_error["nPrev"], 1) del prev_error["nPrev"] prev_error.pop("lastOp", None) error = db.error() error.pop("lastOp", None) # getLastError includes "connectionId" in recent # server versions, getPrevError does not. error.pop("connectionId", None) self.assertEqual(error, prev_error) db.test.find_one() self.assertEqual(None, db.error()) self.assertTrue(db.previous_error()) self.assertEqual(db.previous_error()["nPrev"], 2) db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error())
def test_profiling_info(self): if is_mongos(self.connection): raise SkipTest('profile is not supported by mongos') db = self.connection.pymongo_test db.set_profiling_level(ALL) db.test.find() db.set_profiling_level(OFF) info = db.profiling_info() self.assertTrue(isinstance(info, list)) # Check if we're going to fail because of SERVER-4754, in which # profiling info isn't collected if mongod was started with --auth if server_started_with_auth(self.connection): raise SkipTest( "We need SERVER-4754 fixed for the rest of this test to pass") self.assertTrue(len(info) >= 1) # These basically clue us in to server changes. if version.at_least(db.connection, (1, 9, 1, -1)): self.assertTrue(isinstance(info[0]['responseLength'], int)) self.assertTrue(isinstance(info[0]['millis'], int)) self.assertTrue(isinstance(info[0]['client'], basestring)) self.assertTrue(isinstance(info[0]['user'], basestring)) self.assertTrue(isinstance(info[0]['ntoreturn'], int)) self.assertTrue(isinstance(info[0]['ns'], basestring)) self.assertTrue(isinstance(info[0]['op'], basestring)) else: self.assertTrue(isinstance(info[0]["info"], basestring)) self.assertTrue(isinstance(info[0]["millis"], float)) self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
def test_auth_from_uri(self): c = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") remove_all_users(c.pymongo_test) remove_all_users(c.admin) try: c.admin.add_user("admin", "pass", roles=[ 'readWriteAnyDatabase', 'userAdminAnyDatabase', 'dbAdminAnyDatabase', 'userAdmin' ]) c.admin.authenticate("admin", "pass") c.pymongo_test.add_user("user", "pass", roles=['userAdmin', 'readWrite']) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) # Auth with lazy connection. MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False).pymongo_test.test.find_one() # Wrong password. bad_client = MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) # If auth fails with lazy connection, MongoClient raises # AutoReconnect instead of the more appropriate OperationFailure, # PYTHON-517. self.assertRaises(PyMongoError, bad_client.pymongo_test.test.find_one) finally: # Clean up. remove_all_users(c.pymongo_test) remove_all_users(c.admin)
def test_mongos_connection(self): c = get_connection() is_mongos = utils.is_mongos(c) # Test default mode, PRIMARY cursor = c.pymongo_test.test.find() if is_mongos: self.assertEqual( {'mode': 'primary'}, cursor._Cursor__query_spec().get('$readPreference') ) else: self.assertFalse( '$readPreference' in cursor._Cursor__query_spec()) # Test non-PRIMARY modes which can be combined with tags for mode, mongos_mode in ( (ReadPreference.PRIMARY_PREFERRED, 'primaryPreferred'), (ReadPreference.SECONDARY, 'secondary'), (ReadPreference.SECONDARY_PREFERRED, 'secondaryPreferred'), (ReadPreference.NEAREST, 'nearest'), ): for tag_sets in ( None, [{}] ): c = get_connection( read_preference=mode, tag_sets=tag_sets) self.assertEqual(is_mongos, c.is_mongos) cursor = c.pymongo_test.test.find() if is_mongos: self.assertEqual( {'mode': mongos_mode}, cursor._Cursor__query_spec().get('$readPreference') ) else: self.assertFalse( '$readPreference' in cursor._Cursor__query_spec()) for tag_sets in ( [{'dc': 'la'}], [{'dc': 'la'}, {'dc': 'sf'}], [{'dc': 'la'}, {'dc': 'sf'}, {}], ): c = get_connection( read_preference=mode, tag_sets=tag_sets) self.assertEqual(is_mongos, c.is_mongos) cursor = c.pymongo_test.test.find() if is_mongos: self.assertEqual( {'mode': mongos_mode, 'tags': tag_sets}, cursor._Cursor__query_spec().get('$readPreference')) else: self.assertFalse( '$readPreference' in cursor._Cursor__query_spec())
def test_authenticate_multiple(self): client = get_client() if is_mongos(client) and not version.at_least(self.client, (2, 2, 0)): raise SkipTest("Need mongos >= 2.2.0") if not server_started_with_auth(client): raise SkipTest("Authentication is not enabled on server") # Setup users_db = client.pymongo_test admin_db = client.admin other_db = client.pymongo_test1 users_db.test.remove() other_db.test.remove() admin_db.add_user("admin", "pass", roles=["userAdminAnyDatabase", "dbAdmin", "clusterAdmin", "readWrite"]) try: self.assertTrue(admin_db.authenticate("admin", "pass")) if version.at_least(self.client, (2, 5, 3, -1)): admin_db.add_user("ro-admin", "pass", roles=["userAdmin", "readAnyDatabase"]) else: admin_db.add_user("ro-admin", "pass", read_only=True) users_db.add_user("user", "pass", roles=["userAdmin", "readWrite"]) admin_db.logout() self.assertRaises(OperationFailure, users_db.test.find_one) # Regular user should be able to query its own db, but # no other. users_db.authenticate("user", "pass") self.assertEqual(0, users_db.test.count()) self.assertRaises(OperationFailure, other_db.test.find_one) # Admin read-only user should be able to query any db, # but not write. admin_db.authenticate("ro-admin", "pass") self.assertEqual(0, other_db.test.count()) self.assertRaises(OperationFailure, other_db.test.insert, {}) # Force close all sockets client.disconnect() # We should still be able to write to the regular user's db self.assertTrue(users_db.test.remove()) # And read from other dbs... self.assertEqual(0, other_db.test.count()) # But still not write to other dbs... self.assertRaises(OperationFailure, other_db.test.insert, {}) # Cleanup finally: admin_db.logout() users_db.logout() admin_db.authenticate("admin", "pass") remove_all_users(users_db) remove_all_users(admin_db)
def test_authenticate_multiple(self): client = get_client() if (is_mongos(client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(client): raise SkipTest("Authentication is not enabled on server") # Setup users_db = client.pymongo_test admin_db = client.admin other_db = client.pymongo_test1 users_db.system.users.remove() admin_db.system.users.remove() users_db.test.remove() other_db.test.remove() admin_db.add_user('admin', 'pass') self.assertTrue(admin_db.authenticate('admin', 'pass')) admin_db.add_user('ro-admin', 'pass', read_only=True) users_db.add_user('user', 'pass') admin_db.logout() self.assertRaises(OperationFailure, users_db.test.find_one) # Regular user should be able to query its own db, but # no other. users_db.authenticate('user', 'pass') self.assertEqual(0, users_db.test.count()) self.assertRaises(OperationFailure, other_db.test.find_one) # Admin read-only user should be able to query any db, # but not write. admin_db.authenticate('ro-admin', 'pass') self.assertEqual(0, other_db.test.count()) self.assertRaises(OperationFailure, other_db.test.insert, {}) # Force close all sockets client.disconnect() # We should still be able to write to the regular user's db self.assertTrue(users_db.test.remove()) # And read from other dbs... self.assertEqual(0, other_db.test.count()) # But still not write to other dbs... self.assertRaises(OperationFailure, other_db.test.insert, {}) # Cleanup admin_db.logout() users_db.logout() self.assertTrue(admin_db.authenticate('admin', 'pass')) self.assertTrue(admin_db.system.users.remove()) self.assertEqual(0, admin_db.system.users.count()) self.assertTrue(users_db.system.users.remove())
def test_comment(self): if is_mongos(self.client): raise SkipTest("profile is not supported by mongos") if not version.at_least(self.db.connection, (2, 0)): raise SkipTest("Requires server >= 2.0") if server_started_with_auth(self.db.connection): raise SkipTest("SERVER-4754 - This test uses profiling.") def run_with_profiling(func): self.db.set_profiling_level(OFF) self.db.system.profile.drop() self.db.set_profiling_level(ALL) func() self.db.set_profiling_level(OFF) def find(): list(self.db.test.find().comment('foo')) op = self.db.system.profile.find({ 'ns': 'pymongo_test.test', 'op': 'query', 'query.$comment': 'foo' }) self.assertEqual(op.count(), 1) run_with_profiling(find) def count(): self.db.test.find().comment('foo').count() op = self.db.system.profile.find({ 'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.count': 'test', 'command.$comment': 'foo' }) self.assertEqual(op.count(), 1) run_with_profiling(count) def distinct(): self.db.test.find().comment('foo').distinct('type') op = self.db.system.profile.find({ 'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.distinct': 'test', 'command.$comment': 'foo' }) self.assertEqual(op.count(), 1) run_with_profiling(distinct) self.db.test.insert([{}, {}]) cursor = self.db.test.find() cursor.next() self.assertRaises(InvalidOperation, cursor.comment, 'hello') self.db.system.profile.drop()
def test_auth_from_uri(self): c = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") remove_all_users(c.pymongo_test) remove_all_users(c.admin) try: c.admin.add_user("admin", "pass", roles=['readWriteAnyDatabase', 'userAdminAnyDatabase', 'dbAdminAnyDatabase', 'userAdmin']) c.admin.authenticate("admin", "pass") c.pymongo_test.add_user("user", "pass", roles=['userAdmin', 'readWrite']) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) # Auth with lazy connection. MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False).pymongo_test.test.find_one() # Wrong password. bad_client = MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) # If auth fails with lazy connection, MongoClient raises # AutoReconnect instead of the more appropriate OperationFailure, # PYTHON-517. self.assertRaises( PyMongoError, bad_client.pymongo_test.test.find_one) finally: # Clean up. remove_all_users(c.pymongo_test) remove_all_users(c.admin)
def setUp(self): client = MongoClient(HOST, PORT) # Sharded auth not supported before MongoDB 2.0 if is_mongos(client) and not version.at_least(client, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(client): raise SkipTest('Authentication is not enabled on server') self.set_name = client.admin.command('ismaster').get('setName') client.pymongo_test.add_user('user', 'pass') client.admin.add_user('admin', 'pass') self.client = client
def test_lazy_auth_raises_operation_failure(self): # Check if we have the prerequisites to run this test. c = MongoClient(host, port) if not server_started_with_auth(c): raise SkipTest("Authentication is not enabled on server") if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") lazy_client = MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) assertRaisesExactly(OperationFailure, lazy_client.test.collection.find_one)
def test_comment(self): if is_mongos(self.client): raise SkipTest("profile is not supported by mongos") if not version.at_least(self.db.connection, (2, 0)): raise SkipTest("Requires server >= 2.0") if server_started_with_auth(self.db.connection): raise SkipTest("SERVER-4754 - This test uses profiling.") def run_with_profiling(func): self.db.set_profiling_level(OFF) self.db.system.profile.drop() self.db.set_profiling_level(ALL) func() self.db.set_profiling_level(OFF) def find(): list(self.db.test.find().comment('foo')) op = self.db.system.profile.find({'ns': 'pymongo_test.test', 'op': 'query', 'query.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(find) def count(): self.db.test.find().comment('foo').count() op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.count': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(count) def distinct(): self.db.test.find().comment('foo').distinct('type') op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.distinct': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(distinct) self.db.test.insert([{}, {}]) cursor = self.db.test.find() cursor.next() self.assertRaises(InvalidOperation, cursor.comment, 'hello') self.db.system.profile.drop()
def test_auth_from_uri(self): c = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(c): raise SkipTest('Authentication is not enabled on server') c.admin.add_user("admin", "pass") c.admin.authenticate("admin", "pass") try: c.pymongo_test.add_user("user", "pass", roles=['userAdmin', 'readWrite']) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) self.assertRaises( ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) # Auth with lazy connection. MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False).pymongo_test.test.find_one() # Wrong password. bad_client = MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) self.assertRaises(OperationFailure, bad_client.pymongo_test.test.find_one) finally: # Clean up. remove_all_users(c.pymongo_test) remove_all_users(c.admin)
def test_lazy_auth_raises_operation_failure(self): # Check if we have the prerequisites to run this test. c = MongoClient(host, port) if not server_started_with_auth(c): raise SkipTest('Authentication is not enabled on server') if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") lazy_client = MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) assertRaisesExactly(OperationFailure, lazy_client.test.collection.find_one)
def test_authenticate_add_remove_user(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if version.at_least(self.client, (2, 5, 3, -1)): raise SkipTest("Legacy user manipulation requires MongoDB < 2.5.3") db = self.client.pymongo_test db.system.users.remove({}) db.remove_user("mike") self.assertRaises(TypeError, db.add_user, "user", '') self.assertRaises(TypeError, db.add_user, "user", 'password', 15) self.assertRaises(ConfigurationError, db.add_user, "user", 'password', 'True') db.add_user("mike", "password") self.assertRaises(TypeError, db.authenticate, 5, "password") self.assertRaises(TypeError, db.authenticate, "mike", 5) self.assertRaises(OperationFailure, db.authenticate, "mike", "not a real password") self.assertRaises(OperationFailure, db.authenticate, "faker", "password") self.assertTrue(db.authenticate("mike", "password")) self.assertTrue(db.authenticate(u"mike", u"password")) db.logout() db.remove_user("mike") self.assertRaises(OperationFailure, db.authenticate, "mike", "password") self.assertRaises(OperationFailure, db.authenticate, "Gustave", u"Dor\xe9") db.add_user("Gustave", u"Dor\xe9") self.assertTrue(db.authenticate("Gustave", u"Dor\xe9")) db.logout() db.add_user("Gustave", "password") self.assertRaises(OperationFailure, db.authenticate, "Gustave", u"Dor\xe9") self.assertTrue(db.authenticate("Gustave", u"password")) db.logout() db.add_user("Ross", "password", read_only=True) self.assertTrue(db.authenticate("Ross", u"password")) self.assertTrue(db.system.users.find({"readOnly": True}).count()) db.logout()
def test_command_ignores_network_timeout(self): # command() should ignore network_timeout. if not version.at_least(self.client, (1, 9, 0)): raise SkipTest("Need sleep() to test command with network timeout") db = self.client.pymongo_test # No errors. db.test.remove() db.test.insert({}) cursor = db.test.find({"$where": "sleep(100); return true"}, network_timeout=0.001) self.assertEqual(1, cursor.count()) # mongos doesn't support the eval command if not is_mongos(self.client): db.command("eval", "sleep(100)", network_timeout=0.001)
def test_auth_from_uri(self): c = MongoClient(host, port) # Sharded auth not supported before MongoDB 2.0 if is_mongos(c) and not version.at_least(c, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") if not server_started_with_auth(c): raise SkipTest('Authentication is not enabled on server') c.admin.add_user("admin", "pass") c.admin.authenticate("admin", "pass") try: c.pymongo_test.add_user("user", "pass", roles=['userAdmin', 'readWrite']) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) self.assertRaises(ConfigurationError, MongoClient, "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)) # Auth with lazy connection. MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False).pymongo_test.test.find_one() # Wrong password. bad_client = MongoClient( "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False) self.assertRaises(OperationFailure, bad_client.pymongo_test.test.find_one) finally: # Clean up. remove_all_users(c.pymongo_test) remove_all_users(c.admin)
def test_comment(self): if is_mongos(self.client): raise SkipTest("profile is not supported by mongos") def run_with_profiling(func): self.db.set_profiling_level(OFF) self.db.system.profile.drop() self.db.set_profiling_level(ALL) func() self.db.set_profiling_level(OFF) def find(): list(self.db.test.find().comment('foo')) op = self.db.system.profile.find({'ns': 'pymongo_test.test', 'op': 'query', 'query.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(find) def count(): self.db.test.find().comment('foo').count() op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.count': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(count) def distinct(): self.db.test.find().comment('foo').distinct('type') op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd', 'op': 'command', 'command.distinct': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) run_with_profiling(distinct) self.db.test.insert([{}, {}]) cursor = self.db.test.find() cursor.next() self.assertRaises(InvalidOperation, cursor.comment, 'hello') self.db.system.profile.drop()
def test_comment(self): if is_mongos(self.client): raise SkipTest("profile is not supported by mongos") if not version.at_least(self.db.connection, (2, 0)): raise SkipTest("Requires server >= 2.0") if server_started_with_auth(self.db.connection): raise SkipTest("SERVER-4754 - This test uses profiling.") # MongoDB 3.1.5 changed the ns for commands. regex = {'$regex': 'pymongo_test.(\$cmd|test)'} if version.at_least(self.db.connection, (3, 1, 8, -1)): query_key = "query.comment" else: query_key = "query.$comment" self.client.drop_database(self.db) self.db.set_profiling_level(ALL) try: list(self.db.test.find().comment('foo')) op = self.db.system.profile.find({'ns': 'pymongo_test.test', 'op': 'query', query_key: 'foo'}) self.assertEqual(op.count(), 1) self.db.test.find().comment('foo').count() op = self.db.system.profile.find({'ns': regex, 'op': 'command', 'command.count': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) self.db.test.find().comment('foo').distinct('type') op = self.db.system.profile.find({'ns': regex, 'op': 'command', 'command.distinct': 'test', 'command.$comment': 'foo'}) self.assertEqual(op.count(), 1) finally: self.db.set_profiling_level(OFF) self.db.system.profile.drop() self.db.test.insert([{}, {}]) cursor = self.db.test.find() cursor.next() self.assertRaises(InvalidOperation, cursor.comment, 'hello')
def test_authenticate_add_remove_user(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") db = self.client.pymongo_test db.system.users.remove({}) db.remove_user("mike") self.assertRaises(TypeError, db.add_user, "user", '') self.assertRaises(TypeError, db.add_user, "user", 'password', 15) self.assertRaises(ConfigurationError, db.add_user, "user", 'password', 'True') db.add_user("mike", "password") self.assertRaises(TypeError, db.authenticate, 5, "password") self.assertRaises(TypeError, db.authenticate, "mike", 5) self.assertRaises(OperationFailure, db.authenticate, "mike", "not a real password") self.assertRaises(OperationFailure, db.authenticate, "faker", "password") self.assertTrue(db.authenticate("mike", "password")) self.assertTrue(db.authenticate(u"mike", u"password")) db.logout() db.remove_user("mike") self.assertRaises(OperationFailure, db.authenticate, "mike", "password") self.assertRaises(OperationFailure, db.authenticate, "Gustave", u"Dor\xe9") db.add_user("Gustave", u"Dor\xe9") self.assertTrue(db.authenticate("Gustave", u"Dor\xe9")) db.logout() db.add_user("Gustave", "password") self.assertRaises(OperationFailure, db.authenticate, "Gustave", u"Dor\xe9") self.assertTrue(db.authenticate("Gustave", u"password")) db.logout() db.add_user("Ross", "password", read_only=True) self.assertTrue(db.authenticate("Ross", u"password")) self.assertTrue(db.system.users.find({"readOnly": True}).count()) db.logout()
def test_command_ignores_network_timeout(self): # command() should ignore network_timeout. if not version.at_least(self.client, (1, 9, 0)): raise SkipTest("Need sleep() to test command with network timeout") db = self.client.pymongo_test # No errors. db.test.remove() db.test.insert({}) cursor = db.test.find( {'$where': 'sleep(100); return true'}, network_timeout=0.001) self.assertEqual(1, cursor.count()) # mongos doesn't support the eval command if not is_mongos(self.client): db.command('eval', 'sleep(100)', network_timeout=0.001)
def test_copy_db(self): authed_client = auth_context.client if version.at_least(authed_client, (2, 7, 2)): raise SkipTest("SERVER-17034") if is_mongos(authed_client): raise SkipTest("SERVER-6427") c = MongoClient(host, port) authed_client.admin.add_user("admin", "password") c.admin.authenticate("admin", "password") c.drop_database("pymongo_test") c.drop_database("pymongo_test1") c.pymongo_test.test.insert({"foo": "bar"}) try: c.pymongo_test.add_user("mike", "password") self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") self.assertFalse("pymongo_test1" in c.database_names()) self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") self.assertFalse("pymongo_test1" in c.database_names()) c.copy_database("pymongo_test", "pymongo_test1", username="******", password="******") self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) finally: # Cleanup remove_all_users(c.pymongo_test) c.admin.remove_user("admin") c.disconnect()
def test_authenticate_and_safe(self): if is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0)): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") db = self.client.auth_test db.system.users.remove({}) db.add_user("bernie", "password") db.authenticate("bernie", "password") db.test.remove({}) self.assertTrue(db.test.insert({"bim": "baz"})) self.assertEqual(1, db.test.count()) self.assertEqual(1, db.test.update({"bim": "baz"}, {"$set": {"bim": "bar"}}).get("n")) self.assertEqual(1, db.test.remove({}).get("n")) self.assertEqual(0, db.test.count()) self.client.drop_database("auth_test")
def test_profiling_levels(self): if is_mongos(self.connection): raise SkipTest('profile is not supported by mongos') db = self.connection.pymongo_test self.assertEqual(db.profiling_level(), OFF) # default self.assertRaises(ValueError, db.set_profiling_level, 5.5) self.assertRaises(ValueError, db.set_profiling_level, None) self.assertRaises(ValueError, db.set_profiling_level, -1) db.set_profiling_level(SLOW_ONLY) self.assertEqual(db.profiling_level(), SLOW_ONLY) db.set_profiling_level(ALL) self.assertEqual(db.profiling_level(), ALL) db.set_profiling_level(OFF) self.assertEqual(db.profiling_level(), OFF)
def test_fsync_lock_unlock(self): c = get_connection() if is_mongos(c): raise SkipTest('fsync/lock not supported by mongos') self.assertFalse(c.is_locked) # async flushing not supported on windows... if sys.platform not in ('cygwin', 'win32'): c.fsync(async=True) self.assertFalse(c.is_locked) c.fsync(lock=True) self.assertTrue(c.is_locked) locked = True c.unlock() for _ in xrange(5): locked = c.is_locked if not locked: break time.sleep(1) self.assertFalse(locked)
def test_authenticate_add_remove_user(self): if (is_mongos(self.connection) and not version.at_least(self.connection, (2, 0, 0))): raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0") db = self.connection.pymongo_test db.system.users.remove({}) db.remove_user("mike") self.assertRaises(TypeError, db.add_user, "user", None) self.assertRaises(TypeError, db.add_user, "user", '') self.assertRaises(TypeError, db.add_user, "user", 'password', None) self.assertRaises(ConfigurationError, db.add_user, "user", 'password', 'True') db.add_user("mike", "password") self.assertRaises(TypeError, db.authenticate, 5, "password") self.assertRaises(TypeError, db.authenticate, "mike", 5) self.assertFalse(db.authenticate("mike", "not a real password")) self.assertFalse(db.authenticate("faker", "password")) self.assertTrue(db.authenticate("mike", "password")) self.assertTrue(db.authenticate(u"mike", u"password")) db.remove_user("mike") self.assertFalse(db.authenticate("mike", "password")) self.assertFalse(db.authenticate("Gustave", u"Dor\xe9")) db.add_user("Gustave", u"Dor\xe9") self.assertTrue(db.authenticate("Gustave", u"Dor\xe9")) db.add_user("Gustave", "password") self.assertFalse(db.authenticate("Gustave", u"Dor\xe9")) self.assertTrue(db.authenticate("Gustave", u"password")) db.add_user("Ross", "password", read_only=True) self.assertTrue(db.authenticate("Ross", u"password")) self.assertTrue(db.system.users.find({"readOnly": True}).count()) # just make sure there are no exceptions here db.logout() db.logout()
def test_copy_db(self): c = MongoClient(host, port) # Due to SERVER-2329, databases may not disappear # from a master in a master-slave pair. if server_is_master_with_slave(c): raise SkipTest("SERVER-2329") ctx = catch_warnings() try: warnings.simplefilter("ignore", DeprecationWarning) self.assertRaises(TypeError, c.copy_database, 4, "foo") self.assertRaises(TypeError, c.copy_database, "foo", 4) self.assertRaises(InvalidName, c.copy_database, "foo", "$foo") c.pymongo_test.test.drop() c.pymongo_test.test.insert({"foo": "bar"}) c.drop_database("pymongo_test1") self.assertFalse("pymongo_test1" in c.database_names()) c.copy_database("pymongo_test", "pymongo_test1") self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) c.drop_database("pymongo_test1") # XXX - SERVER-15318 if not (version.at_least(c, (2, 6, 4)) and is_mongos(c)): self.assertFalse(c.in_request()) c.copy_database("pymongo_test", "pymongo_test1", "%s:%d" % (host, port)) # copy_database() didn't accidentally restart the request self.assertFalse(c.in_request()) self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) c.drop_database("pymongo_test1") finally: ctx.exit()
def test_errors(self): if is_mongos(self.client): raise SkipTest('getpreverror not supported by mongos') db = self.client.pymongo_test ctx = catch_warnings() try: warnings.simplefilter("ignore", DeprecationWarning) db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) self.assertTrue(db.previous_error()) db.command("forceerror", check=False) self.assertTrue(db.error()) prev_error = db.previous_error() self.assertEqual(prev_error["nPrev"], 1) del prev_error["nPrev"] prev_error.pop("lastOp", None) error = db.error() error.pop("lastOp", None) # getLastError includes "connectionId" in recent # server versions, getPrevError does not. error.pop("connectionId", None) self.assertEqual(error, prev_error) db.test.find_one() self.assertEqual(None, db.error()) self.assertTrue(db.previous_error()) self.assertEqual(db.previous_error()["nPrev"], 2) db.reset_error_history() self.assertEqual(None, db.error()) self.assertEqual(None, db.previous_error()) finally: ctx.exit()
def test_make_user_readonly(self): if (is_mongos(self.client) and not version.at_least(self.client, (2, 0, 0))): raise SkipTest('Auth with sharding requires MongoDB >= 2.0.0') if not server_started_with_auth(self.client): raise SkipTest('Authentication is not enabled on server') admin = self.client.admin admin.add_user('admin', 'pw') admin.authenticate('admin', 'pw') db = self.client.pymongo_test try: # Make a read-write user. db.add_user('jesse', 'pw') admin.logout() # Check that we're read-write by default. db.authenticate('jesse', 'pw') db.collection.insert({}) db.logout() # Make the user read-only. admin.authenticate('admin', 'pw') db.add_user('jesse', 'pw', read_only=True) admin.logout() db.authenticate('jesse', 'pw') self.assertRaises(OperationFailure, db.collection.insert, {}) finally: # Cleanup admin.authenticate('admin', 'pw') remove_all_users(db) admin.remove_user("admin") admin.logout()
def test_authenticate_multiple(self): client = get_client() authed_client = auth_context.client if (is_mongos(authed_client) and not version.at_least(authed_client, (2, 2, 0))): raise SkipTest("Need mongos >= 2.2.0") # Setup authed_client.pymongo_test.test.drop() authed_client.pymongo_test1.test.drop() users_db = client.pymongo_test admin_db = client.admin other_db = client.pymongo_test1 authed_client.admin.add_user('admin', 'pass', roles=[ "userAdminAnyDatabase", "dbAdmin", "clusterAdmin", "readWrite" ]) try: self.assertTrue(admin_db.authenticate('admin', 'pass')) if version.at_least(self.client, (2, 5, 3, -1)): admin_db.add_user('ro-admin', 'pass', roles=["userAdmin", "readAnyDatabase"]) else: admin_db.add_user('ro-admin', 'pass', read_only=True) users_db.add_user('user', 'pass', roles=["userAdmin", "readWrite"]) admin_db.logout() self.assertRaises(OperationFailure, users_db.test.find_one) # Regular user should be able to query its own db, but # no other. users_db.authenticate('user', 'pass') self.assertEqual(0, users_db.test.count()) self.assertRaises(OperationFailure, other_db.test.find_one) # Admin read-only user should be able to query any db, # but not write. admin_db.authenticate('ro-admin', 'pass') self.assertEqual(0, other_db.test.count()) self.assertRaises(OperationFailure, other_db.test.insert, {}) # Force close all sockets client.disconnect() # We should still be able to write to the regular user's db self.assertTrue(users_db.test.remove()) # And read from other dbs... self.assertEqual(0, other_db.test.count()) # But still not write to other dbs... self.assertRaises(OperationFailure, other_db.test.insert, {}) # Cleanup finally: admin_db.logout() users_db.logout() admin_db.authenticate('admin', 'pass') remove_all_users(users_db) admin_db.remove_user('ro-admin') admin_db.remove_user('admin')
def test_copy_db(self): c = MongoClient(host, port) # We test copy twice; once starting in a request and once not. In # either case the copy should succeed (because it starts a request # internally) and should leave us in the same state as before the copy. c.start_request() self.assertRaises(TypeError, c.copy_database, 4, "foo") self.assertRaises(TypeError, c.copy_database, "foo", 4) self.assertRaises(InvalidName, c.copy_database, "foo", "$foo") c.pymongo_test.test.drop() c.drop_database("pymongo_test1") c.drop_database("pymongo_test2") c.pymongo_test.test.insert({"foo": "bar"}) # Due to SERVER-2329, databases may not disappear from a master in a # master-slave pair if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) self.assertFalse("pymongo_test2" in c.database_names()) c.copy_database("pymongo_test", "pymongo_test1") # copy_database() didn't accidentally end the request self.assertTrue(c.in_request()) self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"]) c.end_request() self.assertFalse(c.in_request()) c.copy_database("pymongo_test", "pymongo_test2", "%s:%d" % (host, port)) # copy_database() didn't accidentally restart the request self.assertFalse(c.in_request()) self.assertTrue("pymongo_test2" in c.database_names()) self.assertEqual("bar", c.pymongo_test2.test.find_one()["foo"]) if version.at_least(c, (1, 3, 3, 1)): c.drop_database("pymongo_test1") c.pymongo_test.add_user("mike", "password") self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) self.assertRaises(OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******") if not server_is_master_with_slave(c): self.assertFalse("pymongo_test1" in c.database_names()) if not is_mongos(c): # See SERVER-6427 c.copy_database("pymongo_test", "pymongo_test1", username="******", password="******") self.assertTrue("pymongo_test1" in c.database_names()) self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])