Snippet para usar un unittest bottle.py con un proceso separado

Necsitaba probar un api rest y se me ocurrio levantar bottle en un proceso separado dentro de un testcase; y necesite hacer todos este chicle.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# "THE WISKEY-WARE LICENSE":
# <jbc.develop@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a WISKEY in return Juan BC

import multiprocessing
import urllib2
import unittest

import bottle

class BottleTest(unittest.TestCase):

    def setUp(self):
        self.process = multiprocessing.Process(
            target=bottle.run,
            kwargs={"port": "8081"}
        )
        self.process.start()

        # wait until bottle process full started
        # si no ponen esto el testcase se va a ejecutar antes
        # que bottle este listo para recibir peticiones
        started = False
        while not started:
            try:
                urllib2.urlopen("http://127.0.0.1:8081/")
            except urllib2.HTTPError:
                started = True
            except urllib2.URLError as err:
                if err.reason.args[0] == 111:
                    pass
                else:
                    raise err
            else:
                started = True

    def tearDown(self):
        self.process.terminate()

    def test_something(self):
        pass

Leer Más