author | Alberto Bertogli
<albertito@gmail.com> 2007-07-14 20:47:47 UTC |
committer | Alberto Bertogli
<albertito@gmail.com> 2007-07-14 20:47:47 UTC |
parent | 191200bcb5fb58c55bab30b39003fb870ec70ef5 |
tests/python/random1-cache.py | +122 | -0 |
diff --git a/tests/python/random1-cache.py b/tests/python/random1-cache.py new file mode 100755 index 0000000..3dca13c --- /dev/null +++ b/tests/python/random1-cache.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python + +import sys +import nmdb +from random import randint, choice + + +class Mismatch (Exception): + pass + + +# network db +ndb = nmdb.Cache() +ndb.add_tipc_server() +ndb.add_tcp_server('localhost') +ndb.add_udp_server('localhost') + +# local db +ldb = {} + +# history of each key +history = {} + +# check decorator +def checked(f): + def newf(k, *args, **kwargs): + try: + return f(k, *args, **kwargs) + except: + print history[k] + raise + newf.__name__ = f.__name__ + return newf + + +# operations +@checked +def set(k, v): + ndb[k] = v + ldb[k] = v + if k not in history: + history[k] = [] + history[k].append((set, k, v)) + +@checked +def get(k): + try: + n = ndb[k] + except KeyError: + del ldb[k] + del history[k] + return 0 + + l = ldb[k] + if l != n: + raise Mismatch, (n, l) + history[k].append((get, k)) + return True + +@checked +def delete(k): + del ldb[k] + try: + del ndb[k] + except KeyError: + pass + history[k].append((delete, k)) + +def find_missing(): + misses = 0 + for k in ldb.keys(): + if not get(k): + misses += 1 + return misses + +# Use integers because the normal random() generates floating point numbers, +# and they can mess up comparisons because of architecture details. +def getrand(): + return randint(0, 1000000000000000000) + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print 'Use: random1-cache.py number_of_keys' + sys.exit(1) + + nkeys = int(sys.argv[1]) + + # fill all the keys + print 'populate' + for i in xrange(nkeys): + set(getrand(), getrand()) + + print 'missing', find_missing() + + lkeys = ldb.keys() + + # operate on them a bit + print 'random operations' + operations = ('set', 'get', 'delete') + for i in xrange(nkeys / 2): + op = choice(operations) + k = choice(lkeys) + if op == 'set': + set(k, getrand()) + elif op == 'get': + get(k) + elif op == 'delete': + delete(k) + lkeys.remove(k) + + print 'missing', find_missing() + + print 'delete' + for k in lkeys: + delete(k) + + print 'missing', find_missing() + + sys.exit(0) + +