def test_document_exists(self):
     """
     Test whether a document exists remotely
     """
     doc = Document(self.db)
     self.assertFalse(doc.exists())
     doc['_id'] = 'julia006'
     self.assertFalse(doc.exists())
     doc.create()
     self.assertTrue(doc.exists())
Beispiel #2
0
 def test_document_exists(self):
     """
     Tests that the result of True is expected when the document exists,
     and False is expected when the document is nonexistent remotely.
     """
     doc = Document(self.db)
     self.assertFalse(doc.exists())
     doc['_id'] = 'julia006'
     self.assertFalse(doc.exists())
     doc.create()
     self.assertTrue(doc.exists())
 def test_document_exists(self):
     """
     Tests that the result of True is expected when the document exists,
     and False is expected when the document is nonexistent remotely.
     """
     doc = Document(self.db)
     self.assertFalse(doc.exists())
     doc['_id'] = 'julia006'
     self.assertFalse(doc.exists())
     doc.create()
     self.assertTrue(doc.exists())
Beispiel #4
0
 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-'))
Beispiel #5
0
 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(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-'))
Beispiel #8
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'})
Beispiel #9
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'})
 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'})
 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'})
 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)
Beispiel #13
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)
Beispiel #14
0
    def doc_exist(self, docid):
        """Test if document exists in a database

        @param docid: str, document id
        @return: boolean, True if document exist
        """
        doc = Document(self.cloudant_database, docid)
        return doc.exists()
Beispiel #15
0
    def doc_exist(self, docid):
        """Test if document exists in a database

        @param docid: str, document id
        @return: boolean, True if document exist
        """
        doc = Document(self.cloudant_database, docid)
        return doc.exists()
def test_update_doc(db, _id, doc_updates):
    """Test document update by Id."""
    orig_doc = Document(db, _id)
    if not orig_doc.exists():
        raise ValueError(f'Document with id {_id} not found')
    try:
        #        with Document(db, _id, decoder=json_decoder) as orig_doc:
        with Document(db, _id) as orig_doc:
            orig_doc.update(doc_updates)
            print(f'SUCCESS UPDATE: Document with id {_id}: {orig_doc}')
    except Exception as e:
        print(f'FAILED UPDATE: {e}')
        raise
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
Beispiel #18
0
 def test_create_document_using_save(self):
     """
     Test that save functionality works.  If a document does
     not exist remotely then create it.
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     self.assertIsNone(doc.get('_rev'))
     doc.save()
     self.assertTrue(doc.exists())
     self.assertTrue(doc['_rev'].startswith('1-'))
     remote_doc = Document(self.db, 'julia006')
     remote_doc.fetch()
     self.assertEqual(remote_doc, doc)
 def test_create_document_using_save(self):
     """
     Test that save functionality works.  If a document does
     not exist remotely then create it.
     """
     doc = Document(self.db, 'julia006')
     doc['name'] = 'julia'
     doc['age'] = 6
     self.assertIsNone(doc.get('_rev'))
     doc.save()
     self.assertTrue(doc.exists())
     self.assertTrue(doc['_rev'].startswith('1-'))
     remote_doc = Document(self.db, 'julia006')
     remote_doc.fetch()
     self.assertEqual(remote_doc, doc)
 def test_document_context_manager(self):
     """
     Test that the __enter__ and __exit__ methods perform as expected
     when initiated through a document context manager.
     """
     new_doc = Document(self.db, 'julia006')
     new_doc.create()
     self.assertTrue(new_doc.exists())
     del new_doc
     with Document(self.db, 'julia006') as doc:
         self.assertTrue(all(x in list(doc.keys()) for x in ['_id', '_rev']))
         self.assertTrue(doc['_rev'].startswith('1-'))
         doc['name'] = 'julia'
         doc['age'] = 6
     self.assertTrue(doc['_rev'].startswith('2-'))
     self.assertEqual(self.db['julia006'], doc)
Beispiel #21
0
 def test_document_context_manager(self):
     """
     Test that the __enter__ and __exit__ methods perform as expected
     when initiated through a document context manager.
     """
     new_doc = Document(self.db, 'julia006')
     new_doc.create()
     self.assertTrue(new_doc.exists())
     del new_doc
     with Document(self.db, 'julia006') as doc:
         self.assertTrue(all(x in list(doc.keys()) for x in ['_id', '_rev']))
         self.assertTrue(doc['_rev'].startswith('1-'))
         doc['name'] = 'julia'
         doc['age'] = 6
     self.assertTrue(doc['_rev'].startswith('2-'))
     self.assertEqual(self.db['julia006'], doc)
Beispiel #22
0
def checkToken(token):
    if token == 'test':
        return 'test'
    if token == None:
        return None
    tokendb = crecli()['token']
    tokendoc = Document(tokendb, token)
    if not tokendoc.exists():
        return None
    if tokendb[token]['time'] > str(datetime.datetime.now() -
                                    datetime.timedelta(
                                        seconds=7)).split('.')[0]:
        tokendoc = tokendb[token]
        tokendoc['time'] = str(datetime.datetime.now()).split('.')[0]
        tokendoc.save()
        return tokendoc['name']
    else:
        return None
Beispiel #23
0
    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
Beispiel #24
0
def checkuser(name, passwd):
    userdb = crecli()['user']
    userdoc = Document(userdb, name)
    if userdoc.exists() and userdb[name]['pass'] == passwd:
        return True
    return False
    def test_document_crud(self):
        """test basic crud operations with mocked backend"""
        doc = Document(self.database, "DUCKUMENT")
        # exists
        mock_resp = mock.Mock()
        mock_resp.status_code = 200
        self.mock_session.get.return_value = mock_resp
        self.assertTrue(doc.exists())
        self.assertTrue(self.mock_session.get.called)
        self.mock_session.get.assert_has_calls(
            [ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
        )
        self.mock_session.get.reset_mock()

        # create
        mock_resp = mock.Mock()
        mock_resp.raise_for_status = mock.Mock()
        mock_resp.status_code = 200
        mock_resp.json = mock.Mock()
        mock_resp.json.return_value = {'id': 'DUCKUMENT', 'rev': 'DUCK2'}
        self.mock_session.post.return_value = mock_resp

        doc.create()
        self.assertEqual(doc['_rev'], 'DUCK2')
        self.assertEqual(doc['_id'], 'DUCKUMENT')
        self.assertTrue(self.mock_session.post.called)
        self.mock_session.post.reset_mock()

        # fetch
        mock_resp = mock.Mock()
        mock_resp.status_code = 200
        mock_resp.raise_for_status = mock.Mock()
        mock_resp.json = mock.Mock()
        mock_resp.json.return_value = {
            '_id': 'DUCKUMENT', '_rev': 'DUCK2',
            'herp': 'HERP', 'derp': 'DERP'
        }
        self.mock_session.get.return_value = mock_resp
        doc.fetch()
        self.assertTrue('herp' in doc)
        self.assertTrue('derp' in doc)
        self.assertEqual(doc['herp'], 'HERP')
        self.assertEqual(doc['derp'], 'DERP')

        self.assertTrue(self.mock_session.get.called)
        self.mock_session.get.assert_has_calls(
            [ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
        )
        self.mock_session.get.reset_mock()

        # save
        mock_put_resp = mock.Mock()
        mock_put_resp.status_code = 200
        mock_put_resp.raise_for_status = mock.Mock()
        mock_put_resp.json = mock.Mock()
        mock_put_resp.json.return_value = {'id': 'DUCKUMENT', 'rev': 'DUCK3'}
        self.mock_session.put.return_value = mock_put_resp
        mock_get_resp = mock.Mock()
        mock_get_resp.status_code = 200
        self.mock_session.get.return_value = mock_get_resp

        doc.save()
        self.assertEqual(doc['_rev'], 'DUCK3')
        self.assertEqual(doc['_id'], 'DUCKUMENT')
        self.assertTrue(self.mock_session.get.called)
        self.assertTrue(self.mock_session.put.called)

        self.mock_session.get.assert_has_calls(
            [ mock.call('https://bob.cloudant.com/unittest/DUCKUMENT') ]
        )
        self.mock_session.put.assert_has_calls(
            [ mock.call(
                  'https://bob.cloudant.com/unittest/DUCKUMENT',
                  headers={'Content-Type': 'application/json'},
                  data=mock.ANY
            ) ]
        )
        self.mock_session.get.reset_mock()
        self.mock_session.put.reset_mock()

        # delete
        mock_resp = mock.Mock()
        mock_resp.status_code = 200
        mock_resp.raise_for_status = mock.Mock()
        self.mock_session.delete.return_value = mock_resp
        doc.delete()

        self.assertTrue(self.mock_session.delete.called)
        self.mock_session.delete.assert_has_calls(
            [ mock.call(
                  'https://bob.cloudant.com/unittest/DUCKUMENT',
                  params={'rev': 'DUCK3'}
            ) ]
        )
        self.mock_session.delete.reset_mock()
        # test delete with no rev explodes as expected
        self.assertRaises(CloudantException, doc.delete)
Beispiel #26
0
def testExists(docid):
    doc = Document(db, document_id=docid)
    return jsonify({"exists": doc.exists()})