def test_eval(self):
        db = self.client.pymongo_test
        db.test.drop()

        with ignore_deprecations():
            self.assertRaises(TypeError, db.eval, None)
            self.assertRaises(TypeError, db.eval, 5)
            self.assertRaises(TypeError, db.eval, [])

            self.assertEqual(3, db.eval("function (x) {return x;}", 3))
            self.assertEqual(3, db.eval(u"function (x) {return x;}", 3))

            self.assertEqual(None,
                             db.eval("function (x) {db.test.save({y:x});}", 5))
            self.assertEqual(db.test.find_one()["y"], 5)

            self.assertEqual(5, db.eval("function (x, y) {return x + y;}", 2, 3))
            self.assertEqual(5, db.eval("function () {return 5;}"))
            self.assertEqual(5, db.eval("2 + 3;"))

            self.assertEqual(5, db.eval(Code("2 + 3;")))
            self.assertRaises(OperationFailure, db.eval, Code("return i;"))
            self.assertEqual(2, db.eval(Code("return i;", {"i": 2})))
            self.assertEqual(5, db.eval(Code("i + 3;", {"i": 2})))

            self.assertRaises(OperationFailure, db.eval, "5 ++ 5;")
    def test_authenticate_add_remove_user(self):
        # "self.client" is logged in as root.
        auth_db = self.client.pymongo_test

        def check_auth(username, password):
            c = rs_or_single_client_noauth(
                username=username,
                password=password,
                authSource="pymongo_test")

            c.pymongo_test.collection.find_one()

        # Configuration errors
        self.assertRaises(ValueError, auth_db.add_user, "user", '')
        self.assertRaises(TypeError, auth_db.add_user, "user", 'password', 15)
        self.assertRaises(TypeError, auth_db.add_user,
                          "user", 'password', 'True')
        self.assertRaises(ConfigurationError, auth_db.add_user,
                          "user", 'password', True, roles=['read'])

        with warnings.catch_warnings():
            warnings.simplefilter("error", DeprecationWarning)
            self.assertRaises(DeprecationWarning, auth_db.add_user,
                              "user", "password")
            self.assertRaises(DeprecationWarning, auth_db.add_user,
                              "user", "password", True)

        with ignore_deprecations():
            self.assertRaises(ConfigurationError, auth_db.add_user,
                              "user", "password", digestPassword=True)

        # Add / authenticate / remove
        auth_db.add_user("mike", "password", roles=["read"])
        self.addCleanup(remove_all_users, auth_db)
        self.assertRaises(TypeError, check_auth, 5, "password")
        self.assertRaises(TypeError, check_auth, "mike", 5)
        self.assertRaises(OperationFailure,
                          check_auth, "mike", "not a real password")
        self.assertRaises(OperationFailure, check_auth, "faker", "password")
        check_auth("mike", "password")

        if not client_context.version.at_least(3, 7, 2) or HAVE_STRINGPREP:
            # Unicode name and password.
            check_auth(u"mike", u"password")

            auth_db.remove_user("mike")
            self.assertRaises(
                OperationFailure, check_auth, "mike", "password")

            # Add / authenticate / change password
            self.assertRaises(
                OperationFailure, check_auth, "Gustave", u"Dor\xe9")
            auth_db.add_user("Gustave", u"Dor\xe9", roles=["read"])
            check_auth("Gustave", u"Dor\xe9")

            # Change password.
            auth_db.add_user("Gustave", "password", roles=["read"])
            self.assertRaises(
                OperationFailure, check_auth, "Gustave", u"Dor\xe9")
            check_auth("Gustave", u"password")
Ejemplo n.º 3
0
    def test_op(self):
        # motor.Op is deprecated in Motor 0.2, superseded by Tornado 3 Futures.
        # Just make sure it still works.

        collection = self.collection
        doc = {'_id': 'jesse'}

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            # Op works.
            _id = yield motor.Op(collection.insert, doc)
            self.assertEqual('jesse', _id)

            # Raised a DeprecationWarning.
            self.assertEqual(1, len(w))
            warning = w[-1]
            self.assertTrue(issubclass(warning.category, DeprecationWarning))
            message = str(warning.message)
            self.assertTrue("deprecated" in message)
            self.assertTrue("insert" in message)

        with ignore_deprecations():
            result = yield motor.Op(collection.find_one, doc)
            self.assertEqual(doc, result)

            # Make sure it works with no args.
            result = yield motor.Op(collection.find_one)
            self.assertTrue(isinstance(result, dict))

            with self.assertRaises(pymongo.errors.DuplicateKeyError):
                yield motor.Op(collection.insert, doc)
Ejemplo n.º 4
0
    def test_authenticate(self):
        # self.db is logged in as root.
        with ignore_deprecations():
            yield self.db.add_user("mike", "password")

        client = motor.MotorClient(env.host, env.port,
                                   **self.get_client_kwargs())
        db = client.motor_test
        try:
            # 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 at_least(self.cx, (2, 5, 4))):
                info = yield self.db.command("usersInfo", "mike")
                users = info.get('users', [])
            else:
                users = yield self.db.system.users.find().to_list(length=10)

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

        finally:
            yield remove_all_users(self.db)
            test.env.sync_cx.close()
Ejemplo n.º 5
0
    def test_errors(self):
        with ignore_deprecations():
            # We must call getlasterror, etc. on same socket as last operation.
            db = rs_or_single_client(maxPoolSize=1).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_eval(self):
        db = self.client.pymongo_test
        db.test.drop()

        with ignore_deprecations():
            self.assertRaises(TypeError, db.eval, None)
            self.assertRaises(TypeError, db.eval, 5)
            self.assertRaises(TypeError, db.eval, [])

            self.assertEqual(3, db.eval("function (x) {return x;}", 3))
            self.assertEqual(3, db.eval(u"function (x) {return x;}", 3))

            self.assertEqual(None,
                             db.eval("function (x) {db.test.save({y:x});}", 5))
            self.assertEqual(db.test.find_one()["y"], 5)

            self.assertEqual(5, db.eval("function (x, y) {return x + y;}", 2, 3))
            self.assertEqual(5, db.eval("function () {return 5;}"))
            self.assertEqual(5, db.eval("2 + 3;"))

            self.assertEqual(5, db.eval(Code("2 + 3;")))
            self.assertRaises(OperationFailure, db.eval, Code("return i;"))
            self.assertEqual(2, db.eval(Code("return i;", {"i": 2})))
            self.assertEqual(5, db.eval(Code("i + 3;", {"i": 2})))

            self.assertRaises(OperationFailure, db.eval, "5 ++ 5;")
Ejemplo n.º 7
0
    async def test_open_client_rs(self):
        if not test.env.is_replica_set:
            raise SkipTest("Not connected to a replica set")

        rsc = self.motor_rsc()
        with ignore_deprecations():
            self.assertEqual(rsc, await rsc.open())
Ejemplo n.º 8
0
    def test_scram_sha1(self):
        host, port = client_context.host, client_context.port

        with ignore_deprecations():
            client = rs_or_single_client_noauth()
            self.assertTrue(
                client.pymongo_test.authenticate('user',
                                                 'pass',
                                                 mechanism='SCRAM-SHA-1'))
            client.pymongo_test.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/pymongo_test?authMechanism=SCRAM-SHA-1'
            % (host, port))
        client.pymongo_test.command('dbstats')

        if client_context.is_rs:
            uri = ('mongodb://*****:*****@%s:%d/pymongo_test?authMechanism=SCRAM-SHA-1'
                   '&replicaSet=%s' %
                   (host, port, client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.pymongo_test.command('dbstats')
            db = client.get_database('pymongo_test',
                                     read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
Ejemplo n.º 9
0
    def test_authenticate(self):
        # self.db is logged in as root.
        with ignore_deprecations():
            yield self.db.add_user("mike", "password")

        client = motor.MotorClient(host, port, **self.get_client_kwargs())
        db = client.motor_test
        try:
            # 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 at_least(self.cx, (2, 5, 4))):
                info = yield self.db.command("usersInfo", "mike")
                users = info.get('users', [])
            else:
                users = yield self.db.system.users.find().to_list(length=10)

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

        finally:
            yield remove_all_users(self.db)
            test.env.sync_cx.disconnect()
Ejemplo n.º 10
0
    def test_uuid_subtype(self):
        collection = self.db.test

        with ignore_deprecations():
            self.assertEqual(collection.uuid_subtype, OLD_UUID_SUBTYPE)
            collection.uuid_subtype = JAVA_LEGACY
            self.assertEqual(collection.uuid_subtype, JAVA_LEGACY)
Ejemplo n.º 11
0
    async def test_open_client(self):
        client = self.asyncio_client()

        with ignore_deprecations():
            self.assertEqual(client, await client.open())

        client.close()
Ejemplo n.º 12
0
    def test_uuid_subtype(self):
        db = self.cx.test

        with ignore_deprecations():
            self.assertEqual(db.uuid_subtype, OLD_UUID_SUBTYPE)
            db.uuid_subtype = JAVA_LEGACY
            self.assertEqual(db.uuid_subtype, JAVA_LEGACY)
    def test_repr(self):
        with ignore_deprecations():
            client = MongoReplicaSetClient(host, port,
                                           replicaSet=self.name)

        self.assertIn("MongoReplicaSetClient(host=[", repr(client))
        self.assertIn(pair, repr(client))
Ejemplo n.º 14
0
    def test_open_sync(self):
        loop = IOLoop()

        with ignore_deprecations():
            cx = loop.run_sync(self.motor_client(io_loop=loop).open)

        self.assertTrue(isinstance(cx, motor.MotorClient))
Ejemplo n.º 15
0
    def test_op(self):
        # motor.Op is deprecated in Motor 0.2, superseded by Tornado 3 Futures.
        # Just make sure it still works.

        collection = self.collection
        doc = {'_id': 'jesse'}

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            # Op works.
            _id = yield motor.Op(collection.insert, doc)
            self.assertEqual('jesse', _id)

            # Raised a DeprecationWarning.
            self.assertEqual(1, len(w))
            warning = w[-1]
            self.assertTrue(issubclass(warning.category, DeprecationWarning))
            message = str(warning.message)
            self.assertTrue("deprecated" in message)
            self.assertTrue("insert" in message)

        with ignore_deprecations():
            result = yield motor.Op(collection.find_one, doc)
            self.assertEqual(doc, result)

            # Make sure it works with no args.
            result = yield motor.Op(collection.find_one)
            self.assertTrue(isinstance(result, dict))

            with assert_raises(pymongo.errors.DuplicateKeyError):
                yield motor.Op(collection.insert, doc)
Ejemplo n.º 16
0
    def test_sasl_plain_bad_credentials(self):

        with ignore_deprecations():
            client = MongoClient(SASL_HOST, SASL_PORT)

            # Bad username
            self.assertRaises(OperationFailure, client.ldap.authenticate,
                              'not-user', SASL_PASS, SASL_DB, 'PLAIN')
            self.assertRaises(OperationFailure, client.ldap.test.find_one)
            self.assertRaises(OperationFailure, client.ldap.test.insert_one,
                              {"failed": True})

            # Bad password
            self.assertRaises(OperationFailure, client.ldap.authenticate,
                              SASL_USER, 'not-pwd', SASL_DB, 'PLAIN')
            self.assertRaises(OperationFailure, client.ldap.test.find_one)
            self.assertRaises(OperationFailure, client.ldap.test.insert_one,
                              {"failed": True})

        def auth_string(user, password):
            uri = ('mongodb://%s:%s@%s:%d/?authMechanism=PLAIN;'
                   'authSource=%s' % (quote_plus(user), quote_plus(password),
                                      SASL_HOST, SASL_PORT, SASL_DB))
            return uri

        bad_user = MongoClient(auth_string('not-user', SASL_PASS))
        bad_pwd = MongoClient(auth_string(SASL_USER, 'not-pwd'))
        # OperationFailure raised upon connecting.
        self.assertRaises(OperationFailure, bad_user.admin.command, 'ismaster')
        self.assertRaises(OperationFailure, bad_pwd.admin.command, 'ismaster')
Ejemplo n.º 17
0
    def test_sasl_plain_bad_credentials(self):

        with ignore_deprecations():
            client = MongoClient(SASL_HOST, SASL_PORT)

            # Bad username
            self.assertRaises(OperationFailure, client.ldap.authenticate,
                              'not-user', SASL_PASS, SASL_DB, 'PLAIN')
            self.assertRaises(OperationFailure, client.ldap.test.find_one)
            self.assertRaises(OperationFailure, client.ldap.test.insert_one,
                              {"failed": True})

            # Bad password
            self.assertRaises(OperationFailure, client.ldap.authenticate,
                              SASL_USER, 'not-pwd', SASL_DB, 'PLAIN')
            self.assertRaises(OperationFailure, client.ldap.test.find_one)
            self.assertRaises(OperationFailure, client.ldap.test.insert_one,
                              {"failed": True})

        def auth_string(user, password):
            uri = ('mongodb://%s:%s@%s:%d/?authMechanism=PLAIN;'
                   'authSource=%s' % (quote_plus(user),
                                      quote_plus(password),
                                      SASL_HOST, SASL_PORT, SASL_DB))
            return uri

        bad_user = MongoClient(auth_string('not-user', SASL_PASS))
        bad_pwd = MongoClient(auth_string(SASL_USER, 'not-pwd'))
        # OperationFailure raised upon connecting.
        self.assertRaises(OperationFailure, bad_user.admin.command, 'ismaster')
        self.assertRaises(OperationFailure, bad_pwd.admin.command, 'ismaster')
Ejemplo n.º 18
0
    def test_errors(self):
        with ignore_deprecations():
            # We must call getlasterror, etc. on same socket as last operation.
            db = rs_or_single_client(maxPoolSize=1).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())
Ejemplo n.º 19
0
    def test_authenticate_add_remove_user(self):
        # "self.client" is logged in as root.
        auth_db = self.client.pymongo_test

        def check_auth(username, password):
            c = rs_or_single_client_noauth(
                username=username,
                password=password,
                authSource="pymongo_test")

            c.pymongo_test.collection.find_one()

        # Configuration errors
        self.assertRaises(ValueError, auth_db.add_user, "user", '')
        self.assertRaises(TypeError, auth_db.add_user, "user", 'password', 15)
        self.assertRaises(TypeError, auth_db.add_user,
                          "user", 'password', 'True')
        self.assertRaises(ConfigurationError, auth_db.add_user,
                          "user", 'password', True, roles=['read'])

        with warnings.catch_warnings():
            warnings.simplefilter("error", DeprecationWarning)
            self.assertRaises(DeprecationWarning, auth_db.add_user,
                              "user", "password")
            self.assertRaises(DeprecationWarning, auth_db.add_user,
                              "user", "password", True)

        with ignore_deprecations():
            self.assertRaises(ConfigurationError, auth_db.add_user,
                              "user", "password", digestPassword=True)

        # Add / authenticate / remove
        auth_db.add_user("mike", "password", roles=["read"])
        self.addCleanup(remove_all_users, auth_db)
        self.assertRaises(TypeError, check_auth, 5, "password")
        self.assertRaises(TypeError, check_auth, "mike", 5)
        self.assertRaises(OperationFailure,
                          check_auth, "mike", "not a real password")
        self.assertRaises(OperationFailure, check_auth, "faker", "password")
        check_auth("mike", "password")

        if not client_context.version.at_least(3, 7, 2) or HAVE_STRINGPREP:
            # Unicode name and password.
            check_auth(u"mike", u"password")

            auth_db.remove_user("mike")
            self.assertRaises(
                OperationFailure, check_auth, "mike", "password")

            # Add / authenticate / change password
            self.assertRaises(
                OperationFailure, check_auth, "Gustave", u"Dor\xe9")
            auth_db.add_user("Gustave", u"Dor\xe9", roles=["read"])
            check_auth("Gustave", u"Dor\xe9")

            # Change password.
            auth_db.add_user("Gustave", "password", roles=["read"])
            self.assertRaises(
                OperationFailure, check_auth, "Gustave", u"Dor\xe9")
            check_auth("Gustave", u"password")
Ejemplo n.º 20
0
    def test_uuid_subtype(self):
        cx = self.asyncio_rsc(uuidRepresentation='javaLegacy')

        with ignore_deprecations():
            self.assertEqual(cx.uuid_subtype, JAVA_LEGACY)
            cx.uuid_subtype = UUID_SUBTYPE
            self.assertEqual(cx.uuid_subtype, UUID_SUBTYPE)
            self.assertEqual(cx.delegate.uuid_subtype, UUID_SUBTYPE)
Ejemplo n.º 21
0
    def test_uuid_subtype(self):
        if pymongo.version_tuple < (2, 9, 4):
            raise SkipTest("PYTHON-1145")

        cx = self.motor_rsc(uuidRepresentation='javaLegacy')

        with ignore_deprecations():
            self.assertEqual(cx.uuid_subtype, JAVA_LEGACY)
            cx.uuid_subtype = UUID_SUBTYPE
            self.assertEqual(cx.uuid_subtype, UUID_SUBTYPE)
            self.assertEqual(cx.delegate.uuid_subtype, UUID_SUBTYPE)
Ejemplo n.º 22
0
    def test_open_sync(self):
        loop = asyncio.new_event_loop()
        with ignore_deprecations():
            cx = loop.run_until_complete(
                self.asyncio_client(io_loop=loop).open())

        self.assertTrue(isinstance(cx, motor_asyncio.AsyncIOMotorClient))
        cx.close()
        loop.stop()
        loop.run_forever()
        loop.close()
    def test_repr(self):
        with ignore_deprecations():
            client = MongoReplicaSetClient(host, port, replicaSet=self.name)

        wait_until(lambda: client.primary == self.primary, "discover primary")
        wait_until(lambda: client.secondaries == self.secondaries,
                   "discover secondaries")

        # repr should be something like
        # MongoReplicaSetClient(["localhost:27017", "localhost:27018"]).
        self.assertIn("MongoReplicaSetClient([", repr(client))
        for h in self.hosts:
            self.assertIn("%s:%d" % h, repr(client))
Ejemplo n.º 24
0
    def test_modifiers(self):
        c = self.db.test

        # "modifiers" is deprecated.
        with ignore_deprecations():
            cur = c.find()
            self.assertTrue('$query' not in cur._Cursor__query_spec())
            cur = c.find().comment("testing").max_time_ms(500)
            self.assertTrue('$query' in cur._Cursor__query_spec())
            self.assertEqual(cur._Cursor__query_spec()["$comment"], "testing")
            self.assertEqual(cur._Cursor__query_spec()["$maxTimeMS"], 500)
            cur = c.find(modifiers={"$maxTimeMS": 500, "$comment": "testing"})
            self.assertTrue('$query' in cur._Cursor__query_spec())
            self.assertEqual(cur._Cursor__query_spec()["$comment"], "testing")
            self.assertEqual(cur._Cursor__query_spec()["$maxTimeMS"], 500)

            # Keyword arg overwrites modifier.
            # If we remove the "modifiers" arg, delete this test after checking
            # that TestCommandMonitoring.test_find_options covers all cases.
            cur = c.find(comment="hi", modifiers={"$comment": "bye"})
            self.assertEqual(cur._Cursor__query_spec()["$comment"], "hi")

            cur = c.find(max_scan=1, modifiers={"$maxScan": 2})
            self.assertEqual(cur._Cursor__query_spec()["$maxScan"], 1)

            cur = c.find(max_time_ms=1, modifiers={"$maxTimeMS": 2})
            self.assertEqual(cur._Cursor__query_spec()["$maxTimeMS"], 1)

            cur = c.find(min=1, modifiers={"$min": 2})
            self.assertEqual(cur._Cursor__query_spec()["$min"], 1)

            cur = c.find(max=1, modifiers={"$max": 2})
            self.assertEqual(cur._Cursor__query_spec()["$max"], 1)

            cur = c.find(return_key=True, modifiers={"$returnKey": False})
            self.assertEqual(cur._Cursor__query_spec()["$returnKey"], True)

            cur = c.find(hint=[("a", 1)], modifiers={"$hint": {"b": "1"}})
            self.assertEqual(cur._Cursor__query_spec()["$hint"], {"a": 1})

            cur = c.find(snapshot=True, modifiers={"$snapshot": False})
            self.assertEqual(cur._Cursor__query_spec()["$snapshot"], True)

            # The arg is named show_record_id after the "find" command arg, the
            # modifier is named $showDiskLoc for the OP_QUERY modifier. It's
            # stored as $showDiskLoc then upgraded to showRecordId if we send a
            # "find" command.
            cur = c.find(show_record_id=True,
                         modifiers={"$showDiskLoc": False})
            self.assertEqual(cur._Cursor__query_spec()["$showDiskLoc"], True)
Ejemplo n.º 25
0
    def test_connection_failure(self):
        # Assuming there isn't anything actually running on this port
        client = motor.MotorClient('localhost', 8765, io_loop=self.io_loop)

        # Test the Future interface.
        with self.assertRaises(ConnectionFailure):
            yield client.admin.command('ping')

        # Test with a callback.
        with ignore_deprecations():
            (result, error), _ = yield gen.Task(client.open)

        self.assertEqual(None, result)
        self.assertTrue(isinstance(error, ConnectionFailure))
    def test_repr(self):
        with ignore_deprecations():
            client = MongoReplicaSetClient(host, port,
                                           replicaSet=self.name)

        wait_until(lambda: client.primary == self.primary, "discover primary")
        wait_until(lambda: client.secondaries == self.secondaries,
                   "discover secondaries")

        # repr should be something like
        # MongoReplicaSetClient(["localhost:27017", "localhost:27018"]).
        self.assertIn("MongoReplicaSetClient([", repr(client))
        for h in self.hosts:
            self.assertIn("%s:%d" % h, repr(client))
Ejemplo n.º 27
0
    def test_connection_failure(self):
        # Assuming there isn't anything actually running on this port
        client = motor.MotorReplicaSetClient('localhost:8765',
                                             replicaSet='rs',
                                             io_loop=self.io_loop)

        with ignore_deprecations():
            # Test the Future interface.
            with self.assertRaises(pymongo.errors.ConnectionFailure):
                yield client.open()

            # Test with a callback.
            (result, error), _ = yield gen.Task(client.open)

        self.assertEqual(None, result)
        self.assertTrue(isinstance(error, pymongo.errors.ConnectionFailure))
Ejemplo n.º 28
0
    def test_authenticate(self):
        # self.db is logged in as root.
        with ignore_deprecations():
            yield self.db.add_user("mike", "password")

        client = motor.MotorClient(env.host, env.port,
                                   **self.get_client_kwargs())
        db = client.motor_test
        try:
            # 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()
            info = yield self.db.command("usersInfo", "mike")
            users = info.get('users', [])
            self.assertFalse("mike" in [u['user'] for u in users])

        finally:
            yield remove_all_users(self.db)
            test.env.sync_cx.close()
Ejemplo n.º 29
0
    def test_scram_sha1(self):
        host, port = client_context.host, client_context.port

        with ignore_deprecations():
            client = rs_or_single_client_noauth()
            self.assertTrue(client.pymongo_test.authenticate(
                'user', 'pass', mechanism='SCRAM-SHA-1'))
            client.pymongo_test.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/pymongo_test?authMechanism=SCRAM-SHA-1'
            % (host, port))
        client.pymongo_test.command('dbstats')

        if client_context.is_rs:
            uri = ('mongodb://*****:*****@%s:%d/pymongo_test?authMechanism=SCRAM-SHA-1'
                   '&replicaSet=%s' % (host, port,
                                       client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.pymongo_test.command('dbstats')
            db = client.get_database(
                'pymongo_test', read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
    def test_errors(self):
        with ignore_deprecations():
            # We must call getlasterror, etc. on same socket as last operation.
            db = rs_or_single_client(maxPoolSize=1).pymongo_test
            db.reset_error_history()
            self.assertEqual(None, db.error())
            self.assertEqual(None, db.previous_error())

            db.test.insert_one({"_id": 1})
            unacked = db.test.with_options(write_concern=WriteConcern(w=0))

            unacked.insert_one({"_id": 1})
            self.assertTrue(db.error())
            self.assertTrue(db.previous_error())

            unacked.insert_one({"_id": 1})
            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())
Ejemplo n.º 31
0
    def test_errors(self):
        with ignore_deprecations():
            # We must call getlasterror, etc. on same socket as last operation.
            db = rs_or_single_client(maxPoolSize=1).pymongo_test
            db.reset_error_history()
            self.assertEqual(None, db.error())
            self.assertEqual(None, db.previous_error())

            db.test.insert_one({"_id": 1})
            unacked = db.test.with_options(write_concern=WriteConcern(w=0))

            unacked.insert_one({"_id": 1})
            self.assertTrue(db.error())
            self.assertTrue(db.previous_error())

            unacked.insert_one({"_id": 1})
            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.assertEqualReply(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())
Ejemplo n.º 32
0
    def test_authenticate_add_remove_user(self):
        # "self.client" is logged in as root.
        auth_db = self.client.pymongo_test
        db = rs_or_single_client_noauth().pymongo_test

        # Configuration errors
        self.assertRaises(ValueError, auth_db.add_user, "user", '')
        self.assertRaises(TypeError, auth_db.add_user, "user", 'password', 15)
        self.assertRaises(TypeError, auth_db.add_user,
                          "user", 'password', 'True')
        self.assertRaises(ConfigurationError, auth_db.add_user,
                          "user", 'password', True, roles=['read'])

        if client_context.version.at_least(2, 5, 3, -1):
            with warnings.catch_warnings():
                warnings.simplefilter("error", DeprecationWarning)
                self.assertRaises(DeprecationWarning, auth_db.add_user,
                                  "user", "password")
                self.assertRaises(DeprecationWarning, auth_db.add_user,
                                  "user", "password", True)

            with ignore_deprecations():
                self.assertRaises(ConfigurationError, auth_db.add_user,
                                  "user", "password", digestPassword=True)

        # Add / authenticate / remove
        auth_db.add_user("mike", "password", roles=["dbOwner"])
        self.addCleanup(remove_all_users, auth_db)
        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")
        db.authenticate("mike", "password")
        db.logout()

        # Unicode name and password.
        db.authenticate(u("mike"), u("password"))
        db.logout()

        auth_db.remove_user("mike")
        self.assertRaises(OperationFailure,
                          db.authenticate, "mike", "password")

        # Add / authenticate / change password
        self.assertRaises(OperationFailure,
                          db.authenticate, "Gustave", u("Dor\xe9"))
        auth_db.add_user("Gustave", u("Dor\xe9"), roles=["dbOwner"])
        db.authenticate("Gustave", u("Dor\xe9"))

        # Change password.
        auth_db.add_user("Gustave", "password", roles=["dbOwner"])
        db.logout()
        self.assertRaises(OperationFailure,
                          db.authenticate, "Gustave", u("Dor\xe9"))
        self.assertTrue(db.authenticate("Gustave", u("password")))

        if not client_context.version.at_least(2, 5, 3, -1):
            # Add a readOnly user
            with ignore_deprecations():
                auth_db.add_user("Ross", "password", read_only=True)

            db.logout()
            db.authenticate("Ross", u("password"))
            self.assertTrue(
                auth_db.system.users.find({"readOnly": True}).count())
Ejemplo n.º 33
0
    def test_authenticate_add_remove_user(self):
        # "self.client" is logged in as root.
        auth_db = self.client.pymongo_test
        db = rs_or_single_client_noauth().pymongo_test

        # Configuration errors
        self.assertRaises(ValueError, auth_db.add_user, "user", '')
        self.assertRaises(TypeError, auth_db.add_user, "user", 'password', 15)
        self.assertRaises(TypeError, auth_db.add_user, "user", 'password',
                          'True')
        self.assertRaises(ConfigurationError,
                          auth_db.add_user,
                          "user",
                          'password',
                          True,
                          roles=['read'])

        if client_context.version.at_least(2, 5, 3, -1):
            with warnings.catch_warnings():
                warnings.simplefilter("error", DeprecationWarning)
                self.assertRaises(DeprecationWarning, auth_db.add_user, "user",
                                  "password")
                self.assertRaises(DeprecationWarning, auth_db.add_user, "user",
                                  "password", True)

            with ignore_deprecations():
                self.assertRaises(ConfigurationError,
                                  auth_db.add_user,
                                  "user",
                                  "password",
                                  digestPassword=True)

        # Add / authenticate / remove
        auth_db.add_user("mike", "password", roles=["dbOwner"])
        self.addCleanup(remove_all_users, auth_db)
        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")
        db.authenticate("mike", "password")
        db.logout()

        # Unicode name and password.
        db.authenticate(u"mike", u"password")
        db.logout()

        auth_db.remove_user("mike")
        self.assertRaises(OperationFailure, db.authenticate, "mike",
                          "password")

        # Add / authenticate / change password
        self.assertRaises(OperationFailure, db.authenticate, "Gustave",
                          u"Dor\xe9")
        auth_db.add_user("Gustave", u"Dor\xe9", roles=["dbOwner"])
        db.authenticate("Gustave", u"Dor\xe9")

        # Change password.
        auth_db.add_user("Gustave", "password", roles=["dbOwner"])
        db.logout()
        self.assertRaises(OperationFailure, db.authenticate, "Gustave",
                          u"Dor\xe9")
        self.assertTrue(db.authenticate("Gustave", u"password"))

        if not client_context.version.at_least(2, 5, 3, -1):
            # Add a readOnly user
            with ignore_deprecations():
                auth_db.add_user("Ross", "password", read_only=True)

            db.logout()
            db.authenticate("Ross", u"password")
            self.assertTrue(
                auth_db.system.users.find({
                    "readOnly": True
                }).count())
Ejemplo n.º 34
0
 def test_client_open(self):
     cx = self.motor_client()
     with ignore_deprecations():
         self.assertEqual(cx, (yield cx.open()))
         self.assertEqual(cx, (yield cx.open()))  # Same the second time.
Ejemplo n.º 35
0
 def test_client_open(self):
     cx = self.asyncio_client()
     with ignore_deprecations():
         self.assertEqual(cx, (yield from cx.open()))
         self.assertEqual(cx, (yield from cx.open()))  # Same, second time.