Example #1
0
    def test_session_calls(self):
        """test session related methods"""
        c = Cloudant(
            self.username,
            self.password,
            url='https://steve.cloudant.com',
            x_cloudant_user=self.username
            )
        c.connect()

        self.assertTrue(self.mock_session.called)

        self.assertEqual(
            self.mock_instance.auth,
            (self.username, self.password)
        )

        self.assertEqual(
            self.mock_instance.headers['X-Cloudant-User'], 
            self.username
        )

        self.assertIsNotNone(self.mock_instance.headers['User-Agent'])

        self.assertEqual('COOKIE', c.session_cookie())

        self.assertTrue(self.mock_instance.get.called)
        self.mock_instance.get.assert_has_calls(
            [ mock.call('https://steve.cloudant.com/_session') ]
        )

        self.assertTrue(self.mock_instance.post.called)
        self.mock_instance.post.assert_has_calls(
            [ mock.call(
                  'https://steve.cloudant.com/_session',
                  headers={'Content-Type': 'application/x-www-form-urlencoded'},
                  data={'password': '******', 'name': 'steve'}
            ) ]
        )

        c.disconnect()
        self.assertTrue(self.mock_instance.delete.called)
        self.mock_instance.delete.assert_has_calls(
            [ mock.call('https://steve.cloudant.com/_session') ]
        )
Example #2
0
    def test_session_calls(self):
        """test session related methods"""
        c = Cloudant(self.username, self.password)
        c.connect()

        self.failUnless(self.mock_session.called)

        self.assertEqual(
            self.mock_instance.auth,
            (self.username, self.password)
        )
        self.assertEqual(
            self.mock_instance.headers,
            {'X-Cloudant-User': self.username}
        )

        self.assertEqual('COOKIE', c.session_cookie())

        self.failUnless(self.mock_instance.get.called)
        self.mock_instance.get.assert_has_calls(
            mock.call('https://steve.cloudant.com/_session')
        )

        self.failUnless(self.mock_instance.post.called)
        self.mock_instance.post.assert_has_calls(
            mock.call(
                'https://steve.cloudant.com/_session',
                headers={'Content-Type': 'application/x-www-form-urlencoded'},
                data={'password': '******', 'name': 'steve'}
            )
        )

        c.disconnect()
        self.failUnless(self.mock_instance.delete.called)
        self.mock_instance.delete.assert_has_calls(
            mock.call('https://steve.cloudant.com/_session')
        )
class UnitTestDbBase(unittest.TestCase):
    """
    The base class for all unit tests targeting a database
    """

    @classmethod
    def setUpClass(cls):
        """
        If targeting CouchDB, Set up a CouchDB instance otherwise do nothing.
          
        Note: Admin Party is currently unsupported so we must create a 
          CouchDB user for tests to function with a CouchDB instance if one is
          not provided.
        """
        if os.environ.get('RUN_CLOUDANT_TESTS') is None:
            if os.environ.get('DB_URL') is None:
                os.environ['DB_URL'] = 'http://127.0.0.1:5984'

            if os.environ.get('DB_USER') is None:
                os.environ['DB_USER_CREATED'] = '1'
                os.environ['DB_USER'] = '******'.format(
                    unicode_(uuid.uuid4())
                    )
                os.environ['DB_PASSWORD'] = '******'
                resp = requests.put(
                    '{0}/_config/admins/{1}'.format(
                        os.environ['DB_URL'],
                        os.environ['DB_USER']
                        ),
                    data='"{0}"'.format(os.environ['DB_PASSWORD'])
                    )
                resp.raise_for_status()

    @classmethod
    def tearDownClass(cls):
        """
        If necessary, clean up CouchDB instance once all tests are complete.
        """
        if (os.environ.get('RUN_CLOUDANT_TESTS') is None and
            os.environ.get('DB_USER_CREATED') is not None):
            resp = requests.delete(
                '{0}://{1}:{2}@{3}/_config/admins/{4}'.format(
                    os.environ['DB_URL'].split('://', 1)[0],
                    os.environ['DB_USER'],
                    os.environ['DB_PASSWORD'],
                    os.environ['DB_URL'].split('://', 1)[1],
                    os.environ['DB_USER']
                    )
                )
            del os.environ['DB_USER_CREATED']
            del os.environ['DB_USER']
            resp.raise_for_status()

    def setUp(self):
        """
        Set up test attributes for unit tests targeting a database
        """
        if os.environ.get('RUN_CLOUDANT_TESTS') is None:
            self.user = os.environ['DB_USER']
            self.pwd = os.environ['DB_PASSWORD']
            self.url = os.environ['DB_URL']
            self.client = CouchDB(self.user, self.pwd, url=self.url)
        else:
            self.account = os.environ.get('CLOUDANT_ACCOUNT')
            self.user = os.environ.get('DB_USER')
            self.pwd = os.environ.get('DB_PASSWORD')
            self.url = os.environ.get(
                'DB_URL',
                'https://{0}.cloudant.com'.format(self.account))
            self.client = Cloudant(
                self.user,
                self.pwd,
                url=self.url,
                x_cloudant_user=self.account)

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

    def db_set_up(self):
        """
        Set up test attributes for Database tests
        """
        self.client.connect()
        self.test_dbname = self.dbname()
        self.db = self.client._DATABASE_CLASS(self.client, self.test_dbname)
        self.db.create()

    def db_tear_down(self):
        """
        Reset test attributes for each test
        """
        self.db.delete()
        self.client.disconnect()
        del self.test_dbname
        del self.db

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

    def populate_db_with_documents(self, doc_count=100):
        docs = [
            {'_id': 'julia{0:03d}'.format(i), 'name': 'julia', 'age': i}
            for i in range(doc_count)
        ]
        return self.db.bulk_docs(docs)
class CloudantAccountTests(UnitTestDbBase):
    """
    Cloudant specific Account unit tests
    """
    
    def test_constructor_with_account(self):
        """
        Test instantiating an account object using an account name
        """
        # Ensure that the client is new
        del self.client
        self.client = Cloudant(self.user, self.pwd, account=self.account)
        self.assertEqual(
            self.client.cloudant_url,
            'https://{0}.cloudant.com'.format(self.account)
            )

    def test_connect_headers(self):
        """
        Test that the appropriate request headers are set
        """
        try:
            self.client.connect()
            self.assertEqual(
                self.client.r_session.headers['X-Cloudant-User'],
                self.account
                )
            agent = self.client.r_session.headers.get('User-Agent')
            self.assertTrue(agent.startswith('python-cloudant'))
        finally:
            self.client.disconnect()

    def test_billing_data(self):
        """
        Test the retrieval of billing data
        """
        try:
            self.client.connect()
            expected = [
                'data_volume',
                'total',
                'start',
                'end',
                'http_heavy',
                'http_light'
                ]
            # Test using year and month
            year = datetime.now().year
            month = datetime.now().month
            data = self.client.bill(year, month)
            self.assertTrue(all(x in expected for x in data.keys()))
            #Test without year and month arguments
            del data
            data = self.client.bill()
            self.assertTrue(all(x in expected for x in data.keys()))
        finally:
            self.client.disconnect()

    def test_volume_usage_data(self):
        """
        Test the retrieval of volume usage data
        """
        try:
            self.client.connect()
            expected = [
                'data_vol',
                'granularity',
                'start',
                'end'
                ]
            # Test using year and month
            year = datetime.now().year
            month = datetime.now().month
            data = self.client.volume_usage(year, month)
            self.assertTrue(all(x in expected for x in data.keys()))
            #Test without year and month arguments
            del data
            data = self.client.volume_usage()
            self.assertTrue(all(x in expected for x in data.keys()))
        finally:
            self.client.disconnect()

    def test_requests_usage_data(self):
        """
        Test the retrieval of requests usage data
        """
        try:
            self.client.connect()
            expected = [
                'requests',
                'granularity',
                'start',
                'end'
                ]
            # Test using year and month
            year = datetime.now().year
            month = datetime.now().month
            data = self.client.requests_usage(year, month)
            self.assertTrue(all(x in expected for x in data.keys()))
            #Test without year and month arguments
            del data
            data = self.client.requests_usage()
            self.assertTrue(all(x in expected for x in data.keys()))
        finally:
            self.client.disconnect()

    def test_shared_databases(self):
        """
        Test the retrieval of shared database list
        """
        try:
            self.client.connect()
            self.assertIsInstance(self.client.shared_databases(), list)
        finally:
            self.client.disconnect()

    def test_generate_api_key(self):
        """
        Test the generation of an API key for this account
        """
        try:
            self.client.connect()
            expected = ['key', 'password', 'ok']
            api_key = self.client.generate_api_key()
            self.assertTrue(all(x in expected for x in api_key.keys()))
            self.assertTrue(api_key['ok'])
        finally:
            self.client.disconnect()

    def test_cors_configuration(self):
        """
        Test the retrieval of the current CORS configuration for this account
        """
        try:
            self.client.connect()
            expected = ['allow_credentials', 'enable_cors', 'origins']
            cors = self.client.cors_configuration()
            self.assertTrue(all(x in expected for x in cors.keys()))
        finally:
            self.client.disconnect()

    def test_cors_origins(self):
        """
        Test the retrieval of the CORS origins list
        """
        try:
            self.client.connect()
            origins = self.client.cors_origins()
            self.assertIsInstance(origins, list)
        finally:
            self.client.disconnect()

    def test_disable_cors(self):
        """
        Test disabling CORS (assuming CORS is enabled)
        """
        try:
            self.client.connect()
            # Save original CORS settings
            save = self.client.cors_configuration()
            # Test CORS disable
            self.assertEqual(self.client.disable_cors(), {'ok': True})
            # Restore original CORS settings
            self.client.update_cors_configuration(
                save['enable_cors'],
                save['allow_credentials'],
                save['origins'],
                True
                )
        finally:
            self.client.disconnect()

    def test_update_cors_configuration(self):
        """
        Test updating CORS configuration
        """
        try:
            self.client.connect()
            # Save original CORS settings
            save = self.client.cors_configuration()
            # Test updating CORS settings, overwriting origins
            result = self.client.update_cors_configuration(
                True,
                True,
                ['https://ibm.com'],
                True)
            self.assertEqual(result, {'ok': True})
            updated_cors = self.client.cors_configuration()
            self.assertTrue(updated_cors['enable_cors'])
            self.assertTrue(updated_cors['allow_credentials'])
            expected = ['https://ibm.com']
            self.assertTrue(all(x in expected for x in updated_cors['origins']))
            # Test updating CORS settings, adding to origins
            result = self.client.update_cors_configuration(
                True,
                True,
                ['https://ibm.cloudant.com']
                )
            self.assertEqual(result, {'ok': True})
            del updated_cors
            updated_cors = self.client.cors_configuration()
            self.assertTrue(updated_cors['enable_cors'])
            self.assertTrue(updated_cors['allow_credentials'])
            expected.append('https://ibm.cloudant.com')
            self.assertTrue(all(x in expected for x in updated_cors['origins']))
            # Restore original CORS settings
            self.client.update_cors_configuration(
                save['enable_cors'],
                save['allow_credentials'],
                save['origins'],
                True
                )
        finally:
            self.client.disconnect()
        data['content'] = result[1]
        data['timestamp'] = result[2]
        insert_to_cloudant(data)


def insert_to_cloudant(data):
    """
    """
    global inserted_counter
    # Create document content data
    # Create a document using the Database API
    my_document = db.create_document(data)

    # Check that the document exists in the database
    if my_document.exists():
        print 'SUCCESS!!'
        inserted_counter += 1


import sqlite3
conn = sqlite3.connect('database-fts.sqlite')
c = conn.cursor()

c.execute("SELECT title, content, timestamp FROM notes WHERE title='2visit'")
results = c.fetchall()
parse_results(results)

# Disconnect from the account
client.disconnect()

print inserted_counter
Example #6
0
class Login:
    """This class deals with all login and logout
    Functions: log_in(username, password): Returns true for success, false for failure
    log_state: returns if you are logged in or not
    log_out: Logs out, returns true
    get_user: Returns username
    get_usergroup: Returns usergroup
    TODO: Implement log of attempts
    """
    def __init__(self):
        self.state = False  # Am I logged in?
        self.current_user = ""
        self.current_usergroup = 0

    def log_state(self):
        return self.state

    def get_user(self):
        return self.current_user

    def get_usergroup(self):
        """Usergroup 1: Admin
        Usergroup 2: User"""
        return self.usergroup

    # Todo: Save to files
    def log_of_attempts(self):
        return True

    def log_in(self, user, password):

        # Connect to database
        USERNAME = ""  # ADD YOUR OWN
        PASSWORD = ""  # ADD YOUR OWN
        URL = ""  # ADD YOUR OWN
        self.client = Cloudant(USERNAME, PASSWORD, url=URL)
        self.client.connect()

        # Get users database
        # print 'Databases: {0}'.format(self.client.all_dbs()) # Debugging
        login_db = self.client[u'users']
        # print type(login_db) # debugging

        # TODO: Get from own class
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

        # if user in self.users:
        user_found = Document(login_db, user)

        if user_found.exists():

            # Get password from DB
            with Document(login_db, user) as document:
                temp_pass = document[u'password']
                temp_usergroup = document[u'usergroup']

            if password == temp_pass:
                self.log_of_attempts  # userlogins.append([user, password, st])
                self.state = True
                self.current_user = user
                self.current_usergroup = int(temp_usergroup)
                return True
            else:
                self.log_of_attempts  # userrequests.append([user, password, st])
                print "Wrong password"
                return False
        else:
            self.log_of_attempts  # userrequests.append([user, password, st])
            print "User not found"
            return False

    def log_out(self):
        self.current_usergroup = 0
        self.current_user = ""
        self.state = False
        self.client.disconnect()  # disconnect to DB
        return True