Example #1
0
def test_immutdoc( url ) :
    c = Client( url=url )
    ca = Client( url=url )
    ca.login( 'pratap', 'pratap' )

    [ db.delete() for db in ca.databases ]
    dba = ca.put( 'testdb' )
    db  = c.Database( 'testdb' )

    print "Testing Immutable document post() method ..."
    doc = db.Document( sampledoc )
    assert doc._id not in db
    assert db.Document( sampledoc ) is doc
    doc.post()
    docrev = doc._rev
    doc.friend = 'akbar'
    doc.put()
    immdoc = db.Document( 'joe', rev=docrev ).fetch()
    assert isinstance( immdoc, ImmutableDocument )
    assert immdoc.name == 'joe'
    try :
        immdoc.name = 'joe'
        assert False
    except :
        pass
Example #2
0
def test_info( url ) :
    print "Testing client ..."
    c = Client( url=url )
    assert c.url, url

    # __nonzero__
    assert bool(c)

    assert c()['version'] == c.version()
Example #3
0
def test_localdoc( url ):
    c = Client( url=url )
    ca = Client( url=url )
    ca.login( 'pratap', 'pratap' )

    [ db.delete() for db in ca.databases ]
    dba = ca.put( 'testdb' )
    db  = c.Database( 'testdb' )

    db.Document( sampledoc ).post()

    print "Testing LocalDocument post(), fetch(), put(), delete() methods ..."
    ldoc = db.LocalDocument( sampledoc ).put()
    ldoc = db.LocalDocument( 'joe' ).fetch()
    assert ldoc.name == 'joe'
    assert ldoc.father == 'basha'

    print "Testing LocalDocument __getattr__, __setattr__ and __delitem__ methods ..."
    ldoc.friend = 'akbar'
    ldoc.put()
    ldoc = db.LocalDocument( 'joe' ).fetch()
    assert ldoc.friend == 'akbar'
    assert ldoc._rev.startswith('0-2')
    del ldoc['friend']
    ldoc.put()
    ldoc = db.LocalDocument( 'joe' ).fetch()
    assert 'friend' not in ldoc
    
    print "Testing local document copy() method ..."
    ldoc1 = ldoc.copy( '_local/joecopy' )
    ldocrev = ldoc._rev
    ldoc1 = db.LocalDocument( 'joecopy' ).fetch()
    d = dict([ (k,v) for k,v in ldoc.items() if not k.startswith('_') ])
    d1 = dict([ (k,v) for k,v in ldoc1.items() if not k.startswith('_') ])
    assert d == d1
    ldoc1.copiedfrom = ldoc._id
    ldoc1.put()
    assert ldoc1._rev.startswith('0-2')
    assert dict(ldoc.items()) != dict(ldoc1.items())
    #ldoc1.copy( 'joe', asrev=ldocrev )
    #ldoc.fetch()
    #assert ldocrev != ldoc._rev
    #assert ldoc._rev.startswith( str((int(ldocrev[0]) + 1)) )
    #d = dict([ (k,v) for k,v in ldoc.items() if not k.startswith('_') ])
    #d1 = dict([ (k,v) for k,v in ldoc1.items() if not k.startswith('_') ])
    #assert dict(ldoc.items()) == dict(ldoc1.items())
    
    print "Testing LocalDocument delete() method ..."
    ldoc.delete()
    try :
        ldoc = db.LocalDocument( 'joe' ).fetch()
        assert False
    except :
        pass
Example #4
0
def test_designdoc( url ):
    print "Testing DesignDocument ..."
    c = Client( url=url, )
    ca = Client( url=url, )
    ca.login( 'pratap', 'pratap' )

    [ db.delete() for db in ca.databases ]
    dba = ca.put( 'testdb' )
    db  = c.Database( 'testdb' )

    print "Testing DesignDocument creation ..."
    ddoc = dba.DesignDocument( designdoc ).post()
    assert ddoc._rev.startswith( '1-' )
    d = dict( ddoc.items() )
    d.pop( '_rev' )
    assert d == designdoc

    print "Testing DesignDocument info() method ..."
    d = ddoc.info()
    assert d['name'] == 'example'
    assert 'view_index' in d
    keys = [ "compact_running", "updater_running", "language", "purge_seq",
             "waiting_commit", "waiting_clients", "signature", "update_seq",
             "disk_size" ]
    assert sorted( d['view_index'].keys() ) == sorted( keys )

    print "Testing DesignDocument views() method and Views class ..."
    views = ddoc.views()
    assert views.keys() == [ 'example' ]

    print "Testing View class ..."
    view = views['example']
    assert isinstance( view, View )
    assert view.doc == ddoc
    assert view.viewname == 'example'
    assert view.query == {}

    print "Testing Query class ..."
    qdict = { '_id' : 10, 'name' : 'xyz' }
    qdict1 = { '_id' : 10, 'name' : 'abc' }
    q = Query( **qdict ) if choice([0,1]) else Query( _q=qdict )
    q1 = Query( **qdict1 ) if choice([0,1]) else Query( _q=qdict1 )

    view1 = view( _q=q )
    assert view1.doc == ddoc
    assert view1.viewname == 'example'
    assert view1.query == qdict

    view2 = view( **q1 )
    assert view2.doc == ddoc
    assert view2.viewname == 'example'
    assert view2.query == qdict1
Example #5
0
def test_statemachine( url ):
    from  couchpy.doc import ST_ACTIVE_POST, ST_ACTIVE_INVALID, ST_ACTIVE_VALID,\
                             ST_ACTIVE_DIRTY

    print "Testing statemachine ..."
    c = Client( url=url, )
    ca = Client( url=url, )
    ca.login( 'pratap', 'pratap' )

    [ db.delete() for db in ca.databases ]
    dba = ca.put( 'testdb' )
    db  = c.Database( 'testdb' )

    doc = db.Document( sampledoc )
    assert doc._x_state == ST_ACTIVE_POST
    doc.father = 'akbar'
    assert doc._x_state == ST_ACTIVE_POST
    try : doc.put()
    except : pass
    else : assert False
    #----
    doc.post()
    assert doc._x_state == ST_ACTIVE_VALID
    doc.fetch()
    assert doc._x_state == ST_ACTIVE_VALID
    try : doc.put()
    except : pass
    else : assert False
    try : doc.post()
    except : pass
    else : assert False
    #----
    doc.father = 'akbar'
    assert doc._x_state == ST_ACTIVE_DIRTY
    doc.father = 'birbal'
    try : doc.post()
    except : pass
    else : assert False
    try : doc.fetch()
    except : pass
    else : assert False
    doc.put()
    doc = db.Document( 'joe' ).fetch()
    assert doc.father == 'birbal'
    assert doc._x_state == ST_ACTIVE_VALID
def couch_enum(couch, target, port=5984, creds="", db_select=False, column_select=False, post_status=True):
    """
    Enumerates Couch Database
    """
    done = False
    further = True
    couchpy = Client('http://' + target + ':' + str(port))
    try:
        if creds:
            username = creds.split(':')[0]
            password = creds.split(':')[1]
            try:
                couch.resource.credentials = (username, password)
                done = True
            except couchdb.http.Unauthorized:
                print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
            try:
                couchpy.login(username, password)
            except Exception as e:
                print e
                further = False
        print colored("\n[!] Enumeration Module For NoSQL Framework Couchdb Launched.....", 'yellow')
        print colored("\n[+] Couch Version : " + couch.version(), 'green')
        print target,port
        parse = requests.get("http://" + target + ":"+str(port)+"/_users/_all_docs")
        j = json.loads(parse.text)
        if str(j.values()[1]) != 'forbidden' and str(j.values()[1]) != 'unauthorized':
            if len(j['rows']) == 1:
                print colored("[-] No Users Found !! \n", 'blue')
                print colored("[!] Looks Like We have Admin Party. DO the Hula Bula Dance \n", 'green')
                # sys.exit(0)
            else:
                print colored("\n[!] Retrieving Couchdb Users\n", 'blue')
                for i in range(1, j['rows'].__len__()):
                    print colored("[-] " + str(j['rows'][i]['id']), 'green')
                    print colored("\t[!] Hashes Obtained", 'green')
                    det = requests.get(
                        "http://" + target + ":"+str(port)+"/_users/" + str(j['rows'][i]['id']))
                    json_couch = json.loads(det.text)
                    try:
                        print colored("\t[+] Password Sha:" + str(json_couch['password_sha']), 'green')
                        print colored("\t[+] Salt:" + str(json_couch['salt']), 'green')
                    except KeyError:
                        print colored("\t[+] Password Sha: Nil", 'green')
                        print colored("\t[+] Salt: Nil", 'green')
        elif done != True:
            print colored("\n[-] _users Forbidden Requires Admin Priveleges ", 'red')
        try:
            print colored("\n[!] Enumerating DB's \n", 'blue')
            for db in couch:
                print colored("\t[+] %s" % (db), 'green')
                # time.sleep(2)
            if db_select:

                print colored('\n[!] Enumerating DB "%s" Keys \n' % (db_select), 'blue')
                try:
                    db = couch[str(db_select)]
                    for i in db:
                        print colored("\t[-] %s" % (i), 'green')
                    if column_select:
                        col = db[column_select]
                        print colored("\n[+] Getting " + column_select + " info \n", 'blue')
                        for i in col:
                            if i:
                                print colored("\t[+] " + i + ":" + str(col.get(i)), 'green')
                except couchdb.http.ServerError:
                    print colored('[-] Forbidden Only admins can access _all_docs of system databases.', 'red')
                except couchdb.http.Unauthorized:
                    print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
                    further = False

            print "\n"
        except couchdb.http.Unauthorized:
            print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
            further = False

    # Enumerates Couch Configuartion
        if further != False and post_status:
            # Parsing needed to be added
            print colored("\n\n[!] Trying to Retrieve CouchDB Configs\n", 'blue')
            try:
                conf = couch.config()
                for i in conf:
                    print colored("\t[+] %s" % i, 'magenta')
                    for j in conf[i]:
                        print colored("\t\t[+] %s : %s" % (j, conf[i].get(j)), 'green')
            except couchdb.http.Unauthorized:
                print colored("\t[-] Oops Looks Like u need Credentials \n", 'red')
    # Enumerates For Couch Logs
            print colored("\n\n[!] Trying to Fetch the CouchDB Server Logs ", 'blue')
            try:
                files = open(target + ".couch.log", 'w')
                logs = couchpy.log()
                files.write(logs)
                files.close()
                print colored("\t[+] Log written to " + target + ".couch.log", 'green')
            except Exception:
                print colored("\t[-] Oops Looks Like u need Credentials \n", 'red')
    except couchdb.http.Unauthorized:
        print colored("\t[-] Credentials are wrong or try without Credentials :( \n", 'red')
Example #7
0
    parser.add_option( '-p', dest='putdb', type="string",
                       default='',
                       help='Put (create) database name in server' )
    parser.add_option( '-d', dest='deldb', type="string",
                       default='',
                       help='Delete databases name from server' )
    parser.add_option( '-u', dest='authsess', action="store_true",
                       default=False,
                       help='Authenticated session information.' )
    options, args   = parser.parse_args()
    return parser, options, args

if __name__ == '__main__' :
    parser, options, args = option_parse()
    url = (args and args[0]) or 'http://localhost:5984'
    client = Client( url )
    if bool( client ) == False :
        print "Server (%s) is not available" % url
        sys.exit(1)
    if options.loginfo :
        logging.basicConfig( level=logging.INFO )

    if options.alive :
        print client()
    elif options.activetasks :
        pprint.pprint( client.active_tasks() )
    elif options.stats :
        pprint.pprint( client.stats() )
    elif options.config :
        if options.confsec :
            pprint.pprint( client.config( section=options.confsec ) )
Example #8
0
def test_doc( url ) :
    c = Client( url=url )
    ca = Client( url=url )
    ca.login( 'pratap', 'pratap' )

    [ db.delete() for db in ca.databases ]
    dba = ca.put( 'testdb' )
    db  = c.Database( 'testdb' )

    print "Testing document post() method ..."
    doc = db.Document( sampledoc )
    assert doc._id not in db
    assert db.Document( sampledoc ) is doc
    doc.post()
    assert db.Document( sampledoc ) is doc

    print "Testing Document() instantiation ..."
    assert db.Document( 'joe' ).fetch() is doc
    doc = db.Document( 'joe' ).fetch()
    assert db.Document({ '_id': doc._id,  '_rev' : doc._rev }).fetch() is doc
    d = deepcopy( sampledoc )
    d['_id'] = 'joe1'
    try :
        db.Document( d ).fetch()
        assert False
    except :
        pass
    doc1 = db.Document(d).post()

    print "Testing Document delete() method ..."
    db.Document('joe1').fetch().delete()
    assert 'joe1' not in db
    doc1 = doc1( rev=doc1['_rev'] ).fetch()
    assert isinstance( doc1, ImmutableDocument )
    assert doc1._deleted == True


    print "Testing __getattr__, __setattr_, __getitem__ and __setitem__ operation ..."
    doc = db.Document( 'joe' ).fetch()
    assert isinstance( doc._x_hthdrs, dict )
    assert doc.name == 'joe'
    assert doc._rev.startswith( '1-' )
    doc.friend = 'akbar'
    doc.put()
    doc = db.Document( 'joe' ).fetch()
    assert doc.friend == 'akbar'
    assert doc['friend'] is doc.friend

    print "Testing Document fetch with revs ..."
    doc = db.Document( 'joe', revs='true' ).fetch()
    assert doc['_revisions']['start'] == 2
    assert len( doc['_revisions']['ids'] ) == 2

    print "Testing Document fetch with revs_info ..."
    doc = db.Document( 'joe', revs_info='true' ).fetch()
    _revs_info = doc['_revs_info']
    assert len( _revs_info ) == 2
    assert list(set( x['status'] for x in _revs_info )) == ['available']
    assert _revs_info[0]['rev'].startswith('2-')
    assert _revs_info[1]['rev'].startswith('1-')
    oldrev = _revs_info[1]['rev']

    print "Testing Document fetch for older revision ..."
    doc = db.Document( 'joe', rev=oldrev ).fetch()
    assert isinstance( doc, ImmutableDocument )
    assert 'friend' not in doc

    print "Testing __delitem__ operation ..."
    doc = db.Document( 'joe' ).fetch()
    assert doc.friend == 'akbar'
    del doc['friend']
    doc.put()
    doc = doc.fetch()
    assert 'friend' not in doc
    
    print "Testing changed(), isDirty(), invalidate() methods ..."
    doc = db.Document( 'joe' ).fetch()
    doc.update( friend='akbar', _x_dirty=False )
    assert doc.isDirty() == False
    doc.fetch()
    assert 'friend' not in doc
    #----
    doc.update( friend='akbar' )
    assert doc.isDirty()
    doc.put().fetch()
    assert 'friend' in doc
    #----
    doc.changed()
    assert doc.isDirty()
    doc.put()
    assert doc.isDirty() == False
    #----
    assert doc._x_state == ST_ACTIVE_VALID
    doc.invalidate()
    assert doc._x_state == ST_ACTIVE_INVALID

    print "Testing head() method ..."
    doc = db.Document( 'joe' ).fetch()
    doc.head()['Etag'] == doc._rev

    print "Testing copy() method ..."
    doc1 = db.Document( doc.copy( 'joecopy' ) ).fetch()
    docrev = doc._rev
    assert 'joecopy' in db
    assert db.Document( 'joecopy' ) is doc1
    d = dict([ (k,v) for k,v in doc.items() if not k.startswith('_') ])
    d1 = dict([ (k,v) for k,v in doc1.items() if not k.startswith('_') ])
    assert d == d1
    doc1.copiedfrom = doc._id
    doc1.put()
    assert doc1._rev.startswith('2-')
    assert dict(doc.items()) != dict(doc1.items())
    doc1.copy( 'joe', asrev=doc._rev )
    doc.fetch()
    assert docrev != doc._rev
    assert doc._rev.startswith( str((int(docrev[0]) + 1)) )
    d = dict([ (k,v) for k,v in doc.items() if not k.startswith('_') ])
    d1 = dict([ (k,v) for k,v in doc1.items() if not k.startswith('_') ])
    assert d == d1

    print "Testing attach() method ..."
    sampledoc1 = deepcopy( sampledoc )
    sampledoc1.update( _id='joeattach' )
    doc = db.Document( sampledoc1 )
    f1 = choice( files ) ; files.remove( f1 )
    doc.attach( f1 )
    f2 = choice( files ) ; files.remove( f2 )
    doc.attach( f2 )
    doc.post()
    assert doc._rev.startswith( '1-' )
    attachfiles = sorted( [f1, f2], key=lambda x : basename(x) )
    print "Testing class Attachment methods ..."
    doc = db.Document( 'joeattach' ).fetch()
    attachs = sorted( doc.attachments(), key=lambda x : x.filename )
    assert len(attachs) == 2
    assert all([ isinstance(x, Attachment) for x in attachs ])
    assert [ x.filename for x in attachs ] == \
           map( lambda f : basename(f), attachfiles )
    assert [ x.data for x in attachs ] == [ None, None ]
    [ x.get() for x in attachs ]
    assert attachs[0].data == open( attachfiles[0] ).read()
    assert attachs[1].data == open( attachfiles[1] ).read()
    attachs[0].delete()
    attachs[1].delete()
    assert doc._rev.startswith( '3-' )

    print "Testing Attachment class ..."
    doc = db.Document( 'joeattach' ).fetch()
    assert doc.attachments() == []
    f3 = choice( files )
    doc.Attachment( filepath=f3 ).put()
    doc.fetch()
    attach = doc.Attachment( filepath=f3 ).get()
    assert attach.data == open( f3 ).read()
Example #9
0
    qdict = { '_id' : 10, 'name' : 'xyz' }
    qdict1 = { '_id' : 10, 'name' : 'abc' }
    q = Query( **qdict ) if choice([0,1]) else Query( _q=qdict )
    q1 = Query( **qdict1 ) if choice([0,1]) else Query( _q=qdict1 )

    view1 = view( _q=q )
    assert view1.doc == ddoc
    assert view1.viewname == 'example'
    assert view1.query == qdict

    view2 = view( **q1 )
    assert view2.doc == ddoc
    assert view2.viewname == 'example'
    assert view2.query == qdict1


if __name__ == '__main__' :
    url = 'http://localhost:5984/'
    c = Client( url=url, )
    #logging.basicConfig( level=logging.INFO )
    print 'CouchDB version %s' % c.version()
    test_statemachine( url )
    print ''
    test_doc( url )
    print ''
    test_localdoc( url )
    print ''
    test_immutdoc( url )
    print ''
    test_designdoc( url )
Example #10
0
def couch_enum(couch, target, port=5984, creds="", db_select=False, column_select=False, post_status=True):
    """
    Enumerates Couch Database
    """
    done = False
    further = True
    couchpy = Client('http://' + target + ':' + str(port))
    try:
        if creds:
            username = creds.split(':')[0]
            password = creds.split(':')[1]
            try:
                couch.resource.credentials = (username, password)
                done = True
            except couchdb.http.Unauthorized:
                print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
            try:
                couchpy.login(username, password)
            except Exception as e:
                print e
                further = False
        print colored("\n[!] Enumeration Module For NoSQL Framework Couchdb Launched.....", 'yellow')
        print colored("\n[+] Couch Version : " + couch.version(), 'green')
        print target,port
        parse = requests.get("http://" + target + ":"+str(port)+"/_users/_all_docs")
        j = json.loads(parse.text)
        if str(j.values()[1]) != 'forbidden' and str(j.values()[1]) != 'unauthorized':
            if len(j['rows']) == 1:
                print colored("[-] No Users Found !! \n", 'blue')
                print colored("[!] Looks Like We have Admin Party. DO the Hula Bula Dance \n", 'green')
                # sys.exit(0)
            else:
                print colored("\n[!] Retrieving Couchdb Users\n", 'blue')
                for i in xrange(1, len(j['rows'])):
                    print colored("[-] " + str(j['rows'][i]['id']), 'green')
                    print colored("\t[!] Hashes Obtained", 'green')
                    det = requests.get(
                        "http://" + target + ":"+str(port)+"/_users/" + str(j['rows'][i]['id']))
                    json_couch = json.loads(det.text)
                    try:
                        print colored("\t[+] Password Sha:" + str(json_couch['password_sha']), 'green')
                        print colored("\t[+] Salt:" + str(json_couch['salt']), 'green')
                    except KeyError:
                        print colored("\t[+] Password Sha: Nil", 'green')
                        print colored("\t[+] Salt: Nil", 'green')
        elif done != True:
            print colored("\n[-] _users Forbidden Requires Admin Priveleges ", 'red')
        try:
            print colored("\n[!] Enumerating DB's \n", 'blue')
            for db in couch:
                print colored("\t[+] %s" % (db), 'green')
                # time.sleep(2)
            if db_select:

                print colored('\n[!] Enumerating DB "%s" Keys \n' % (db_select), 'blue')
                try:
                    db = couch[str(db_select)]
                    for i in db:
                        print colored("\t[-] %s" % (i), 'green')
                    if column_select:
                        col = db[column_select]
                        print colored("\n[+] Getting " + column_select + " info \n", 'blue')
                        for i in col:
                            if i:
                                print colored("\t[+] " + i + ":" + str(col.get(i)), 'green')
                except couchdb.http.ServerError:
                    print colored('[-] Forbidden Only admins can access _all_docs of system databases.', 'red')
                except couchdb.http.Unauthorized:
                    print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
                    further = False

            print "\n"
        except couchdb.http.Unauthorized:
            print colored("[-] The DB requires Credentials or Wrong Credentials :( \n", 'red')
            further = False

    # Enumerates Couch Configuartion
        if further != False and post_status:
            # Parsing needed to be added
            print colored("\n\n[!] Trying to Retrieve CouchDB Configs\n", 'blue')
            try:
                conf = couch.config()
                for i in conf:
                    print colored("\t[+] %s" % i, 'magenta')
                    for j in conf[i]:
                        print colored("\t\t[+] %s : %s" % (j, conf[i].get(j)), 'green')
            except couchdb.http.Unauthorized:
                print colored("\t[-] Oops Looks Like u need Credentials \n", 'red')
    # Enumerates For Couch Logs
            print colored("\n\n[!] Trying to Fetch the CouchDB Server Logs ", 'blue')
            try:
                files = open(target + ".couch.log", 'w')
                logs = couchpy.log()
                files.write(logs)
                files.close()
                print colored("\t[+] Log written to " + target + ".couch.log", 'green')
            except Exception:
                print colored("\t[-] Oops Looks Like u need Credentials \n", 'red')
    except couchdb.http.Unauthorized:
        print colored("\t[-] Credentials are wrong or try without Credentials :( \n", 'red')
Example #11
0
#!/usr/bin/env python

# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
#       Copyright (c) 2011 SKR Farms (P) LTD.

# -*- coding: utf-8 -*-

from   copy                 import deepcopy
from   couchpy.client       import Client
from   couchpy.database     import Database
from   couchpy.doc          import Document, View, Query

URL = 'http://*****:*****@localhost:5984/'
c = Client( url=URL )
if 'db1' in c : del c['db1']
if 'db2' in c : del c['db2']
if 'db3' in c : del c['db3']

db1 = c.create( 'db1' )
db2 = c.create( 'db2' )
db3 = c.create( 'db3' )

fn = "function(doc) {if(doc._conflicts) { emit(doc._conflicts, null);} }"
db1.createdoc( docs=[{ "_id" : "_design/conflicts", "views": { "showconflicts": { "map": fn } }}] )[0]
db1doc = db1.createdoc( docs=[{ '_id' : 'test', 'count' : 1 }] )[0] # version 1 in db1
db1docs = [ deepcopy(db1doc.doc) ]

c.replicate( 'db1', 'db2' )                         # Replicate version 1 in db2
db2doc = Document( db2, 'test', fetch=True )
db2docs = [ deepcopy(db2doc.doc) ]
Example #12
0
def test_basics( url ) :
    print "Testing client in python way ..."
    c = Client( url=url )
    ca = Client( url=url )
    ca.login( 'pratap', 'pratap' )

    ca.delete('testdb1') if 'testdb1' in ca else None
    ca.delete('testdb2') if 'testdb2' in ca else None
    ca.delete('testdb3') if 'testdb3' in ca else None

    print "Testing put() ..."
    ca.put('testdb1')
    ca.put('testdb2')

    print "Testing __contains__ operation ..."
    assert 'testdb1' in c
    assert 'testdb2' in c
    
    print "Testing __iter__ operation ..."
    databases = sorted([ db.dbname for db in c ])
    assert 'testdb1' in databases
    assert 'testdb2' in databases

    print "Testing __len__ operation and put(), delete() methods ..."
    a = len(c)
    assert a >= 2
    ca.put('testdb3')
    assert len(c) == a+1

    print "Testing __getitem__, __delitem__ operation and put() method ..."
    assert isinstance( c['testdb3'], Database )
    assert c['testdb3'].dbname == 'testdb3'
    del ca['testdb3']

    print "Testing .databases properties ..."
    databases = sorted([ db.dbname for db in c.databases ])
    assert 'testdb1' in databases
    assert 'testdb2' in databases

    print "Testing active_tasks() method ..."
    ds = ca.active_tasks()
    assert isinstance(ds, list)
    for d in ds :
        keys = sorted([ 'pid', 'status', 'task', 'type' ])
        assert sorted(d[0].keys()) == keys

    print "Testing all_dbs() method ..."
    assert sorted(c.all_dbs()) == sorted( map(lambda x : x.dbname, c))

    print "Testing log() method ..."
    logtext1 = ca.log()
    assert 'GMT' in logtext1
    assert len(logtext1) == 1000
    assert logtext1[:60] not in ca.log(bytes=100)
    assert logtext1[900:60] in ca.log(bytes=100)
    #assert logtext1[:60] in ca.log(bytes=100, offset=900)
    #assert logtext1[100:60] not in ca.log(bytes=100, offset=900)

    print "Testing stats() method ..."
    stats = c.stats()
    for statname, stvalue in stats.items() :
        for key, value in stvalue.items() :
            ref = { statname : { key : value } }
            assert ref.keys() == c.stats( statname, key ).keys()

    print "Testing uuids() method ..."
    uuid = c.uuids()
    assert len(uuid) == 1
    assert int(uuid[0], 16)
    uuids = c.uuids(10)
    assert len(uuids) == 10
    for uuid in uuids :
        assert int(uuid, 16)


    print "Testing authentication and administration ..."
    c.login( 'pratap', 'pratap' )
    assert c.authsession()['userCtx']['name']  ==   'pratap'
    assert c.authsession()['userCtx']['roles'] == [ '_admin' ]
    assert c.sessionuser == 'pratap'
    if True :                   # config()
        sections = c.config()
        assert len(sections) > 10
        for secname, section in sections.items() :
            assert section == c.config(secname)
            for key, value in section.items() :
                assert value == c.config(secname, key)
        c.config( 'uuids', 'algorithm', value='utc_random' )
        assert c.config( 'uuids', 'algorithm', value='utc_random' ) == 'utc_random'
        c.config( 'uuids', 'algorithm', delete=True )
    if True :                   # administration
        assert c.admins().keys() == [ 'pratap' ] 
        c.addadmin( 'joe', 'joe' )
        assert sorted( c.admins().keys() ) == sorted([ 'pratap', 'joe' ])
        c.deladmin( 'joe' )
    c.logout()
    try :
        c.config()
        assert False
    except :
        pass

    print "Testing Database ..."
    db = c.Database( 'testdb1' )
    assert isinstance( db, Database )
    assert db.dbname == 'testdb1'

    print "Testing delete() method ..."
    ca.delete( 'testdb1' )
    ca.delete( 'testdb2' )
Example #13
0
def test_client() :
    log.info( "Testing client ..." )
    c = Client( url='http://*****:*****@localhost:5984/' )
    [ c.delete(db.dbname) for db in c ]

    [ c.delete(db.dbname) for db in c ]