コード例 #1
0
def setup(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) != 2 or argv[1] == "--help":
        print "Usage: magicmocksetup <dest dir>"
        return
    current_dir_abs = os.path.abspath(os.path.dirname(__file__))
    sampler_folder = os.path.join(current_dir_abs, "Sample")
    output_dir_abs = os.getcwd()
    output_folder = os.path.join(output_dir_abs, argv[1])
    Utils.copy_folder(sampler_folder, output_folder)
    print "Sample project created."
コード例 #2
0
def setup(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) != 2 or argv[1] == "--help":
        print "Usage: magicmocksetup <dest dir>"
        return
    current_dir_abs = os.path.abspath(os.path.dirname(__file__))
    sampler_folder = os.path.join(current_dir_abs, "Sample")
    output_dir_abs = os.getcwd()
    output_folder = os.path.join(output_dir_abs, argv[1])
    Utils.copy_folder(sampler_folder, output_folder)
    print "Sample project created."
コード例 #3
0
    def _process_request(self):
        try:
            if web.mockserver.global_delay == 0:
                Log.Mockserver.debug("time delay is set to %s sec" %
                                     web.mockserver.delay)
                time.sleep(web.mockserver.delay)
            else:
                Log.Mockserver.debug("global time delay is set to %s sec" %
                                     web.mockserver.global_delay)
                time.sleep(web.mockserver.global_delay)

            MockController.RecordRequest()
            if not MockController.PerformMock():
                resp = MockController.ForwardRequest()
                MockController.RecordResponse(resp)
                web.ctx.headers = MockUtils.ConvertHeader(resp.headers)
                web.ctx.status = resp.status
                data = resp.data
            else:
                data = MockController.GetResponse()
                resp = Response()
                resp.data = data
                resp.headers = web.ctx.headers
                resp.status = web.ctx.status
                resp.url = web.ctx.fullpath

                MockController.RecordResponse(resp)
                MockController.RestoreResponse()
                if data is None:
                    data = "API hasn't been implemented!"
            MockController.RestoreModeAndDelay()
            return data
        except Exception, e:
            Log.Mockserver.exception("general server error")
            return "general server error"
コード例 #4
0
def LoadJson(json_file):
    config = Utils.config
    if not config["MOCK_SERVER"].has_key("jsontemplatepath"):
        raise Exceptions.IncorrectConfigError(
            "Key '%S' is missing!" % config["MOCK_SERVER"]['JsonTemplatePath'])
    paths = ['Projects']
    for path in config["MOCK_SERVER"]["jsontemplatepath"].split("."):
        paths.append(path)
    result = Utils.GetJsonFromFile(paths, json_file)
    return result
コード例 #5
0
def GetResponse(method = None):
    if method:
        method = method.lower()
    else:
        method = 'get'
    for uri in web.url_mapping.keys():
        if uri in web.ctx.fullpath: 
            response = web.url_mapping[uri][method]
            web.ctx.headers = Utils.ConvertHeader(response["headers"])
            web.ctx.status = str(response["status"])
            return json.dumps(response["body"])
コード例 #6
0
def LoadImage(image_file):
    config = Utils.config
    Utils.AssertConfig("MOCK_SERVER", "JsonTemplatePath")
    paths = os.getcwd()
    for path in config["MOCK_SERVER"]["jsontemplatepath"].split("."):
        paths = os.path.join(paths, path)
    try:
        f = open(os.path.join(paths, image_file), 'rb')
        data = f.read()
    except Exception, e:
        data = {"mock_server_error": "invalid image file"}
コード例 #7
0
def LoadLdapConfig():
    Log.Mockserver.info("Load ldap config")
    template_path = web.mockserver.config["MOCK_SERVER"]['ldaptemplatepath']
    
    paths = ['Projects']
    for path in template_path.split("."):
        paths.append(path)
    try:
        config = Utils.GetJsonFromFile(paths, "default.json")
        return config
    except:
        raise Exceptions.UnableToRetrieveDataError("Error to load ldap config data. Please check file existence or format.")
コード例 #8
0
def GetResponse():

    method = web.ctx.method.lower()

    for uri in web.mockserver.url_mapping.keys():
        if uri in web.ctx.fullpath: 
            response = web.mockserver.url_mapping[uri][method]
            web.ctx.headers = Utils.ConvertHeader(response["headers"])
            web.ctx.status = str(response["status"])
            if isinstance(response["body"], dict) or isinstance(response["body"], list) or isinstance(response["body"], tuple):
                return json.dumps(response["body"])
            else:
                return response["body"]
コード例 #9
0
def LoadJson(json_file, json_path=None):
    assertResult = Utils.AssertConfig("MOCK_SERVER", "JsonTemplatePath")
    paths = os.getcwd()
    if assertResult:
        for path in Utils.GetConfig("MOCK_SERVER",
                                    "jsontemplatepath").split("."):
            paths = os.path.join(paths, path)
        if json_path:
            if isinstance(json_path, str):
                paths = os.path.join(paths, json_path)
            elif isinstance(json_path, list) or isinstance(json_path, tuple):
                for jpath in json_path:
                    paths = os.path.join(paths, jpath)
            else:
                print "unrecognized path list!"

    try:
        result = Utils.GetJsonFromFile(os.path.join(paths, json_file))
    except Exception, e:

        result = {
            "mock_server_error": "invalid json file",
            "exception": str(e)
        }
コード例 #10
0
def ForwardRequest():
    Utils.AssertConfig('MOCK_SERVER', 'serveraddress')
    base_url = web.mockserver.config['MOCK_SERVER']['serveraddress']
    url = web.ctx.fullpath
    headers = web.ctx.env['REQUEST_HEADERS']
#    headers = Utils.ConvertHeaderToDict(web.ctx.headers)
    body = web.data()
    method = web.ctx.method
    Log.Mockserver.debug("remote server url is %s, headers are %s" % (base_url, str(headers)))
    request = Request(url = url, headers = None, method = method, body = body, base_url =  base_url)
    req = request.send()
    if isinstance(req.response.data, dict) or isinstance(req.response.data, list) or isinstance(req.response.data, tuple):
        req.response.data = json.dumps(req.response.data)
    for k in req.response.headers.keys():
        if k in ignore_headers:
            del(req.response.headers[k]) 
    return req.response
コード例 #11
0
def ParseConfig(config_file, config_path):
    Utils.SetConfigFilePath(config_path)
    Utils.SetConfigFile(config_file)
    Utils.InitConfig()
    config = Utils.config
    section = "MOCK_SERVER"
    Utils.AssertConfig(section, "BASEURL")
    Utils.AssertConfig(section, "Port")
    Utils.AssertConfig(section, "Mode")
    if config[section]["mode"] == "Mock":
        Utils.AssertConfig(section, "APITemplatePath")
        apiTemplatePath = config[section]["apitemplatepath"]
    else:
        apiTemplatePath = None
    try:
        port = int(config["MOCK_SERVER"]["port"])
    except:
        raise Exceptions.IncorrectConfigError("Port should be an integer")
    web.mockserver.config = config
    return config["MOCK_SERVER"]["baseurl"], port, apiTemplatePath
コード例 #12
0
def InitMode():
    Utils.AssertConfig("MOCK_SERVER", "Mode")
    web.mockserver.global_mode = Utils.config['MOCK_SERVER']["mode"]
    web.mockserver.mode = web.mockserver.global_mode
コード例 #13
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = OptionParser()
    parser.add_option("-d",
                      "--daemon",
                      dest="daemon",
                      action="store_true",
                      help="run as daemon")
    parser.add_option("-c",
                      "--config",
                      dest="config",
                      help="specify config file")
    parser.add_option("-p",
                      "--config-path",
                      dest="configpath",
                      help="specify the relative path of config file")
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="specify output absolute path")

    (options, args) = parser.parse_args()
    ip, port, api_path = ParseConfig(options.config, options.configpath)
    Utils.SetOutputDir(os.path.join(options.output, "Logs"))
    section = "MOCK_SERVER"
    loglevel = Utils.GetLogLevel(section)
    Log.Mockserver = Logger(name=Name.MockServer,
                            path=Utils.outputdir,
                            filename="mockserver.log",
                            loglevel=loglevel,
                            output=Output.File,
                            formatter=Formatter.MockServer).get_logger()
    Log.Request = Logger(name=Name.Request,
                         path=Utils.outputdir,
                         filename='request.log',
                         loglevel=logging.INFO,
                         output=Output.File,
                         formatter=Formatter.Request).get_logger()
    Log.Response = Logger(name=Name.Response,
                          path=Utils.outputdir,
                          filename='response.log',
                          loglevel=logging.INFO,
                          output=Output.File,
                          formatter=Formatter.Response).get_logger()
    if Utils.config[section].has_key("ssl"):
        if Utils.config[section]['ssl'].lower() == 'true':
            Utils.AssertConfig(section, "sslkeypath")
            Utils.AssertConfig(section, "sslcerpath")
            CherryPyWSGIServer.ssl_certificate = Utils.config[section][
                'sslkeypath']
            CherryPyWSGIServer.ssl_private_key = Utils.config[section][
                'sslcerpath']
    if Utils.config[section]["mode"] == "Mock":
        InitURLMapping(api_path)
    InitMode()
    web.config.debug = True

    #     import daemon
    #     with daemon.DaemonContext():
    #         s = LdapServer()
    #         s.start()
    if options.daemon:
        import daemon
        with daemon.DaemonContext():
            application.run(ip=ip, port=port)
    else:
        application.run(ip=ip, port=port)
コード例 #14
0
            request = Request(url=uri,
                              body=body,
                              method="post",
                              base_url=self.baseurl)
            result = request.send().result
            if result['status'] == '200':
                print("Set mode success!")
                return True
            else:
                raise Exception("Set mode failed!")
        except:
            print("Error response returned!")
            return False


if __name__ == "__main__":
    Utils.configfile = "mockserver_Demo.cfg"
    Utils.configfilePath = "Trela3_6"
    Utils.InitConfig()
    from Projects.Alert.Resource.APITemplates import giftcards_detail_error

    Log.Chorus = Logger(name=Name.ChorusCore,
                        loglevel=logging.DEBUG,
                        output=Output.Console,
                        formatter=Formatter.ChorusCore).get_logger()
    print SetResponse("giftcards_detail_error",
                      giftcards_detail_error.response_821)
#    from Projects.Usher.UVS.APITemplates import user_retrieve__events_get
#    print SetResponse("user_retrieve__events_get", user_retrieve__events_get.response_device_activation)
#SetMode(mode = Mode.Mock, is_global = False)
#SetDelay()