#!/usr/bin/env python
"""
Look for memory leaks in lxml/libxml2.

Usage: lxml-memleak.py
       lxml-memleak.py testname [number-of-repetitions]

"""

sample_document = "<body>lalala</body>"

def test_lxml_html():
    from lxml.etree import HTML
    doc = HTML(sample_document)

def test_libxml2_html():
    import libxml2
    doc = libxml2.htmlParseDoc(sample_document, 'ascii')
    doc.freeDoc()

def test_lxml_xml():
    from lxml.etree import XML
    doc = XML(sample_document)

def test_libxml2_xml():
    import libxml2
    doc = libxml2.parseDoc(sample_document)
    doc.freeDoc()


def check_mem_leaks(fn):
    import libxml2
    mem_before = libxml2.debugMemory(1)
    libxml2.initParser()
    fn()
    libxml2.cleanupParser()
    mem_after = libxml2.debugMemory(1)
    print "%s: leaked %d bytes" % (fn.__name__, mem_after - mem_before)


def main():
    import sys, subprocess
    if len(sys.argv) > 1:
        if sys.argv[1] in ('-h', '--help', '/?'):
            print __doc__
            return
        n_times = 1
        if len(sys.argv) > 2:
            n_times = int(sys.argv[2])
        for n in range(n_times):
            check_mem_leaks(globals()[sys.argv[1]])
    else:
        for fn in sorted(fn for fn in globals() if fn.startswith('test_')):
            subprocess.call([sys.executable, sys.argv[0], fn])


if __name__ == '__main__':
    main()

