#!/usr/bin/env python

from __future__ import division
import httplib
import gc
import sys
from time import time

TEST_HOST = '127.0.0.1:5984'
TEST_PATH = '/'

testfuncs = {}

def test_simple(host, path):
    def run():
        conn = httplib.HTTPConnection(host)
        conn.request('GET', path)
        resp = conn.getresponse()
        assert resp.status < 400
        return resp.read()
    return run
testfuncs['simple'] = test_simple

def test_shared(host, path):
    conn = httplib.HTTPConnection(host)
    def run():
        conn.request('GET', path)
        resp = conn.getresponse()
        assert resp.status < 400
        return resp.read()
    return run
testfuncs['shared'] = test_shared

def measure(func, *args, **kwargs):
    start = time()
    func(*args, **kwargs)
    return time() - start

def test(tests, host, path, number=25):
    gc.disable()
    for testname in tests:
        testfunc = testfuncs[testname](host, path)
        results = []
        for idx in range(number):
            secs = measure(testfunc)
            print '%10s (%2d):   GET %6.2fms' %\
                    (testname, idx, secs * 1000)
            results.append(secs)

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser(usage='%prog [options] test1 ...')
    parser.add_option('-n', '--number', dest='number', type='int')
    parser.add_option('-p', '--profile', action='store_true', dest='profile')
    parser.add_option('-H', '--host', dest='host')
    parser.add_option('-P', '--path', dest='path')
    parser.set_defaults(number=100, profile=False, host=TEST_HOST, path=TEST_PATH)
    options, tests = parser.parse_args()

    if options.profile:
        import hotshot, hotshot.stats
        prof = hotshot.Profile("httplib_test.prof")
        benchtime = prof.runcall(test, tests, options.host, options.path,
                                 number=options.number)
        stats = hotshot.stats.load("httplib_test.prof")
        stats.strip_dirs()
        stats.sort_stats('time', 'calls')
        stats.print_stats(.05)
    else:
        test(tests, options.host, options.path, number=options.number)


