Beispiel #1
0
    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 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()
Beispiel #2
0
    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_system_js(self):
        db = self.client.pymongo_test
        db.system.js.remove()

        self.assertEqual(0, db.system.js.count())
        db.system_js.add = "function(a, b) { return a + b; }"
        self.assertEqual('add', db.system.js.find_one()['_id'])
        self.assertEqual(1, db.system.js.count())
        self.assertEqual(6, db.system_js.add(1, 5))
        del db.system_js.add
        self.assertEqual(0, db.system.js.count())

        db.system_js['add'] = "function(a, b) { return a + b; }"
        self.assertEqual('add', db.system.js.find_one()['_id'])
        self.assertEqual(1, db.system.js.count())
        self.assertEqual(6, db.system_js['add'](1, 5))
        del db.system_js['add']
        self.assertEqual(0, db.system.js.count())

        if version.at_least(db.connection, (1, 3, 2, -1)):
            self.assertRaises(OperationFailure, db.system_js.add, 1, 5)

        # TODO right now CodeWScope doesn't work w/ system js
        # db.system_js.scope = Code("return hello;", {"hello": 8})
        # self.assertEqual(8, db.system_js.scope())

        self.assertRaises(OperationFailure, db.system_js.non_existant)

        # XXX: Broken in V8, works in SpiderMonkey
        # Use 1.2.9999 instead of 1.3.0 in order to catch 1.3.0-pre-
        if not version.tokumx_at_least(db.connection, (1, 2, 9999)):
            db.system_js.no_param = Code("return 5;")
            self.assertEqual(5, db.system_js.no_param())
    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_distinct(self):
        if not version.at_least(self.db.connection, (1, 1)):
            raise SkipTest()

        self.db.drop_collection("test")

        self.db.test.save({"a": 1})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 3})

        distinct = self.db.test.distinct("a")
        distinct.sort()

        self.assertEqual([1, 2, 3], distinct)

        self.db.drop_collection("test")

        self.db.test.save({"a": {"b": "a"}, "c": 12})
        self.db.test.save({"a": {"b": "b"}, "c": 12})
        self.db.test.save({"a": {"b": "c"}, "c": 12})
        self.db.test.save({"a": {"b": "c"}, "c": 12})

        distinct = self.db.test.distinct("a.b")
        distinct.sort()

        self.assertEqual(["a", "b", "c"], distinct)
    def test_group_with_scope(self):
        db = self.db
        db.drop_collection("test")
        db.test.save({"a": 1})
        db.test.save({"b": 1})

        reduce_function = "function (obj, prev) { prev.count += inc_value; }"

        self.assertEqual(2, db.test.group([], {}, {"count": 0},
                                          Code(reduce_function,
                                               {"inc_value": 1}))[0]['count'])
        self.assertEqual(4, db.test.group([], {}, {"count": 0},
                                          Code(reduce_function,
                                               {"inc_value": 2}))[0]['count'])

        self.assertEqual(1, db.test.group([], {}, {"count": 0},
                                          Code(reduce_function,
                                               {"inc_value": 0.5}))[0]['count'])

        if version.at_least(db.connection, (1, 1)):
            self.assertEqual(2, db.test.group([], {}, {"count": 0},
                                              Code(reduce_function,
                                                   {"inc_value": 1}),
                                              command=True)[0]['count'])

            self.assertEqual(4, db.test.group([], {}, {"count": 0},
                                              Code(reduce_function,
                                                   {"inc_value": 2}),
                                              command=True)[0]['count'])

            self.assertEqual(1, db.test.group([], {}, {"count": 0},
                                              Code(reduce_function,
                                                   {"inc_value": 0.5}),
                                              command=True)[0]['count'])
    def test_create_collection(self):
        db = Database(self.client, "pymongo_test")

        db.test.insert({"hello": "world"})
        self.assertRaises(CollectionInvalid, db.create_collection, "test")

        db.drop_collection("test")

        self.assertRaises(TypeError, db.create_collection, 5)
        self.assertRaises(TypeError, db.create_collection, None)
        self.assertRaises(InvalidName, db.create_collection, "coll..ection")

        test = db.create_collection("test")
        test.save({"hello": u"world"})
        self.assertEqual(db.test.find_one()["hello"], "world")
        self.assertTrue(u"test" in db.collection_names())

        db.drop_collection("test.foo")
        db.create_collection("test.foo")
        self.assertTrue(u"test.foo" in db.collection_names())
        expected = {}
        if version.at_least(self.client, (2, 7, 0)):
            # usePowerOf2Sizes server default
            expected["flags"] = 1
        result = db.test.foo.options()
        # mongos 2.2.x adds an $auth field when auth is enabled.
        result.pop('$auth', None)
        self.assertEqual(result, expected)
        self.assertRaises(CollectionInvalid, db.create_collection, "test.foo")
 def test_error_code(self):
     try:
         self.db.test.update({}, {"$thismodifierdoesntexist": 1}, safe=True)
         self.fail()
     except OperationFailure, e:
         if version.at_least(self.db.connection, (1, 3)):
             self.assertEqual(10147, e.code)
    def setUp(self):
        super(TestBulkAuthorization, self).setUp()
        self.client = client = get_client()
        if (not server_started_with_auth(client)
                or not version.at_least(client, (2, 5, 3))):
            raise SkipTest('Need at least MongoDB 2.5.3 with auth')

        db = client.pymongo_test
        self.coll = db.test
        self.coll.remove()

        db.add_user('dbOwner', 'pw', roles=['dbOwner'])
        db.authenticate('dbOwner', 'pw')
        db.add_user('readonly', 'pw', roles=['read'])
        db.command('createRole',
                   'noremove',
                   privileges=[{
                       'actions': ['insert', 'update', 'find'],
                       'resource': {
                           'db': 'pymongo_test',
                           'collection': 'test'
                       }
                   }],
                   roles=[])

        db.add_user('noremove', 'pw', roles=['noremove'])
        db.logout()
Beispiel #10
0
    def test_authenticate(self):
        db = self.db
        try:
            yield self.cx.admin.add_user("admin", "password")
            yield self.cx.admin.authenticate("admin", "password")
            yield db.add_user("mike", "password")

            # Authenticate many times at once to test concurrency.
            yield [db.authenticate("mike", "password") for _ in range(10)]

            # just make sure there are no exceptions here
            yield db.remove_user("mike")
            yield db.logout()
            if (yield version.at_least(self.cx, (2, 5, 4))):
                info = yield db.command("usersInfo", "mike")
                users = info.get('users', [])
            else:
                users = yield db.system.users.find().to_list(length=10)

            self.assertFalse("mike" in [u['user'] for u in users])

        finally:
            yield remove_all_users(db)
            yield self.cx.admin.remove_user('admin')
            test.sync_cx.disconnect()
Beispiel #11
0
    def test_init_disconnected(self):
        c = MongoClient(host, port, _connect=False)

        self.assertIsInstance(c.is_primary, bool)
        self.assertIsInstance(c.is_mongos, bool)
        self.assertIsInstance(c.max_pool_size, int)
        self.assertIsInstance(c.use_greenlets, bool)
        self.assertIsInstance(c.nodes, frozenset)
        self.assertIsInstance(c.auto_start_request, bool)
        self.assertEqual(dict, c.get_document_class())
        self.assertIsInstance(c.tz_aware, bool)
        self.assertIsInstance(c.max_bson_size, int)
        self.assertIsInstance(c.min_wire_version, int)
        self.assertIsInstance(c.max_wire_version, int)
        self.assertIsInstance(c.max_write_batch_size, int)
        self.assertEqual(None, c.host)
        self.assertEqual(None, c.port)

        c.pymongo_test.test.find_one()  # Auto-connect.
        self.assertEqual(host, c.host)
        self.assertEqual(port, c.port)

        if version.at_least(c, (2, 5, 4, -1)):
            self.assertTrue(c.max_wire_version > 0)
        else:
            self.assertEqual(c.max_wire_version, 0)
        self.assertTrue(c.min_wire_version >= 0)

        bad_host = "somedomainthatdoesntexist.org"
        c = MongoClient(bad_host, port, connectTimeoutMS=1, _connect=False)
        self.assertRaises(ConnectionFailure, c.pymongo_test.test.find_one)
    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()
Beispiel #13
0
    def test_distinct(self):
        if not version.at_least(self.db.connection, (1, 1, 3, 1)):
            raise SkipTest("distinct with query requires MongoDB >= 1.1.3")

        self.db.drop_collection("test")

        self.db.test.save({"a": 1})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 2})
        self.db.test.save({"a": 3})

        distinct = self.db.test.find({"a": {"$lt": 3}}).distinct("a")
        distinct.sort()

        self.assertEqual([1, 2], distinct)

        self.db.drop_collection("test")

        self.db.test.save({"a": {"b": "a"}, "c": 12})
        self.db.test.save({"a": {"b": "b"}, "c": 8})
        self.db.test.save({"a": {"b": "c"}, "c": 12})
        self.db.test.save({"a": {"b": "c"}, "c": 8})

        distinct = self.db.test.find({"c": 8}).distinct("a.b")
        distinct.sort()

        self.assertEqual(["b", "c"], distinct)
Beispiel #14
0
    def test_parallel_scan(self):
        if not (yield version.at_least(self.cx, (2, 5, 5))):
            raise SkipTest("Requires MongoDB >= 2.5.5")

        yield skip_if_mongos(self.cx)

        collection = self.collection

        # Enough documents that each cursor requires multiple batches.
        yield collection.remove()
        yield collection.insert(({
            '_id': i
        } for i in range(8000)),
                                w=test.env.w)
        if test.env.is_replica_set:
            client = self.motor_rsc()

            # Test that getMore messages are sent to the right server.
            client.read_preference = ReadPreference.SECONDARY
            collection = client.motor_test.test_collection

        docs = []

        @gen.coroutine
        def f(cursor):
            self.assertTrue(isinstance(cursor, motor.MotorCommandCursor))

            while (yield cursor.fetch_next):
                docs.append(cursor.next_object())

        cursors = yield collection.parallel_scan(3)
        yield [f(cursor) for cursor in cursors]
        self.assertEqual(len(docs), (yield collection.count()))
    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
Beispiel #16
0
    def test_count_with_limit_and_skip(self):
        if not version.at_least(self.db.connection, (1, 1, 4, -1)):
            raise SkipTest("count with limit / skip requires MongoDB >= 1.1.4")

        self.assertRaises(TypeError, self.db.test.find().count, "foo")

        def check_len(cursor, length):
            self.assertEqual(len(list(cursor)), cursor.count(True))
            self.assertEqual(length, cursor.count(True))

        self.db.drop_collection("test")
        for i in range(100):
            self.db.test.save({"i": i})

        check_len(self.db.test.find(), 100)

        check_len(self.db.test.find().limit(10), 10)
        check_len(self.db.test.find().limit(110), 100)

        check_len(self.db.test.find().skip(10), 90)
        check_len(self.db.test.find().skip(110), 0)

        check_len(self.db.test.find().limit(10).skip(10), 10)
        check_len(self.db.test.find()[10:20], 10)
        check_len(self.db.test.find().limit(10).skip(95), 5)
        check_len(self.db.test.find()[95:105], 5)
    def test_properties(self):
        c = ReplicaSetConnection(pair, replicaSet=self.name)
        c.admin.command('ping')
        self.assertEqual(c.primary, self.primary)
        self.assertEqual(c.hosts, self.hosts)
        self.assertEqual(c.arbiters, self.arbiters)
        self.assertEqual(c.read_preference, ReadPreference.PRIMARY)
        self.assertEqual(c.max_pool_size, 10)
        self.assertEqual(c.document_class, dict)
        self.assertEqual(c.tz_aware, False)
        self.assertEqual(c.slave_okay, False)
        self.assertEqual(c.safe, False)
        c.close()

        c = ReplicaSetConnection(pair, replicaSet=self.name, max_pool_size=25,
                                 document_class=SON, tz_aware=True,
                                 slaveOk=False, safe=True,
                                 read_preference=ReadPreference.SECONDARY)
        c.admin.command('ping')
        self.assertEqual(c.primary, self.primary)
        self.assertEqual(c.hosts, self.hosts)
        self.assertEqual(c.arbiters, self.arbiters)
        self.assertEqual(c.read_preference, ReadPreference.SECONDARY)
        self.assertEqual(c.max_pool_size, 25)
        self.assertEqual(c.document_class, SON)
        self.assertEqual(c.tz_aware, True)
        self.assertEqual(c.slave_okay, False)
        self.assertEqual(c.safe, True)

        if version.at_least(c, (1, 7, 4)):
            self.assertEqual(c.max_bson_size, 16777216)
        else:
            self.assertEqual(c.max_bson_size, 4194304)
        c.close()
Beispiel #18
0
    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 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()
Beispiel #20
0
    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")
Beispiel #21
0
    def test_command_max_time_ms(self):
        if not version.at_least(self.client, (2, 5, 3, -1)):
            raise SkipTest("MaxTimeMS requires MongoDB >= 2.5.3")
        if "enableTestCommands=1" not in get_command_line(self.client)["argv"]:
            raise SkipTest("Test commands must be enabled.")

        self.client.admin.command("configureFailPoint",
                                  "maxTimeAlwaysTimeOut",
                                  mode="alwaysOn")
        try:
            db = self.client.pymongo_test
            db.command('count', 'test')
            self.assertRaises(ExecutionTimeout, db.command,
                              'count', 'test', maxTimeMS=1)
            pipeline = [{'$project': {'name': 1, 'count': 1}}]
            # Database command helper.
            db.command('aggregate', 'test', pipeline=pipeline)
            self.assertRaises(ExecutionTimeout, db.command,
                              'aggregate', 'test',
                              pipeline=pipeline, maxTimeMS=1)
            # Collection helper.
            db.test.aggregate(pipeline=pipeline)
            self.assertRaises(ExecutionTimeout,
                              db.test.aggregate, pipeline, maxTimeMS=1)
        finally:
            self.client.admin.command("configureFailPoint",
                                      "maxTimeAlwaysTimeOut",
                                      mode="off")
Beispiel #22
0
    def test_get_last_error_defaults(self):
        if not version.at_least(self.c, (1, 9, 0)):
            raise SkipTest(
                "Need MongoDB >= 1.9.0 to test getLastErrorDefaults")

        replset = self.c.local.system.replset.find_one()
        settings = replset.get('settings', {})
        # This should cause a WTimeoutError for every write command
        settings['getLastErrorDefaults'] = {'w': 3, 'wtimeout': 1}
        replset['settings'] = settings
        replset['version'] = replset.get("version", 1) + 1

        self.c.admin.command("replSetReconfig", replset)

        self.assertRaises(WTimeoutError, self.c.pymongo_test.test.insert,
                          {'_id': 0})
        self.assertRaises(WTimeoutError, self.c.pymongo_test.test.save, {
            '_id': 0,
            "a": 5
        })
        self.assertRaises(WTimeoutError, self.c.pymongo_test.test.update,
                          {'_id': 0}, {"$set": {
                              "a": 10
                          }})
        self.assertRaises(WTimeoutError, self.c.pymongo_test.test.remove,
                          {'_id': 0})
    def test_max_time_ms_getmore(self):
        # Test that Cursor handles server timeout error in response to getmore.
        if "enableTestCommands=1" not in get_command_line(self.client)["argv"]:
            raise SkipTest("Need test commands enabled")

        if not version.at_least(self.db.connection, (2, 5, 3, -1)):
            raise SkipTest("MaxTimeMS requires MongoDB >= 2.5.3")

        coll = self.db.pymongo_test
        coll.insert({} for _ in range(200))
        cursor = coll.find().max_time_ms(100)

        # Send initial query before turning on failpoint.
        cursor.next()
        self.client.admin.command("configureFailPoint",
                                  "maxTimeAlwaysTimeOut",
                                  mode="alwaysOn")
        try:
            try:
                # Iterate up to first getmore.
                list(cursor)
            except ExecutionTimeout:
                pass
            else:
                self.fail("ExecutionTimeout not raised")
        finally:
            self.client.admin.command("configureFailPoint",
                                      "maxTimeAlwaysTimeOut",
                                      mode="off")
Beispiel #24
0
    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()
        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]['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))
Beispiel #25
0
    def test_system_js(self):
        db = self.connection.pymongo_test
        db.system.js.remove()

        self.assertEqual(0, db.system.js.count())
        db.system_js.add = "function(a, b) { return a + b; }"
        self.assertEqual('add', db.system.js.find_one()['_id'])
        self.assertEqual(1, db.system.js.count())
        self.assertEqual(6, db.system_js.add(1, 5))
        del db.system_js.add
        self.assertEqual(0, db.system.js.count())

        db.system_js['add'] = "function(a, b) { return a + b; }"
        self.assertEqual('add', db.system.js.find_one()['_id'])
        self.assertEqual(1, db.system.js.count())
        self.assertEqual(6, db.system_js['add'](1, 5))
        del db.system_js['add']
        self.assertEqual(0, db.system.js.count())

        if version.at_least(db.connection, (1, 3, 2, -1)):
            self.assertRaises(OperationFailure, db.system_js.add, 1, 5)

        # TODO right now CodeWScope doesn't work w/ system js
        # db.system_js.scope = Code("return hello;", {"hello": 8})
        # self.assertEqual(8, db.system_js.scope())

        self.assertRaises(OperationFailure, db.system_js.non_existant)

        db.system_js.no_param = Code("return 5;")
        self.assertEqual(5, db.system_js.no_param())
Beispiel #26
0
    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_last_error_options(self):
        if not version.at_least(self.connection, (1, 5, 1)):
            raise SkipTest()

        # XXX: Fix this if we ever have a replica set unittest env.
        # mongo >=1.7.6 errors with 'norepl' when w=2+
        # and we aren't replicated.
        if not version.at_least(self.connection, (1, 7, 6)):
            self.assertRaises(TimeoutError, self.db.test.save, {"x": 1}, w=2, wtimeout=1)
            self.assertRaises(TimeoutError, self.db.test.insert, {"x": 1}, w=2, wtimeout=1)
            self.assertRaises(TimeoutError, self.db.test.update, {"x": 1}, {"y": 2}, w=2, wtimeout=1)
            self.assertRaises(TimeoutError, self.db.test.remove, {"x": 1}, {"y": 2}, w=2, wtimeout=1)

        self.db.test.save({"x": 1}, w=1, wtimeout=1)
        self.db.test.insert({"x": 1}, w=1, wtimeout=1)
        self.db.test.remove({"x": 1}, w=1, wtimeout=1)
        self.db.test.update({"x": 1}, {"y": 2}, w=1, wtimeout=1)
 def test_manual_last_error(self):
     self.db.test.save({"x": 1})
     # XXX: Fix this if we ever have a replica set unittest env.
     # mongo >=1.7.6 errors with 'norepl' when w=2+
     # and we aren't replicated
     if not version.at_least(self.connection, (1, 7, 6)):
         self.assertRaises(TimeoutError, self.db.command, "getlasterror", w=2, wtimeout=1)
     self.db.command("getlasterror", w=1, wtimeout=1)
 def setUp(self):
     self.client = MongoClient(host, port)
     authed_client = auth_context.client
     if not version.at_least(authed_client, (2, 4, 0)):
         raise SkipTest(
             'Delegated authentication requires MongoDB >= 2.4.0')
     if version.at_least(authed_client, (2, 5, 3, -1)):
         raise SkipTest('Delegated auth does not exist in MongoDB >= 2.5.3')
     # Give admin all privileges.
     authed_client.admin.add_user('admin',
                                  'pass',
                                  roles=[
                                      'readAnyDatabase',
                                      'readWriteAnyDatabase',
                                      'userAdminAnyDatabase',
                                      'dbAdminAnyDatabase', 'clusterAdmin'
                                  ])
Beispiel #30
0
 def test_fsync_and_j(self):
     if not version.at_least(self.client, (1, 8, 2)):
         raise SkipTest("Need at least MongoDB 1.8.2")
     batch = self.coll.initialize_ordered_bulk_op()
     batch.insert({'a': 1})
     self.assertRaises(
         OperationFailure,
         batch.execute, {'fsync': True, 'j': True})