Next / Previous / Contents / TCC Help System / NM Tech homepage

5. skiptest: A small test driver

Here is a small test script that exercises the module.

skiptest
#!/usr/bin/env python
#================================================================
# skiptest:  Test driver for pyskip.py
#   Do not edit this file.  It is extracted automatically from
#   the documentation:
#     http://www.nmt.edu/tcc/help/lang/python/examples/pyskip/
#----------------------------------------------------------------

import pyskip

# - - - - -   m a i n

def main():
    '''Main program.
    '''
    #--
    # Test 1: Build a small list with no duplicates and print it.
    #--
    print "=== Test 1, no duplicates ==="

    s=pyskip.SkipList()
    s.insert("foo")
    s.insert("bar")
    s.insert('klarn')
    s.insert('zoop')
    s.insert('aab')

    for k in s:
        print k,
    print

    print "=== len() test, should be 5 ==="
    print len(s)

    print "=== The list starting at 'foo':"
    for k in s.find("foo"):
        print k,
    print

    print "=== Match test, should find zoop:"
    print s.match("zoop")
    print "=== Match test, should print `Pass':"
    try:
        result = s.match("no-such")
        print "Fail, it found", result
    except KeyError:
        print "Pass"

    print "=== Test of __getitem__ ==="
    print "s['foo'] contains", s['foo']

    print "=== Test of __contains__: should print True, then False"
    print ('foo' in s), ('no-such' in s)

    #--
    # Test 2: Test stability with duplicates.
    #--
    print "\n=== Test 2, duplicates, key function: Equal keys should"
    print "=== ascending serial numbers; serial #1 was deleted."

    s=pyskip.SkipList(allowDups=1, keyFun=Serial.key)
    s.insert(Serial("a"))
    s.insert(Serial("x"))
    s.insert(Serial("x"))
    s.insert(Serial("x"))
    s.insert(Serial("x"))
    s.insert(Serial("x"))
    s.insert(Serial("x"))
    s.insert(Serial("a"))
    s.insert(Serial("a"))
    s.insert(Serial("a"))
    s.insert(Serial("x"))
    s.delete("a")
    for k in s:
        print k,
    print

# - - - - -   c l a s s   S e r i a l

class Serial:
    """A class that adds a unique serial number to each instance.
    """
    serialNo  =  0

    def __init__ ( self, child ):
        """Constructor"""
        self.child       =  child
        Serial.serialNo  +=  1
        self.serial      =  Serial.serialNo

    def __str__ ( self ):
        """String convert function"""
        return "%s [#%d]" % (self.child, self.serial)

    def key ( self ):
        """Key extractor function"""
        return self.child

# - - - - -   E p i l o g u e

if __name__ == "__main__":
    main()