import bottle from bottle import route, HTTPResponse from pretenders.base import get_logger from pretenders.base.pretender import Pretender from pretenders.http import Preset, RequestSerialiser LOGGER = get_logger('pretenders.http.server') def get_header(header, default=None): return bottle.request.headers.get(header, default) class MockHTTPServer(Pretender): def __init__(self, *args, **kwargs): super(MockHTTPServer, self).__init__(*args, **kwargs) self.setup_routes() def run(self): bottle.run(host=self.host, port=self.port, reloader=True) def setup_routes(self): route('<url:path>', method='ANY', callback=self.replay) def replay(self, url): """ Replay a previously recorded preset, and save the request in history """ request_info = RequestSerialiser(url, bottle.request) body = request_info.serialize()
import signal import subprocess import sys import time from pretenders.boss import PretenderModel from pretenders.constants import ( RETURN_CODE_PORT_IN_USE, PRETEND_PORT_RANGE ) from pretenders.base import get_logger from pretenders.boss import data from pretenders.exceptions import NoPortAvailableException LOGGER = get_logger('pretenders.smtp.handler') class SMTPPretenderModel(PretenderModel): def __init__(self, start, uid, timeout, last_call, port, pid): super(SMTPPretenderModel, self).__init__( start, uid, timeout, last_call ) self.__dict__.update({ 'port': port, 'pid': pid, }) class SmtpHandler(object):
import json import bottle from bottle import post, HTTPResponse, route from pretenders.base import get_logger from pretenders.boss.apps import pretender from pretenders.boss.apps.history import save_history from pretenders.boss.apps.preset import preset_count, select_preset from pretenders.http import Preset, RequestSerialiser from pretenders.http.handler import HttpHandler LOGGER = get_logger('pretenders.boss.apps.replay') def replay(uid, body): "Save the request and replay response" mock_request = json.loads(body) LOGGER.debug('[UID:{0}] Saving history:\n{1}'.format(uid, mock_request)) save_history(uid, mock_request) if preset_count(uid) == 0: LOGGER.error("Cannot find matching request\n{0}".format(body)) raise HTTPResponse(b"No preset response", status=404) selected = select_preset(uid, mock_request) LOGGER.debug("SELECTED:\n{0}".format(selected)) return selected @post('/replay/<uid:int>') def replay_smtp(uid): """
import datetime import json import bottle from bottle import delete, get, post, HTTPResponse from pretenders import settings from pretenders.base import get_logger from pretenders.http.handler import HttpHandler from pretenders.smtp.handler import SmtpHandler LOGGER = get_logger('pretenders.boss.apps.pretender') UID_COUNTER = 0 HANDLERS = { 'http': HttpHandler(), 'smtp': SmtpHandler(), } def get_pretenders(protocol): """ Get a dict mapping UID to pretender data for the given protocol """ return HANDLERS[protocol].PRETENDERS def keep_alive(protocol, uid): """ Notification from a mock server that it must be kept alive.
from bottle import delete, post, HTTPResponse try: from collections import OrderedDict except ImportError: #2.6 compatibility from pretenders.compat.ordered_dict import OrderedDict from collections import defaultdict from pretenders.base import get_logger from pretenders.constants import FOREVER from pretenders.http import Preset LOGGER = get_logger('pretenders.boss.apps.preset') PRESETS = defaultdict(OrderedDict) def preset_count(uid): """ Check whether there are any presets. """ return len(PRESETS[uid]) def select_preset(uid, value): """ Select a preset to respond with. Look through the presets for a match. If one is found pop off a preset
import bottle from pretenders import settings from pretenders.base import get_logger, in_parent_process, save_pid_file from pretenders.boss import data from pretenders.boss.maintain import launch_maintainer # Import apps so that they get initialised for bottle. from pretenders.boss.apps import history, pretender, preset, replay LOGGER = get_logger('pretenders.boss.server') def run(host='localhost', port=8000): "Start the mock HTTP server" data.BOSS_PORT = port if in_parent_process(): if settings.RUN_MAINTAINER: LOGGER.debug('Starting maintainer process') launch_maintainer() save_pid_file('pretenders-boss.pid') bottle.run(host=host, port=port, reloader=True) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Start the server') parser.add_argument('-H', '--host', dest='host', default='localhost', help='host/IP to run the server on (default: localhost)') parser.add_argument('-p', '--port', dest='port', type=int, default=8000, help='port number to run the server on (default: 8000)')
import bottle from bottle import route, HTTPResponse from pretenders.base import get_logger from pretenders.base.pretender import Pretender from pretenders.http import Preset, RequestSerialiser LOGGER = get_logger('pretenders.http.server') def get_header(header, default=None): return bottle.request.headers.get(header, default) class MockHTTPServer(Pretender): def __init__(self, *args, **kwargs): super(MockHTTPServer, self).__init__(*args, **kwargs) self.setup_routes() def run(self): bottle.run(host=self.host, port=self.port, reloader=True) def setup_routes(self): route('<url:path>', method='ANY', callback=self.replay) def replay(self, url): """ Replay a previously recorded preset, and save the request in history """ request_info = RequestSerialiser(url, bottle.request)
try: import argparse except ImportError: pass import socket from pretenders.base import ( get_logger, in_parent_process, save_pid_file) from pretenders.boss.client import BossClient from pretenders.constants import RETURN_CODE_PORT_IN_USE LOGGER = get_logger('pretenders.base.pretender') class Pretender(object): def __init__(self, uid, host, port, boss_port): self.uid = uid self.boss_port = boss_port self.host = host self.port = port self.boss_api_handler = BossClient(host, boss_port).boss_access if in_parent_process(): save_pid_file('pretenders-mock-{0}.pid'.format(uid)) def run(self): raise NotImplementedError("run() not defined in " "{0}".format(self.__class__))
try: from http.client import HTTPConnection except ImportError: # Python2.6/2.7 from httplib import HTTPConnection from pretenders.base import ( get_logger, ResourceNotFound, UnexpectedResponseStatus ) from pretenders.base import APIHelper from pretenders.boss import PretenderModel from pretenders.exceptions import ConfigurationError from pretenders.http import binary_to_ascii, Preset LOGGER = get_logger('pretenders.boss.client') class PresetHelper(APIHelper): def add(self, match_rule=None, response_status=200, response_body=b'', response_headers={}, times=1): """ Add a new preset to the boss server. """ new_preset = Preset( headers=response_headers, body=binary_to_ascii(response_body), status=response_status, rule=match_rule, times=times,
import json from collections import defaultdict from bottle import delete, get, HTTPResponse from pretenders.base import get_logger LOGGER = get_logger('pretenders.boss.apps.history') HISTORY = defaultdict(list) def save_history(uid, request): """ Save a value in history """ HISTORY[uid].append(request) @get('/history/<uid:int>/<ordinal:int>') def get_history(uid, ordinal): """ Access requests issued to the mock server """ try: return json.dumps(HISTORY[uid][ordinal]) except IndexError: raise HTTPResponse(b"No recorded request", status=404) except Exception: LOGGER.exception('Unexpected exception')
import bottle from pretenders import settings from pretenders.base import get_logger, in_parent_process, save_pid_file from pretenders.boss import data from pretenders.boss.maintain import launch_maintainer # Import apps so that they get initialised for bottle. from pretenders.boss.apps import history, pretender, preset, replay LOGGER = get_logger('pretenders.boss.server') def run(host='localhost', port=8000): "Start the mock HTTP server" data.BOSS_PORT = port if in_parent_process(): if settings.RUN_MAINTAINER: LOGGER.debug('Starting maintainer process') launch_maintainer() save_pid_file('pretenders-boss.pid') bottle.run(host=host, port=port, reloader=True) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Start the server') parser.add_argument( '-H', '--host', dest='host', default='localhost',
import bottle try: from collections import OrderedDict except ImportError: #2.6 compatibility from pretenders.compat.ordered_dict import OrderedDict from pretenders.base import get_logger from pretenders.constants import REQUEST_ONLY_HEADERS LOGGER = get_logger('pretenders.boss.utils') def acceptable_response_header(header): "Use to filter which HTTP headers in the request should be removed" return header not in REQUEST_ONLY_HEADERS def to_dict(wsgi_headers, include=lambda _: True): """ Convert WSGIHeaders to a dict so that it can be JSON-encoded """ ret = {} for k, v in wsgi_headers.items(): if include(k): ret[k] = v return ret def get_header(header, default=None):