def mapping_item_for_mapping_request(self, request): # try find by scenario mappings = [ item for item in self.mappings if item.mock_scenario == Config.scenario and item.handles_mapping_request(request) ] if mappings: if Config.verbose: Log.info("Mapping found by scenario: {0}".format( Config.scenario)) return mappings # try find by default scenario mappings = [ item for item in self.mappings if item.mock_scenario == Constants.DEFAULT_SCENARIO and item.handles_mapping_request(request) ] if mappings: if Config.verbose: Log.info("Mapping found by default scenario") return mappings return []
def __eq__(self, other): matches_method = self.method_matches(other.method) matches_url = self.url_matches(other.url) matches_body = self.body_matches(other.body) matches_headers = HeaderMatcher(self.headers).matches(other.headers) matches_form_fields = self.form_fields_matches(other.form_fields) matches_query_string = self.query_string_matches(other.query_string) if Config.verbose: Log.info("Mock tested:") Log.normal("Mock ID: {0}".format(self.mock_id)) Log.normal("Mock Scenario: {0}".format(self.mock_scenario)) Log.normal("Request URL: {0}".format(other.url)) Log.normal("Mock URL: {0}".format(self.url)) Log.normal("Matches Method: {0}".format( ("Yes" if matches_method else "No"))) Log.normal("Matches URL: {0}".format( ("Yes" if matches_url else "No"))) Log.normal("Matches Body: {0}".format( ("Yes" if matches_body else "No"))) Log.normal("Matches Headers: {0}".format( ("Yes" if matches_headers else "No"))) Log.normal("Matches Form Fields: {0}".format( ("Yes" if matches_form_fields else "No"))) Log.normal("Matches Query String: {0}".format( ("Yes" if matches_query_string else "No"))) return (matches_method and matches_url and matches_body and matches_headers and matches_form_fields and matches_query_string)
def start(): Log.info("Initializing server...") # update config cherrypy.config.update({ "server.socket_port": Config.port, "server.socket_host": Config.host, "environment": "embedded", "tools.encode.text_only": False, "cors.expose.on": Config.cors, }) # update config for verbose mode if Config.verbose: cherrypy.config.update({ "log.screen": True, }) # cors if Config.cors: cherrypy_cors.install() Log.info("CORS enabled") # listen for signal def signal_handler(signal, frame): Log.info("Shutting down server...") cherrypy.engine.exit() Log.ok("Server shutdown successfully") signal.signal(signal.SIGINT, signal_handler) # start server cherrypy.quickstart(CherryPyServer())
def on_any_event(self, event): Log.info("Directory changed, rebuilding mapping settings...\n" "Path: %s" % event.src_path + "\nEvent type: %s" % event.event_type) Config.reload_sys_path_list() self.mapping_manager.parse_yaml_files() Log.ok("Mapping settings rebuilt successfully")
def handle_request(self): request = self.cherrypy.to_mapper_request() if Config.verbose: Log.info("Request data:") Log.normal(request) else: Log.request_url(self.cherrypy.url()) items = self.mapping_handler.mapping_item_for_mapping_request(request) if len(items) == 0: self.cherrypy.response.status = 500 Log.failed("No response found for request: {0}".format( self.cherrypy.url())) return "No response found for request" if len(items) > 1: Log.warn("Matched {0:d} items, choosing the first one".format( len(items))) if Config.verbose: Log.multiple_matches(items) matched_item = items[0] response = matched_item.response if Config.verbose: Log.log_request(matched_item.request, self.cherrypy.url()) delay = Config.delay if delay > 0: delay = delay / 1000 if Config.verbose: Log.info("Delay: {0:.3f}ms".format(delay)) sleep(delay) if response.body.body_type == BodyResponse.PYTHON: response.process_python_data({"request": request}) self.cherrypy.response.status = response.status self.fill_headers(response.headers) if Config.verbose: Log.log_response(response) return response.body_response()
def __init__(self, dic, base_path): self.base_path = base_path self.value = "" self._body_type = BodyResponse.NONE if dic: if "body_raw" in dic: self._body_type = BodyResponse.RAW self.file_name = "" self.value_from_raw(dic["body_raw"]) elif "body_file" in dic: self._body_type = BodyResponse.FILE self.file_name = dic["body_file"] self.value_from_file(self.file_name) elif "body_image" in dic: self._body_type = BodyResponse.IMAGE self.file_name = dic["body_image"] self.value_from_image(self.file_name) elif "body_json" in dic: self._body_type = BodyResponse.JSON self.file_name = "" self.value_from_object(dic["body_json"]) elif "body_python" in dic: self._body_type = BodyResponse.PYTHON self.file_name = dic["body_python"] # add sys path item to sys path list sys_path_list = dic["sys_path"] if "sys_path" in dic else [] if sys_path_list: for sys_path_item in sys_path_list: if sys_path_item == "auto": # auto = dir of python file full_path = File.real_path(self.base_path, self.file_name) full_path = os.path.dirname(full_path) else: # create path from item specified full_path = File.real_path(self.base_path, sys_path_item) if full_path not in sys.path: Log.info("Path added to sys.path: {0}".format( full_path)) sys.path.append(full_path)
def run(args): if args.update_scenario: scenario = args.update_scenario if not scenario: scenario = Constants.DEFAULT_SCENARIO Log.info("Changing to scenario {0}...".format(scenario)) try: r = requests.get( "{0}/pymocky/update-scenario?scenario={1}".format( args.server_host, scenario, )) if r.status_code == 200: Log.ok("Scenario updated") else: Log.failed("Scenario not updated: {0:d}".format( r.status_code)) except requests.exceptions.RequestException as e: Log.error("Scenario update error: {0}".format(e)) elif args.reload: Log.info("Reloading...") try: r = requests.get("{0}/pymocky/reload".format(args.server_host)) if r.status_code == 200: Log.ok("Reloaded") else: Log.failed("Reload failed: {0:d}".format(r.status_code)) except requests.exceptions.RequestException as e: Log.error("Reload error: {0}".format(e)) elif args.version: Log.normal("Version: {0}".format(__version__)) else: if not args.path: Log.error("Path argument is required (--path or -p)") Config.sys_path_list = sys.path.copy() CherryPyServer.start()
def parse_yaml_files(self): self.yaml_files = File.get_yaml_files(Config.path) self.mappings = [] for yaml_file in self.yaml_files: full_path = os.path.join(Config.path, yaml_file) with open(full_path, "r") as file: file_data = yaml.load(file, yaml.SafeLoader) if "mappings" in file_data: mappings = file_data["mappings"] if mappings and isinstance(mappings, list): for mapping in mappings: new_mapping = MappingItem( mapping, full_path, os.path.dirname(full_path), ) self.mappings.append(new_mapping) Log.info("Mappings loaded: {0:d}".format(len(self.mappings)))
def __init__(self): self.parse_yaml_files() if Config.watch: Log.info("Live reload enabled") self.install_watchers()
def test_info(self): with patch("sys.stdout", new=StringIO()) as output: Log.info("info message") self.assertIn("info message", output.getvalue().strip())
def signal_handler(signal, frame): Log.info("Shutting down server...") cherrypy.engine.exit() Log.ok("Server shutdown successfully")