def test_create_document_with_docid(self):
     """
     Test creating a document providing an id
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     self.assertFalse(doc.exists())
     self.assertIsNone(doc.get('_rev'))
     doc.create()
     self.assertTrue(doc.exists())
     self.assertTrue(doc.get('_rev').startswith('1-'))
 def test_create_document_with_docid_encoded_url(self):
     """
     Test creating a document providing an id that has an encoded url
     """
     doc = Document(self.db, 'http://example.com')
     doc['name'] = 'julia'
     doc['age'] = 6
     self.assertFalse(doc.exists())
     self.assertIsNone(doc.get('_rev'))
     doc.create()
     self.assertTrue(doc.exists())
     self.assertTrue(doc.get('_rev').startswith('1-'))
Esempio n. 3
0
def read(poll_id):
    if request.method == 'GET':
        doc = Document(couch, poll_id)
        doc.fetch()
        return doc.json()
    if request.method == 'POST':
        data = request.get_json()
        data['pollID'] = poll_id
        data['remote_addr'] = request.remote_addr
        data['user_agent'] = request.headers.get('User-Agent')
        doc = couch.create_document(data)
        return doc['_id'], 201
Esempio n. 4
0
 def test_list_field_append_successfully(self):
     """
     Test the static helper method to successfully append to a list field.
     """
     doc = Document(self.db)
     self.assertEqual(doc, {})
     doc.list_field_append(doc, 'pets', 'cat')
     self.assertEqual(doc, {'pets': ['cat']})
     doc.list_field_append(doc, 'pets', 'dog')
     self.assertEqual(doc, {'pets': ['cat', 'dog']})
     doc.list_field_append(doc, 'pets', None)
     self.assertEqual(doc, {'pets': ['cat', 'dog']})
Esempio n. 5
0
 def test_search_index_via_query(self):
     """
     Test that a created TEXT index will produce expected query results.
     """
     index = TextIndex(self.db, 'ddoc001', 'index001')
     index.create()
     self.populate_db_with_documents(100)
     with Document(self.db, 'julia006') as doc:
         doc['name'] = 'julia isabel'
     query = Query(self.db)
     resp = query(fields=['name', 'age'], selector={'$text': 'isabel'})
     self.assertEqual(resp['docs'], [{'name': 'julia isabel', 'age': 6}])
 def test_design_document_url(self):
     """
     Test that the document url is populated correctly when a design document
     id is provided.
     """
     doc = Document(self.db, '_design/ddoc001')
     self.assertEqual(
         doc.document_url, posixpath.join(
             self.db.database_url,
             '_design/ddoc001'
         )
     )
Esempio n. 7
0
def upload_file_train():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'test' not in request.files:
            # flash('No file part')
            return "no file part"
        file = request.files['test']
        username = request.args.get('username')
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            # flash('No selected file')
            return "no selected file"
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            trainFileName = os.path.join(filename)
            file.save(trainFileName)
            print trainFileName

            with open(trainFileName, 'rb') as f:
                uploaded_file_content = b64encode(f.read())
                if Document(db, username).exists():
                    with Document(db, username) as document:
                        document['_attachments'][trainFileName] = {
                            'data': uploaded_file_content
                        }
                else:
                    data = {
                        '_id': username,
                        '_attachments': {
                            trainFileName: {
                                'data': uploaded_file_content
                            },
                        },
                        'time_spent': 0
                    }
                    db.create_document(data)

            return trainFileName
    return ''
Esempio n. 8
0
 def test_fetch_document_without_docid(self):
     """
     Test fetching document content with no id provided
     """
     doc = Document(self.db)
     try:
         doc.fetch()
         self.fail('Above statement should raise an Exception')
     except CloudantDocumentException as err:
         self.assertEqual(
             str(err),
             'A document id is required to fetch document contents. '
             'Add an _id key and value to the document and re-try.')
Esempio n. 9
0
async def get_user_no_read(id):
    try:
        ch_feed = await get_changes(id)
    except HTTPError:
        return None
    try:
        if '_deleted' in ch_feed['doc'] and ch_feed['doc']['_deleted']:
            return None
        doc = Document(db, ch_feed['doc']['_id'])
        doc.update(ch_feed['doc'])
        return doc
    except:
        return None
Esempio n. 10
0
 def test_create_existing_document(self):
     """
     Test creating an already existing document
     """
     doc = Document(self.db, 'julia006')
     doc.create()
     with self.assertRaises(requests.HTTPError) as cm:
         doc.create()
     err = cm.exception
     self.assertEqual(
         err.response.status_code,
         409
     )
def personExists(MAC_Addr):
    client = this.__client__
    myDatabase = this.__myDatabase__
    if not Document(myDatabase, MAC_Addr).exists():
        return False
    else:
        try:
            if getSecretKey(MAC_Addr) != "":
                return True
            else:
                return False
        except KeyError:
            return False
Esempio n. 12
0
 def test_list_field_remove_failure(self):
     """
     Test the static helper method to remove from a list
     field errors as expected.
     """
     doc = Document(self.db)
     doc.field_set(doc, 'name', 'julia')
     try:
         doc.list_field_remove(doc, 'name', 'julia')
         self.fail('Above statement should raise an Exception')
     except CloudantDocumentException as err:
         self.assertEqual(str(err), 'The field name is not a list.')
     self.assertEqual(doc, {'name': 'julia'})
Esempio n. 13
0
    def update_stock(self, symbol, name, buybelow, comments, active):
        with Document(self.db, symbol) as doc:
            doc['updated'] = strftime("%Y-%m-%d %H:%M:%S")
            doc['name'] = str(name)
            if active == 'true':
                doc['active'] = True
            else:
                doc['active'] = False
            doc['buybelow'] = float(buybelow)
            doc['comments'] = str(comments)

            for x in ('updated', 'name', 'active', 'buybelow', 'comments'):
                self.stocks[symbol][x] = doc[x]
Esempio n. 14
0
 def test_delete_document_success_with_encoded_url(self):
     """
     Test that we can remove a document from the remote
     database successfully when the document id requires an encoded url.
     """
     doc = Document(self.db, 'http://example.com')
     doc['name'] = 'julia'
     doc['age'] = 6
     doc['pets'] = ['cat', 'dog']
     doc.create()
     self.assertTrue(doc.exists())
     doc.delete()
     self.assertFalse(doc.exists())
     self.assertEqual(doc, {'_id': 'http://example.com'})
Esempio n. 15
0
 def test_delete_document_success(self):
     """
     Test that we can remove a document from the remote
     database successfully.
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     doc['pets'] = ['cat', 'dog']
     doc.create()
     self.assertTrue(doc.exists())
     doc.delete()
     self.assertFalse(doc.exists())
     self.assertEqual(doc, {'_id': 'julia006'})
Esempio n. 16
0
 def test_field_set_and_replace(self):
     """
     Test the static helper method to set or replace a field value.
     """
     doc = Document(self.db)
     self.assertEqual(doc, {})
     doc.field_set(doc, 'name', 'julia')
     self.assertEqual(doc, {'name': 'julia'})
     doc.field_set(doc, 'name', 'jules')
     self.assertEqual(doc, {'name': 'jules'})
     doc.field_set(doc, 'pets', ['cat', 'dog'])
     self.assertEqual(doc, {'name': 'jules', 'pets': ['cat', 'dog']})
     doc.field_set(doc, 'pets', None)
     self.assertEqual(doc, {'name': 'jules'})
Esempio n. 17
0
    def test_document_context_manager_update_failure_on_error(self):
        """
        Test that the document context manager skips document update if there
        is an error.
        """
        # Create the document.
        doc = Document(self.db, 'julia006')
        doc['name'] = 'julia'
        doc['age'] = 6
        doc.save()

        # Make a document update and then raise an error.
        with self.assertRaises(ZeroDivisionError), Document(
                self.db, 'julia006') as doc:
            doc['age'] = 7
            raise ZeroDivisionError()

        # Assert the change persists locally.
        self.assertEqual(doc['age'], 7)

        # Assert the document has not been saved to remote server.
        self.assertTrue(doc['_rev'].startswith('1-'))
        self.assertEqual(self.db['julia006']['age'], 6)
Esempio n. 18
0
    def post(self):
        body = load_body(scrap_schema)
        db = get_scraps_db()

        doc = Document(db)
        data = scrap_schema.dump(body).data

        body = data.pop('body')
        content_type = data.pop('content_type')

        doc.update(**data)
        doc.create()
        doc.put_attachment('body', content_type, body)
        return doc
Esempio n. 19
0
 def __getitem__(self, key):
     if not self.remote:
         if key in list(self.keys(remote=False)):
             return super(CouchDatabase, self).__getitem__(key)
     if key.startswith("_design/"):
         doc = DesignDocument(self, key)
     else:
         doc = Document(self, key)
     if doc.exists():
         doc.fetch()
         super(CouchDatabase, self).__setitem__(key, doc)
         return doc
     else:
         raise KeyError(key)
Esempio n. 20
0
 def populate_categories(self):
     pass
     print("Portfolio.populate_categories()")
     # Load portfolio specification document from DB
     self.foliodoc = Document(self.db, self.name)
     self.foliodoc.fetch()
     for category in self.foliodoc['categories']:
         # print category
         for subcategory in self.foliodoc['categories'][category].keys():
             # print "Subcategory name: {0} Target: {1}".format(subcategory, self.foliodoc['categories'][category][subcategory])
             self.categories[subcategory] = dict(
                 target=self.foliodoc['categories'][category][subcategory],
                 actual=0,
                 type=category)
Esempio n. 21
0
 def new_transaction_doc(self, symbol, quantity, price, fee, action):
     xactiondoc = Document(self.db)
     xactiondoc['type'] = 'transaction'
     xactiondoc['action'] = action
     xactiondoc['quantity'] = quantity
     xactiondoc['date'] = strftime("%Y-%m-%d %H:%M:%S")
     xactiondoc['fee'] = fee
     xactiondoc['price'] = price
     if action == 'deposit' or action == 'withdrawl':
         xactiondoc['symbol'] = 'Cash'
         xactiondoc['price'] = 1
     else:  #otherwise use symbol passed and check to see if updating cash is needed
         xactiondoc['symbol'] = symbol
     xactiondoc.save()
def test_fetch_doc_by_id(db, _id):
    """Test document fetch by Id."""
    doc = Document(db, _id)
    #    doc = Document(db, _id, decoder=json_decoder)
    if not doc.exists():
        raise ValueError(f'Document with id {_id} not found')
    else:
        try:
            doc.fetch()
            print(f'SUCCESS FETCH: Document with id {_id}: {doc}')
        except Exception as e:
            print(f'FAILED FETCH: {e}')
            raise
    return doc
Esempio n. 23
0
 def test_update_field(self):
     """
     Test that we can update a single field remotely using the
     update_field method.
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     doc['pets'] = ['cat', 'dog']
     doc.create()
     self.assertTrue(doc['_rev'].startswith('1-'))
     self.assertEqual(doc['pets'], ['cat', 'dog'])
     doc.update_field(doc.list_field_append, 'pets', 'fish')
     self.assertTrue(doc['_rev'].startswith('2-'))
     self.assertEqual(doc['pets'], ['cat', 'dog', 'fish'])
Esempio n. 24
0
 def test_document_exists_raises_httperror(self):
     """
     Test document exists raises an HTTPError.
     """
     # Mock HTTPError when running against CouchDB and Cloudant
     resp = requests.Response()
     resp.status_code = 400
     self.client.r_session.head = mock.Mock(return_value=resp)
     doc = Document(self.db)
     doc['_id'] = 'julia006'
     with self.assertRaises(requests.HTTPError) as cm:
         doc.exists()
     err = cm.exception
     self.assertEqual(err.response.status_code, 400)
     self.client.r_session.head.assert_called_with(doc.document_url)
Esempio n. 25
0
    def __init__(self, context, client):
        self.context = context
        self.client = client
        self.trainer_db = client["trainer"]
        if Document(self.trainer_db, self.context).exists():
            trainer = self.trainer_db[self.context]
            self.training_data = list(trainer['training_data'])
        else:
            self.training_data = list()
            data = dict([('_id', self.context), ('context', self.context),
                         ('training_data', self.training_data)])

            # Create a document using the Database API
            self.trainer_db.create_document(data)
        self.synapse_db = client["synapse"]
Esempio n. 26
0
    def get_course_ids(cls, dept, number):
        number_dict = dict()
        if dept in cls.query_table:
            number_dict = cls.query_table[dept]
        else:
            logging.warn('Department not found locally.'
                         ' Querying online database: {}'.format(dept))
            with Document(cls.query_table_db, dept) as doc:
                number_dict = json.loads(doc.json())
                cls.query_table[dept] = number_dict

        if number not in number_dict:
            logging.warn("Course not found in {}: {}".format(dept, number))
            return list()
        return number_dict[number]
Esempio n. 27
0
 def create_user(self, username, password, admin, portfolios):
     if self.admin == True:
         try:
             # Create user document in auth_db
             with Document(self.auth_db, username) as doc:
                 doc['password'] = pbkdf2_sha256.hash(password)
                 doc['admin'] = admin
                 doc['portfolios'] = portfolios
             # Create user's custom database and populate views
             newdb_name = "{0}".format(username)
             newdb = self.client.create_database(newdb_name)
             self.initialize_views(newdb)
             return "User created"
         except Exception as e:
             return "Cannot create user: {0}".format(e)
Esempio n. 28
0
 def test_delete_document_failure(self):
     """
     Test failure condition when attempting to remove a document
     from the remote database.
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     doc['pets'] = ['cat', 'dog']
     try:
         doc.delete()
         self.fail('Above statement should raise an Exception')
     except CloudantDocumentException as err:
         self.assertEqual(
             str(err), 'Attempting to delete a doc with no _rev. '
             'Try running .fetch and re-try.')
Esempio n. 29
0
    def test_document_request_fails_after_client_disconnects(self):
        """
        Test that after disconnecting from a client any objects created based
        on that client are not able to make requests.
        """
        self.client.connect()
        doc = Document(self.db, 'julia001')
        doc.save()
        self.client.disconnect()

        try:
            with self.assertRaises(AttributeError):
                doc.fetch()
            self.assertIsNone(doc.r_session)
        finally:
            self.client.connect()
Esempio n. 30
0
    def new_stock(self, category, symbol, name, buybelow, comments, active):
        print("Portfolio.new_stock()")
        with Document(self.db, symbol) as stockdoc:
            stockdoc['type'] = 'stock'
            stockdoc['updated'] = strftime("%Y-%m-%d %H:%M:%S")
            stockdoc['category'] = category
            stockdoc['symbol'] = symbol
            stockdoc['active'] = active
            stockdoc['name'] = name
            stockdoc['comments'] = comments
            stockdoc['buybelow'] = buybelow
            self.stocks[symbol] = json.loads(stockdoc.json())
        # Get a quote for the new stock
        self.stocks[symbol]['lastprice'] = -1
        self.stocks[symbol]['qty'] = 0

        # update all holdings and totals
        self.refresh_total_value()