Ejemplo n.º 1
0
def upload(t_pretty, filename, manual=False):
    print('Uploading to db...')

    # compute the pk for this new entry
    db = CloudantDatabase(client, db_name)
    resp = db.get_view_raw_result('_design/view', 'log', reduce=True)
    if not resp['rows']:
        pk = 1
    else:
        pk = resp['rows'][0]['value']
        pk += 1

    docid = 'log:' + str(pk)
    data = {
        '_id'      : docid,
        'pk'       : pk,
        'timestamp': t_pretty,
        'filename' : filename,
        'manual'   : manual
    }
    new_document = client[db_name].create_document(data)
    fp = open('img/'+filename, 'rb')
    data = fp.read()
    fp.close()
    new_document.put_attachment(filename, 'image/jpeg', data)
    if new_document.exists():
        print('Upload success!')
        # send live feed to webpage
        payload = {'type': 'doc', 'doc': new_document}
        pubnub.publish(pubnub_channel_pi, payload)
        return docid

    print('Failed to upload image.')
    return False
Ejemplo n.º 2
0
    def get_sentiment_user(self, db, date_begin, date_end):
        db = CloudantDatabase(self.client, db, partitioned=False)
        days = get_days(date_begin, date_end)

        while not db.exists():
            time.sleep(0.1)

        results = {'negative': 0, 'neutral': 0, 'positive': 0}
        cou = 0
        hash_count = {}
        related = 0
        hash_cou = 0
        for tweet_data in db:
            results[tweet_data['simple_sentiment_label']] += 1
            cou += 1
            flag = 0
            for hash in tweet_data['hashtags']:
                hash_cou += 1
                hash = hash.lower()
                if 'covid' in hash or 'corona' in hash or ('19' in hash and 'co' in hash) \
                        or 'home' in hash or 'lock' in hash or 'safe' in hash:
                    flag = 1

                hash_count[hash] = hash_count.get(hash, 0) + 1

            related += flag

        results['count'] = cou
        results['hashtags'] = sorted(hash_count.items(),
                                     key=lambda item: item[1],
                                     reverse=True)
        results['coronavirus_related'] = related
        results['hashtag_count'] = hash_cou
        db.delete()
        return results
Ejemplo n.º 3
0
    def get_tweet_count_today(self, region, date=datetime.datetime.today()):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        counts = 0

        for re in db.get_partitioned_view_result(date, '_design/tweet_count',
                                                 'tweet_count'):
            counts += re['value']
        return {'count': counts}
Ejemplo n.º 4
0
 def get_user_info(self, emailAddress):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     selector = {'emailAddress': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)[0]
     except Exception as e:
         raise
     else:
         return res[0]
Ejemplo n.º 5
0
    def get_corona(self, region, date_begin, date_end):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        counts = 0
        for day in days:
            for re in db.get_partitioned_view_result(
                    day, '_design/coronavirus_related', 'coronavirus_related'):
                counts += re['value']
        return {'count': counts}
Ejemplo n.º 6
0
 def create_index(cls):
     """
     Create an Indexs for the "page_id" attribute
     """
     with cloudant(USERNAME, PASSWORD, url=URL) as client:
         clouddb = CloudantDatabase(client, DBNAME)
         clouddb.create_query_index(index_name='pageid-index',
                                    index_type='text',
                                    fields=[{
                                        "name": "page_id",
                                        "type": "string"
                                    }])
Ejemplo n.º 7
0
 def get_user_tasks(self, emailAddress):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     if not database.exists():
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     selector = {'user': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)
     except Exception as e:
         raise
     else:
         return res
Ejemplo n.º 8
0
    def get_sentiment(self, region, date_begin, date_end):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        counts = {'negative': 0, 'neutral': 0, 'positive': 0}
        for day in days:
            for re in db.get_partitioned_view_result(day,
                                                     '_design/sentiment_count',
                                                     'sentiment_count',
                                                     group_level=1):
                counts[re['key']] += re['value']
        return counts
Ejemplo n.º 9
0
    def __enter__(self):
        """
        Runs when the control flow enters the with() statement.
        Creates the Cloudant client instant and the Cloudant database instant.

        To connect to the world readable database, I had to use the 'admin_party' flag.
        """
        self.client = Cloudant(" ",
                               " ",
                               admin_party=True,
                               url=self.url,
                               connect=True)

        self.db = CloudantDatabase(self.client, self.db_name)

        return self
Ejemplo n.º 10
0
    def get_aurin(self, region, types):
        mapping = {
            'income': "income_num(aud)",
            'labor': "labour_force_num",
            'participation': "Participation_rate%",
            'unemployment': "Unemployment_rate%",
            'highedu': "higher_education_rate%",
            'male': "Male",
            'female': "Female"
        }
        db = CloudantDatabase(self.client, 'aurin', partitioned=False)

        if self.dic is None:
            self.dic = {
                '_'.join(filter(lambda x: x[0] != '(',
                                key.split())).lower().replace('-', '_'): key
                for key in db['aurin_data'].keys()
            }

        if region[-1] == ')':
            re = 'unincorporated_vic'
        else:
            re = region.lower().replace(' ', '_').replace('-', '_')

        if re in self.dic:
            if types == 'all':
                return {
                    key: db['aurin_data'][self.dic[re]][value]
                    for key, value in mapping.items()
                }
            return db['aurin_data'][self.dic[re]].get(mapping.get(types, ""),
                                                      -1)
        else:
            return -1
Ejemplo n.º 11
0
 def update_schedule_status(self, doc_id, to_value):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
     remote_doc = Document(database, doc_id)
     remote_doc.update_field(action=remote_doc.field_set,
                             field='status',
                             value=to_value)
Ejemplo n.º 12
0
    def get_overview(self, date_begin, date_end):
        db = CloudantDatabase(self.client, 'daily_increase', partitioned=False)
        days = get_days(date_begin, date_end)

        results = {}
        keys = db.keys(remote=True)

        for day in days:
            if day in keys:
                res = db[day]
                results[day] = {
                    key: value
                    for key, value in res.items()
                    if key != '_id' and key != '_rev'
                }

        return results
Ejemplo n.º 13
0
 def update_user_info(self, doc_id, update_field, to_value):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     remote_doc = Document(database, doc_id)
     remote_doc.update_field(action=remote_doc.field_set,
                             field=update_field,
                             value=to_value)
Ejemplo n.º 14
0
 def is_authorized(self, emailAddress, report_level, request_access):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     selector = {'emailAddress': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)[0]
     except Exception:
         return False
     else:
         if res and \
                 ((res[0]['approved_country_accesses'] and \
                 request_access in res[0]['approved_country_accesses']) \
                 or (res[0]['approved_company_accesses'] and \
                 request_access in res[0]['approved_company_accesses'])):
             return True
         else:
             return False
Ejemplo n.º 15
0
 def get_cloudant_doc(itemID):
     client = Cloudant.iam(app.config["USER"],
                           app.config["APIKEY"],
                           connect=True)
     client.connect()
     database = CloudantDatabase(client, "marketplace-history-database")
     with Document(database,
                   document_id=f"marketplace-history-{itemID}") as document:
         return (document)
Ejemplo n.º 16
0
def main():
    client = Cloudant(config.username, config.password, account=config.account)

    client.connect()

    dbs = client.all_dbs()

    output = []
    for db in dbs:
        print 'Retrieving stats for {0}...'.format(db)
        db = CloudantDatabase(client, db)
        print "db: " + json.dumps(db)
        output.append(db.doc_count())

        print json.dumps(output, indent=4)
        print json.dumps(sort(output), indent=4)

    client.disconnect()
Ejemplo n.º 17
0
def main():
    client = Cloudant(config.username, config.password, account=config.account)

    client.connect()

    dbs = client.all_dbs()

    output = []
    for db in dbs:
    	print 'Retrieving stats for {0}...'.format(db)
        db = CloudantDatabase(client, db)
        print "db: " + json.dumps(db)
        output.append(db.doc_count())

	print json.dumps(output, indent=4)
	print json.dumps(sort(output), indent=4)

    client.disconnect()
Ejemplo n.º 18
0
    def setUp(self):
        self.mock_session = mock.Mock()
        self.mock_session.get = mock.Mock()
        self.mock_session.post = mock.Mock()
        self.mock_session.put = mock.Mock()
        self.mock_session.delete = mock.Mock()

        self.account = mock.Mock()
        self.account.cloudant_url = "https://bob.cloudant.com"
        self.account.r_session = self.mock_session

        self.username = "******"
        self.db_name = "testdb"
        self.cl = CloudantDatabase(self.account, self.db_name)

        self.sec_doc = {
            "_id": "_security",
            "cloudant": {
                "someapikey": [
                    "_reader"
                ],
                "nobody": [],
                "bob": [
                    "_writer",
                    "_admin",
                    "_replicator",
                    "_reader"
                ]
            }
        }

        self.shards = {
            "shards": {
                "00000000-3fffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "40000000-7fffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "80000000-bfffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "c0000000-ffffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ]
            }
        }
Ejemplo n.º 19
0
def patient_details():
    if (request.method == "POST"):
        allergies = request.form["allergies"]
        immunizations = request.form["immunizations"]
        observations = request.form["observations"]
        procedures = request.form["procedures"]
        careplans = request.form["careplans"]
        medications = request.form["medications"]
        current = request.form["current"]
        #flash("Patient Details Successfully Updated !!!",category="success")

        ## code to store this info in the database
        username = "******"
        apikey = "HAltxJaD5Sr4VsbAVB4-rYLfWdrWOkW0fWuqzQFP_Ra_"
        client = Cloudant.iam(username, apikey, connect=True)

        db_name = "patient_details"
        p_details = CloudantDatabase(client, db_name)

        date_v = str(date.today())
        encounter_id = str(session["user_id"]) + '_' + date_v
        if p_details.exists():

            patient_document = {
                "allergies": allergies,
                "immunizations": immunizations,
                "observations": observations,
                "procedures": procedures,
                "careplans": careplans,
                "medications": medications,
                "current": current,
                "encounter_id": encounter_id,
                "date": date_v
            }
            p_details.create_document(patient_document)
        #flash("Data Added Successfully !")
        client.disconnect()
        flash("Patient Details Successfully Updated !!!", category="success")

        return redirect(url_for("patient_details"))

    return render_template("p_details.html")
Ejemplo n.º 20
0
    def init_user(self, userinfo, status='active'):

        database = CloudantDatabase(
            self.client,
            self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
        doc = {
            "emailAddress": userinfo.get('emailAddress'),
            "firstName": userinfo.get('firstName'),
            "lastName": userinfo.get('lastName'),
            "uid": userinfo.get('uid'),
            "approved_country_accesses": None,
            "approved_company_accesses": None,
            "pending_country_accesses": None,
            "pending_company_accesses": None,
            "status": status,
            "init time": time.ctime()
        }
        if database.exists():
            database.create_document(doc)
        else:
            return False
Ejemplo n.º 21
0
    def get_all_overview(self):
        db = CloudantDatabase(self.client, 'daily_increase', partitioned=False)
        results = {}

        for day_data in db:
            results[day_data['_id']] = {
                key: value
                for key, value in day_data.items()
                if key != '_id' and key != '_rev'
            }

        return results
Ejemplo n.º 22
0
    def get_hashtag_overview(self, region, date_begin, date_end, top):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        results = {}
        for day in days:
            tmp_re = db.get_partitioned_view_result(day,
                                                    '_design/hashtag_count',
                                                    'hashtag_count',
                                                    group_level=1,
                                                    limit=1000)
            for re in tmp_re[:]:
                results[re['key'].lower()] = results.get(re['key'].lower(),
                                                         0) + re['value']
        if top:
            return sorted(results.items(),
                          key=lambda item: item[1],
                          reverse=True)[:top]
        else:
            return sorted(results.items(),
                          key=lambda item: item[1],
                          reverse=True)
Ejemplo n.º 23
0
 def write_to_schedule(self, schedule_record):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
     append_info = {
         "status": 'active',
         "failure_counts": "0",
         "submit time": time.ctime()
     }
     new_document = schedule_record.copy()
     new_document.update(append_info)
     if database.exists():
         database.create_document(new_document)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
         database.create_document(new_document)
Ejemplo n.º 24
0
 def write_to_request(self, document, user=None, status=None):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     append_info = {
         "user": user,
         "status": status,
         "failure_counts": "0",
         "submit time": time.ctime()
     }
     new_document = document.copy()
     new_document.update(append_info)
     if database.exists():
         database.create_document(new_document)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
         database.create_document(new_document)
Ejemplo n.º 25
0
 def write_to_mail(self, to, sender, subject, confirm_link, requester):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_MAIL_DATABASE_NAME'])
     doc = {
         "to": to,
         "sender": sender,
         "subject": subject,
         "confirm_link": confirm_link,
         "requester": requester,
         "status": 'submitted',
         "submit time": time.ctime()
     }
     if database.exists():
         database.create_document(doc)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_MAIL_DATABASE_NAME'])
         database.create_document(doc)
Ejemplo n.º 26
0
class Couch:
    db = None
    c_db = None
    couch_db = None

    # usage: database = Couch(db_name)
    # fields: db_name -> str
    def __init__(self, db_name):
        server_config = Config(CONFIG_PATH).get('couchdb')
        self.client = CouchDB(server_config['username'],
                              server_config['password'],
                              url=server_config['server_addr'],
                              connect=True,
                              auto_renew=True)
        self.select_db(db_name)

    # Get one database selected; if the database doesn't exist, create it.
    # usage: database.select_db(db_name);
    # fields: db_name -> str
    def select_db(self, db_name):
        self.couch_db = CouchDatabase(self.client, db_name)
        if not self.couch_db.exists():
            self.couch_db.create()
        self.db = self.client[db_name]
        self.c_db = CloudantDatabase(self.client, db_name)

    # usage: database.close()
    # Database should be closed when finish using
    def close(self):
        self.client.disconnect()

    # Get count of documents in current database;
    # usage database.count();
    def count(self):
        return self.couch_db.doc_count()

    # Get everything from the database;
    # usage: database.query_all();
    # note: after query_all, iterate the returned item to get every document
    def query_all(self):
        qlist = []
        for doc in self.db:
            qlist.append(doc)
        return qlist

    # Select something from the database;
    # usage: database.query(selector);
    # fields: selector -> Dictionary
    # note: after query, iterate the returned item to get every document
    def query(self, selector):
        qlist = []
        result = self.c_db.get_query_result(selector)
        for doc in result:
            qlist.append(doc)
        return qlist

    def query_multiple(self, selectors):
        qlist = []
        for selector in selectors:
            qlist += self.query(selector)
        return qlist

    # insert operation of the database;
    # usage: database.insert(doc);
    # fields: doc -> Dictionary
    def insert(self, doc):
        doc['timestamp'] = _timestamp()
        document = self.db.create_document(doc)
        if document.exists():
            return document['_id']

    def distinct_insert(self, doc):
        query_res = self.query(doc)
        if len(query_res) == 0:
            return self.insert(doc)
        return query_res[0]['_id']

    # update operation of the database;
    # usage: database.update(field, old_value, new_value)
    # fields: field -> str; value -> str; new_value -> str
    def update(self, selector, field, new_value):
        q_res = self.c_db.get_query_result(selector)
        for document in q_res:
            doc_id = document['_id']
            doc = Document(self.db, doc_id)
            doc.update_field(action=doc.field_set,
                             field=field,
                             value=new_value)
            doc.update_field(action=doc.field_set,
                             field='timestamp',
                             value=_timestamp())

    # delete operation of the database;
    # usage: database.delete(selector)
    # fields: selector -> Dictionary
    def delete(self, selector):
        q_res = self.c_db.get_query_result(selector)
        for document in q_res:
            id = document['_id']
            rev = document['_rev']
            doc = Document(self.db, id)
            doc['_rev'] = rev
            doc.delete()

    def move_doc(self, selector, target):
        """
        Move documents from current database to target database.
        :param selector: dictionary
        :param target: string, db name
        :return:
        """
        documents = self.query(selector)
        for doc in documents:
            del doc['_id']
            del doc['_rev']
            Couch(target).distinct_insert(doc)
        self.delete(selector)

    def query_latest_change(self, selector):
        """
        Query latest item sorted by timestamp. Returns only timestamp in documents.
        :param selector: dictionary
        :return: a list that contains 1 or 0 docs
        """
        q_res = self.query(selector)
        q_res = list(filter(lambda x: 'timestamp' in x.keys(), q_res))
        res = sorted(q_res, key=lambda x: x['timestamp'])
        return res[-1:]
Ejemplo n.º 27
0
class AirportDbClient:
    """
    Class to connect to the world readable Cloudant database. The class is a
    context manager, and must be used inside a with() statement.

    List of airports can be pulled from the database with a rectangle search query.

    Attributes:
        url (str): The url of the Cloudant account.
        db_name (str): Name of the Cloudant database.
        design_doc (str): Name of the design document.
        search_index (str): The search index used.
        client (Cloudant): Cloudant client instance.
        db (CloudantDatabase): Cloudant database instance.
    """
    def __init__(self, url, db_name, design_doc, search_index):
        self.url = url
        self.db_name = db_name
        self.design_doc = design_doc
        self.search_index = search_index

    def __enter__(self):
        """
        Runs when the control flow enters the with() statement.
        Creates the Cloudant client instant and the Cloudant database instant.

        To connect to the world readable database, I had to use the 'admin_party' flag.
        """
        self.client = Cloudant(" ",
                               " ",
                               admin_party=True,
                               url=self.url,
                               connect=True)

        self.db = CloudantDatabase(self.client, self.db_name)

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Runs when the control flow leaves the with() statement.
        """
        self.client.disconnect()

    @staticmethod
    def _format_query(rect):
        """
        Formats the query in the format of 'lat:[X TO Y] AND lon:[V TO Z]'.
        Creates one or two queries, depending on its input.

        Args:
            rect (list): List of 4 (lat1, lat2, lon1, lon2) floats or
                    list of 6 (lat1, lat2, lon1, lon2, lon3, lon4) floats.

        Returns:
            list: List of one query string, or two query strings.
        """

        if len(rect) == 4:
            query = f"lat:[{rect[0]} TO {rect[1]}] AND lon:[{rect[2]} TO {rect[3]}]"
            return [query]

        qr1 = f"lat:[{rect[0]} TO {rect[1]}] AND lon:[{rect[2]} TO {rect[3]}]"
        qr2 = f"lat:[{rect[0]} TO {rect[1]}] AND lon:[{rect[4]} TO {rect[5]}]"

        return [qr1, qr2]

    def get_search_results(self, rectangles):
        """
        Getting all of the search results from the database based on the queries submitted.

        Args:
            rectangles (list): Rectangle data for the query.
                Or data for two rectangles if 2 query is present.

        Returns:
            list: The list of airports from the database.

        Raises:
            AirportDbException: Every problem with the database and its connection (e.g.
                no internet, or wrong url and name etc.)
                No errors occur when the Cloudant client and database instance are created,
                therefore errors are only raised here, when the search method is called,
                because this is where the Cloudant database is actively used.
        """

        queries = self._format_query(rectangles)
        total_number = 0
        results = []

        try:
            for qr in queries:  # 1 or 2 queries

                # The max limit of results pulled at once for a request is 200.
                # Hence, when there are more than 200 results, multiple requests
                # must be sent.

                q_result = self.db.get_search_result(self.design_doc,
                                                     self.search_index,
                                                     query=qr,
                                                     limit=200)

                # NOTE: when 0 airports match the query, q_result will
                # look like {"total_rows":0,"bookmark":"g2o","rows":[]}

                # NOTE: the 'total_rows' field contains the total number of results,
                # not the number of results in the current query result.

                total_number = total_number + q_result['total_rows']
                results.extend([r['fields'] for r in q_result['rows']])

                while len(results
                          ) < total_number:  # Paging through all the results

                    # To get to the next page of results, the bookmark
                    # field of the previous request is used.
                    bookmark = q_result['bookmark']

                    q_result = self.db.get_search_result(self.design_doc,
                                                         self.search_index,
                                                         query=qr,
                                                         limit=200,
                                                         bookmark=bookmark)

                    results.extend([r['fields'] for r in q_result['rows']])

        except Exception as ex:  # Any problem when trying to connect to and use the database
            raise AirportDbException(ex)

        return results
 def __get_db(self, **connection_parameters):
     try:
         _client = CouchDB(**connection_parameters)
         return CloudantDatabase(_client, 'airportdb')
     except Exception as e:
         print(e)
Ejemplo n.º 29
0
class CloudantDBTest(unittest.TestCase):
    """
    Tests for additional Cloudant database features
    """
    def setUp(self):
        self.mock_session = mock.Mock()
        self.mock_session.get = mock.Mock()
        self.mock_session.post = mock.Mock()
        self.mock_session.put = mock.Mock()
        self.mock_session.delete = mock.Mock()

        self.account = mock.Mock()
        self.account.cloudant_url = "https://bob.cloudant.com"
        self.account.r_session = self.mock_session

        self.username = "******"
        self.db_name = "testdb"
        self.cl = CloudantDatabase(self.account, self.db_name)

        self.sec_doc = {
            "_id": "_security",
            "cloudant": {
                "someapikey": [
                    "_reader"
                ],
                "nobody": [],
                "bob": [
                    "_writer",
                    "_admin",
                    "_replicator",
                    "_reader"
                ]
            }
        }

        self.shards = {
            "shards": {
                "00000000-3fffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "40000000-7fffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "80000000-bfffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ],
                "c0000000-ffffffff": [
                    "*****@*****.**",
                    "*****@*****.**",
                    "*****@*****.**"
                ]
            }
        }

    def test_security_doc(self):
        mock_resp = mock.Mock()
        mock_resp.json = mock.Mock(return_value=self.sec_doc)
        self.mock_session.get = mock.Mock(return_value=mock_resp)

        security_doc = self.cl.security_document()

        self.assertTrue(self.mock_session.get.called)
        self.assertDictEqual(security_doc, self.sec_doc)

    def test_shared_dbs(self):
        # share database
        mock_sec_doc = mock.Mock()
        mock_sec_doc.json.return_value = self.sec_doc
        self.mock_session.get.return_value = mock_sec_doc
        self.mock_session.put.return_value = mock_sec_doc

        shared_resp = self.cl.share_database(
            'someotheruser',
            reader=True,
            writer=True
        )

        self.assertTrue(self.mock_session.get.called)
        self.assertTrue(self.mock_session.put.called)
        self.assertIn('someotheruser', shared_resp['cloudant'])

        # unshare database
        unshared_resp = self.cl.unshare_database('someotheruser')
        self.assertNotIn('someotheruser', unshared_resp['cloudant'])

    def test_shards(self):
        mock_resp = mock.Mock()
        mock_resp.status_code = 200
        mock_resp.raise_for_status = mock.Mock()
        mock_resp.json = mock.Mock(return_value=self.shards)
        self.mock_session.get.return_value = mock_resp

        r = self.cl.shards()

        self.assertTrue(self.mock_session.get.called)
        self.assertEqual(r, self.shards)

    def test_missing_revs(self):
        doc_id = 'somedocument'
        ret_val = {
            "missing_revs": {doc_id: ['rev1']}
        }
        mock_resp = mock.Mock()
        mock_resp.status_code = 201
        mock_resp.raise_for_status = mock.Mock()
        mock_resp.json = mock.Mock(return_value=ret_val)
        self.mock_session.post.return_value = mock_resp

        missed_revs = self.cl.missing_revisions(doc_id, 'rev1', 'rev2', 'rev3')

        expected_data = {doc_id: ['rev1', 'rev2', 'rev3']}
        expected_url = posixpath.join(
            self.account.cloudant_url,
            self.db_name,
            '_missing_revs'
        )
        self.assertTrue(self.mock_session.post.called)
        self.mock_session.post.assert_called_once_with(
            expected_url,
            headers={'Content-Type': 'application/json'},
            data=json.dumps(expected_data)
        )
        self.assertEqual(missed_revs, ret_val["missing_revs"][doc_id])

    def test_revs_diff(self):
        doc_id = 'somedocument'
        ret_val = {
            doc_id: {
                "missing": ['rev1', 'rev3'],
                "possible_ancestors": ['rev2']
            }
        }
        mock_resp = mock.Mock()
        mock_resp.status_code = 201
        mock_resp.raise_for_status = mock.Mock()
        mock_resp.json = mock.Mock(return_value=ret_val)
        self.mock_session.post.return_value = mock_resp

        revs_diff = self.cl.revisions_diff(doc_id, 'rev1', 'rev2', 'rev3')

        expected_data = {doc_id: ['rev1', 'rev2', 'rev3']}
        expected_url = posixpath.join(
            self.account.cloudant_url,
            self.db_name,
            '_revs_diff'
        )
        self.assertTrue(self.mock_session.post.called)
        self.mock_session.post.assert_called_once_with(
            expected_url,
            headers={'Content-Type': 'application/json'},
            data=json.dumps(expected_data)
        )
        self.assertEqual(revs_diff, ret_val)

    def test_revs_limit(self):
        limit = 500
        expected_url = posixpath.join(
            self.account.cloudant_url,
            self.db_name,
            '_revs_limit'
        )

        # set rev limit
        mock_put = mock.Mock()
        mock_put.status_code = 201
        mock_put.raise_for_status = mock.Mock()
        mock_put.json = mock.Mock(return_value='{"ok": true}')
        self.mock_session.put.return_value = mock_put

        set_limit = self.cl.set_revision_limit(limit)

        self.assertTrue(self.mock_session.put.called)
        self.mock_session.put.assert_called_once_with(
            expected_url,
            data=json.dumps(limit)
        )
        self.assertEqual(set_limit, '{"ok": true}')

        # get rev limit
        mock_get = mock.Mock()
        mock_get.status_code = 200
        mock_get.raise_for_status = mock.Mock()
        mock_get.text = limit
        self.mock_session.get.return_value = mock_get

        get_limit = self.cl.get_revision_limit()

        self.assertTrue(self.mock_session.put.called)
        self.mock_session.get.assert_called_once_with(expected_url)
        self.assertEqual(get_limit, limit)

    def test_get_revs_limit_bad_resp(self):
        mock_get = mock.Mock()
        mock_get.status_code = 200
        mock_get.raise_for_status = mock.Mock()
        mock_get.text = 'bloop'
        self.mock_session.get.return_value = mock_get

        with self.assertRaises(CloudantException):
            resp = self.cl.get_revision_limit()
            self.assertTrue(self.mock_session.get.called)
            self.assertEqual(resp.status_code, 400)

    def test_view_cleanup(self):
        expected_url = posixpath.join(
            self.account.cloudant_url,
            self.db_name,
            '_view_cleanup'
        )

        mock_post = mock.Mock()
        mock_post.status_code = 201
        mock_post.raise_for_status = mock.Mock()
        mock_post.json = mock.Mock(return_value='{"ok": true}')
        self.mock_session.post.return_value = mock_post

        cleanup = self.cl.view_cleanup()

        self.assertTrue(self.mock_session.post.called)
        self.mock_session.post.assert_called_once_with(
            expected_url,
            headers={'Content-Type': 'application/json'}
        )
        self.assertEqual(cleanup, '{"ok": true}')
Ejemplo n.º 30
0
 def select_db(self, db_name):
     self.couch_db = CouchDatabase(self.client, db_name)
     if not self.couch_db.exists():
         self.couch_db.create()
     self.db = self.client[db_name]
     self.c_db = CloudantDatabase(self.client, db_name)