Esempio n. 1
0
 def test_basic_auth_str(self):
     c = CouchDB(self.username, self.password, url=self.url)
     auth_str = c.basic_auth_str()
     self.assertTrue(auth_str.startswith("Basic"))
     self.assertFalse(auth_str.endswith("Basic "))
     self.assertFalse(auth_str.endswith("Basic"))
class CouchDBAccountTests(unittest.TestCase):
    """
    CouchDB Class unit tests
    """

    @classmethod
    def setUpClass(self):
        """
        Set up CouchDB instance to be used by all tests

        If no user is specified then, assuming Admin Party and we
          need to create a user to run the CouchDB tests.
          
        Note: Admin Party is currently unsupported.
        """
        if os.environ.get('COUCHDB_URL') is None:
            os.environ['COUCHDB_URL'] = 'http://127.0.0.1:5984'

        if os.environ.get('COUCHDB_USER') is None:
            os.environ['COUCHDB_USER_CREATED'] = '1'
            os.environ['COUCHDB_USER'] = '******'.format(
                unicode(uuid.uuid4())
                )
            os.environ['COUCHDB_PASSWORD'] = '******'
            resp = requests.put(
                '{0}/_config/admins/{1}'.format(
                    os.environ['COUCHDB_URL'],
                    os.environ['COUCHDB_USER']
                    ),
                data='"{0}"'.format(os.environ['COUCHDB_PASSWORD'])
                )
            resp.raise_for_status()

    @classmethod
    def tearDownClass(self):
        """
        Clean up CouchDB instance once all tests are complete
        """
        if os.environ.get('COUCHDB_USER_CREATED') is not None:
            resp = requests.delete(
                '{0}://{1}:{2}@{3}/_config/admins/{4}'.format(
                    os.environ['COUCHDB_URL'].split('://', 1)[0],
                    os.environ['COUCHDB_USER'],
                    os.environ['COUCHDB_PASSWORD'],
                    os.environ['COUCHDB_URL'].split('://', 1)[1],
                    os.environ['COUCHDB_USER']
                    )
                )
            resp.raise_for_status()

    def setUp(self):
        """
        Set up test attributes for CouchDB Account tests
        """
        self.user = os.environ['COUCHDB_USER']
        self.pwd = os.environ['COUCHDB_PASSWORD']
        self.url = os.environ['COUCHDB_URL']
        self.client = CouchDB(self.user, self.pwd, url=self.url)

    def tearDown(self):
        """
        Ensure the client is new for each test
        """
        del self.client

    def dbname(self, database_name='account-unit-test-db'):
        return '{0}-{1}'.format(database_name, unicode(uuid.uuid4()))

    def test_constructor_with_url(self):
        """
        Test instantiating an account object using a URL
        """
        self.assertEqual(
            self.client.cloudant_url,
            self.url
            )
        self.assertEqual(self.client.encoder, json.JSONEncoder)
        self.assertIsNone(self.client.r_session)

    def test_connect(self):
        """
        Test connect and disconnect functionality
        """
        try:
            self.client.connect()
            self.assertIsInstance(self.client.r_session, requests.Session)
            self.assertEqual(self.client.r_session.auth, (self.user, self.pwd))
        finally:
            self.client.disconnect()
            self.assertIsNone(self.client.r_session)

    def test_session(self):
        """
        Test getting session information
        """
        try:
            self.client.connect()
            session = self.client.session()
            self.assertEqual(session['userCtx']['name'], self.user)
        finally:
            self.client.disconnect()

    def test_session_cookie(self):
        """
        Test getting the session cookie
        """
        try:
            self.client.connect()
            self.assertIsNotNone(self.client.session_cookie())
        finally:
            self.client.disconnect()

    def test_basic_auth_str(self):
        """
        Test getting the basic authentication string
        """
        try:
            self.client.connect()
            expected = 'Basic {0}'.format(
                base64.urlsafe_b64encode("{0}:{1}".format(self.user, self.pwd))
                )
            self.assertEqual(
                self.client.basic_auth_str(),
                expected
                )
        finally:
            self.client.disconnect()

    def test_all_dbs(self):
        """
        Test getting a list of all of the databases in the account
        """
        dbnames = []
        for _ in range(3):
            dbnames.append(self.dbname())
        try:
            self.client.connect()
            for dbname in dbnames:
                self.client.create_database(dbname)
            self.assertTrue(set(dbnames).issubset(self.client.all_dbs()))
        finally:
            for dbname in dbnames:
                self.client.delete_database(dbname)
            self.client.disconnect()

    def test_create_delete_database(self):
        """
        Test database creation and deletion
        """
        try:
            self.client.connect()
            dbname = self.dbname()
            # Create database
            db = self.client.create_database(dbname)
            self.assertTrue(db.exists())
            # Delete database
            self.assertIsNone(self.client.delete_database(dbname))
            self.assertFalse(db.exists())
        finally:
            self.client.disconnect()

    def test_create_existing_database(self):
        """
        Test creation of already existing database
        """
        dbname = self.dbname()
        try:
            self.client.connect()
            self.client.create_database(dbname)
            self.client.create_database(dbname, throw_on_exists=True)
            self.fail('Above statement should raise a CloudantException')
        except CloudantException, err:
            self.assertEqual(
                str(err),
                'Database {0} already exists'.format(dbname)
                )
        finally: