def execute(self, ws):
     data = self.to_json().encode('utf8')
     log.debug("AuthenticateCommand Sending {}".format(data))
     ws.send(data)
     result = ws.recv()
     log.debug("AuthenticateCommand Response Received {}".format(result))
     if ClientAuthenticateCommand.verify_response(result):
         log.info("Authentication successful")
     else:
         log.error("Bad Authentication response")
 def execute(self, ws):
     data = self.to_json().encode('utf8')
     log.debug("ScheduleJobCommand Sending {}".format(data))
     ws.send(data)
     response = ws.recv()
     log.debug("ScheduleJobCommand Response Received {}".format(response))
     if ClientScheduleJobCommand.verify_response(response):
         log.info("ScheduleJobCommand successful")
     else:
         log.error("Bad ScheduleJobCommand response")
 def download_project():
     conn = httplib.HTTPConnection(config_params.downloadurl)
     conn.request("GET", download_path)
     r1 = conn.getresponse()
     status = r1.status
     if status == 200:
         log.info("Download Project Http status OK: "+ config_params.downloadurl+download_path)
         return r1.read()
     else:
         log.error("Download Project Http status not OK, status is:" + str(status))
    def validate_ziped_project():
        failed = False
        if not os.path.isdir("tmp/"):
            os.makedirs("tmp/")
        file = open("tmp/project.zip","wb")
        file.write(ziped_project)
        file.close()
        myzip = zipfile.ZipFile("tmp/project.zip")
        xml_file_path = myzip.extract("code.xml","tmp/")

        def sortAndStripCodeXml(xml_file_path):
            import xml.etree.ElementTree as ET
            order = 0
            tagsToSort = ["formula", "entry"]

            def getUniqueId(child):
                id = ET.tostring(child)
                return id

            def sortchildrenby(parent, order):
                order += 1
                for child in parent:
                    order += 1
                    order = sortchildrenby(child, order)
                parent[:] = sorted(parent, key=lambda child: getUniqueId(child) if str(child.tag) in tagsToSort else order)
                return order

            tree = ET.parse(xml_file_path)
            root = tree.getroot()
            #remove the build number and other version dependent attributes
            root.find("header").remove(root.find("header").find("applicationBuildNumber"))
            root.find("header").remove(root.find("header").find("applicationVersion"))
            root.find("header").remove(root.find("header").find("catrobatLanguageVersion"))
            root.find("header").remove(root.find("header").find("description"))

            sortchildrenby(root, order)
            result = ""
            for line in ET.tostring(root).split("\n"):
                result += line.strip()+"\n"
            return result

        xml = sortAndStripCodeXml(xml_file_path)
        hash_of_xml_file = hash(xml)
        if hash_of_xml_file == config_params.code_xml_hash:
            log.info("Project hash OK")
        else:
            log.error("Project hash unexpected, has: " + str(hash_of_xml_file)
                      + " but should be: " + str(config_params.code_xml_hash))
            failed = True
        os.remove("tmp/project.zip")
        os.remove("tmp/code.xml")
        return failed
def test_web_api(webapirul):
    conn = None
    failed = True
    try:
        conn = httplib.HTTPConnection(webapirul)
        conn.request("GET", "/")
        r1 = conn.getresponse()
        status = r1.status
        if status == 200:
            log.info("WebApi is up and running")
            failed = False
        else:
            log.error("WebApi Http status not OK, status is:" + str(status))
    except:
        log.error("Could not connect to WebApi:\n" + traceback.format_exc())
    try:
        conn.close()
    except AttributeError:
        log.error("Could not close websocket "+ traceback.format_exc())
    return failed
def test_conversion(config_params):
    def authenticate():
        command = ClientAuthenticateCommand(config_params)
        command.execute(ws)

    def start_conversion():
        command = ClientScheduleJobCommand(config_params)
        command.execute(ws)

    def retrieve_info():
        command = ClientRetrieveInfoCommand(config_params)
        return command.execute(ws)

    def download_project():
        conn = httplib.HTTPConnection(config_params.downloadurl)
        conn.request("GET", download_path)
        r1 = conn.getresponse()
        status = r1.status
        if status == 200:
            log.info("Download Project Http status OK: "+ config_params.downloadurl+download_path)
            return r1.read()
        else:
            log.error("Download Project Http status not OK, status is:" + str(status))

    def validate_ziped_project():
        failed = False
        if not os.path.isdir("tmp/"):
            os.makedirs("tmp/")
        file = open("tmp/project.zip","wb")
        file.write(ziped_project)
        file.close()
        myzip = zipfile.ZipFile("tmp/project.zip")
        xml_file_path = myzip.extract("code.xml","tmp/")

        def sortAndStripCodeXml(xml_file_path):
            import xml.etree.ElementTree as ET
            order = 0
            tagsToSort = ["formula", "entry"]

            def getUniqueId(child):
                id = ET.tostring(child)
                return id

            def sortchildrenby(parent, order):
                order += 1
                for child in parent:
                    order += 1
                    order = sortchildrenby(child, order)
                parent[:] = sorted(parent, key=lambda child: getUniqueId(child) if str(child.tag) in tagsToSort else order)
                return order

            tree = ET.parse(xml_file_path)
            root = tree.getroot()
            #remove the build number and other version dependent attributes
            root.find("header").remove(root.find("header").find("applicationBuildNumber"))
            root.find("header").remove(root.find("header").find("applicationVersion"))
            root.find("header").remove(root.find("header").find("catrobatLanguageVersion"))
            root.find("header").remove(root.find("header").find("description"))

            sortchildrenby(root, order)
            result = ""
            for line in ET.tostring(root).split("\n"):
                result += line.strip()+"\n"
            return result

        xml = sortAndStripCodeXml(xml_file_path)
        hash_of_xml_file = hash(xml)
        if hash_of_xml_file == config_params.code_xml_hash:
            log.info("Project hash OK")
        else:
            log.error("Project hash unexpected, has: " + str(hash_of_xml_file)
                      + " but should be: " + str(config_params.code_xml_hash))
            failed = True
        os.remove("tmp/project.zip")
        os.remove("tmp/code.xml")
        return failed

    ws = None
    try:
        ws = websocket.create_connection(config_params.conversionurl)
        authenticate()
        start_conversion()
        result = retrieve_info()
        download_path = ClientRetrieveInfoCommand.get_download_url(result, config_params.scractchprojectid)
        ziped_project = download_project()
        failed = validate_ziped_project()
        #TODO idea: check without force flag if caching works

    except:
        log.error("Exception while Conversion: " + traceback.format_exc())
        failed = True
    try:
        ws.close()
    except AttributeError:
        log.error("Could not close websocket "+ traceback.format_exc())
    return failed