Source

Dad / conftest.py

Full commit
import os
import sys
import logging
import subprocess
import urllib
import time
import shutil

from cherrypy.process.servers import check_port

import py.test

HERE = os.path.abspath(os.path.dirname(__file__))
DAD_TEST_SANDBOXES = os.path.join(HERE, 'test_sandboxes')

class TestApps(object):

    def create_sandboxes(self):
        sbox = os.path.join(DAD_TEST_SANDBOXES, 'simpleweb')
        if not os.path.isdir(sbox):
            os.makedirs(sbox)
        return sbox

    def deploy(self):
        sbox = self.create_sandboxes()

    def remove(self):
        shutil.rmtree(DAD_TEST_SANDBOXES)


class DevServer(object):
    port = 5000
    host = 'localhost'
    log_root = os.path.join(os.getcwd(), 'test_logs')
    log_name = 'dad_server.log'
    
    def __init__(self):
        self.proc = None
        self.log = logging.getLogger(__name__)

    def get_log(self):
        if not os.path.isdir(self.log_root):
            os.mkdir(self.log_root)
        log_filename = os.path.join(self.log_root, self.log_name)
        log_file = open(log_filename, 'a')
        self.log_reader = open(log_filename, 'r')
        self.log_reader.seek(log_file.tell())
        return log_file

    def start(self):
        cmd = os.path.join(sys.prefix, 'bin', 'dad.web')
        self.log.info('starting %s', cmd)

        os.environ['DAD_SANDBOXES'] = DAD_TEST_SANDBOXES
        os.environ['DAD_CONFIG'] = 'configs/simple.conf'
        self.proc = subprocess.Popen([cmd], stdout=self.get_log())

        try:
            check_port(self.host, self.port)
        except IOError:
            return
        
        up = None
        while not up:
            try:
                up = urllib.urlopen('http://%s:%s/' % (self.host, self.port))
            except IOError:
                time.sleep(1)
        self.log.info('started %s: pid %s', cmd, self.proc.pid)

    def stop(self):
        self.log.info('stopping %s' % self.proc.pid)
        self.proc.kill()
        self.proc.wait()
        self.log.info('stopped %s' % self.proc.pid)
                


def pytest_namespace():
    dev_server = DevServer()
    test_apps = TestApps()
    return vars()

def pytest_configure(config):
    logging.basicConfig(level=logging.INFO)
    py.test.test_apps.deploy()
    py.test.dev_server.start()

def pytest_unconfigure(config):
    py.test.dev_server.stop()
    py.test.test_apps.remove()