def compose_send_email(exec_type, abs_filepath, logs_dir, results_dir, result,
                       mail_on="per_execution"):
    """ compose and sends email from smtp server using input arguments as:
    :Arguments:
        1. exec_type - type of test(case/suite/project)
        2. abs_filepath - full path of case/suite/project
        3. logs_dir - full path of logs directory
        4. results_dir - full path of results directory
        5. result - execution result
        6. mail_on(optional) - it is to specify when to send an email
           Supported options below:
                (1) per_execution(default)
                (2) first_failure
                (3) every_failure
    """
    resultconverted = {"True": "Pass", "False": "Fail", "ERROR": "Error",
                       "EXCEPTION": "Exception", "RAN": "Ran"}.get(str(result))
    subject = str(resultconverted)+": "+file_Utils.getFileName(abs_filepath)
    body = construct_mail_body(exec_type, abs_filepath, logs_dir, results_dir)
    report_attachment = results_dir + os.sep + \
        file_Utils.getNameOnly(file_Utils.getFileName(abs_filepath)) + ".html"
    log_attachment = logs_dir + os.sep + \
        file_Utils.getNameOnly\
        (file_Utils.getFileName(abs_filepath)) + "_consoleLogs.log"

    if mail_on in ["per_execution"] and file_Utils.fileExists(report_attachment):
        files = [report_attachment]
    elif mail_on in ["first_failure", "every_failure"] and file_Utils.fileExists(log_attachment):
        files = [log_attachment]
    set_params_send_email(subject, body, files, mail_on)
def get_execution_files(filepath, execution_dir, extn):
    """Get the execution files like resultfile, logfile etc"""

    filename = file_Utils.getFileName(filepath)
    nameonly = file_Utils.getNameOnly(filename)
    if extn.lower() == "res":
        fullpath = execution_dir + os.sep + nameonly + "_results" + "." + extn
    else:
        fullpath = execution_dir + os.sep + nameonly + '.' + extn
    if file_Utils.fileExists(fullpath):
        fullpath = file_Utils.addTimeDate(fullpath)
    return fullpath
def get_default_xml_datafile(filepath):
    """Get the default datafile for a testcase/testsuite file

    :Arguments:
        1. filepath   = full path of the input xml file
    """
    inpdir = os.path.split(filepath)[0]
    filename = file_Utils.getFileName(filepath)
    nameonly = file_Utils.getNameOnly(filename)
    data_dir = os.sep.join(inpdir.split(os.sep)[:-1]) + os.sep + 'Data'

    def_datafile_path = data_dir + os.sep + nameonly + '_Data.xml'
    return def_datafile_path
def construct_mail_body(exec_type, abs_filepath, logs_dir, results_dir):
    """ construct e-mail body with Project, Logs/Results directory & Execution summary
    :Arguments:
        1. exec_type - type of test(case/suite/project)
        2. abs_filepath - full path of case/suite/project
        3. logs_dir - full path of logs directory
        4. results_dir - full path of results directory
    :Returns:
        1. body - return mail body
    """
    junit_result_file = os.path.join(
        results_dir, file_Utils.getNameOnly(file_Utils.getFileName(abs_filepath))) + "_junit.xml"
    suite_tc, body = "", ""
    body_arg = ('<html><body><p><b>{0}</b>{1}</p>'
                '<p><b>Logs directory:</b>{2}</p>'
                '<p><b>Results directory:</b>{3}</p>').format(exec_type, abs_filepath,\
                                                    logs_dir, results_dir)
    body_arg1 = ('<p><b>Execution Summary:</b></p>'
                '<table cellspacing="10" cellpadding="0"><tr><td><b>Type</b>'
                '</td><td><b>Name</b></td><td><b>Status</b></td>'
                '<td><b>Path</b></td></tr>')
    if file_Utils.fileExists(junit_result_file):
        body_arg = body_arg + body_arg1
        junit_object = ExecutionSummary(junit_result_file)
        project_sum = junit_object.project_summary(junit_result_file)
        suite_tc_sum = junit_object.suite_summary(junit_result_file)
        # complete html body that will be sent through mail
        if exec_type == 'Project: ':
            project = ""
            for proj in project_sum:
                project = project + ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>\n'\
                                 .format(proj[0], proj[1], proj[2], proj[3]))
            for value in suite_tc_sum:
                suite_tc = suite_tc + ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>\n'\
                                   .format(value[0], value[1], value[2], value[3]))
            body = body_arg + project + suite_tc + "</table></body></html>"
        elif exec_type == 'Test Suite: ' or exec_type == 'Test Case: ':
            for value in suite_tc_sum:
                suite_tc = suite_tc + ('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>\n'\
                                   .format(value[0], value[1], value[2], value[3]))
            body = body_arg + suite_tc + "</table></body></html>"
    else:
        body = body_arg + "</table></body></html>"
    return body
    def sftp_from_remotehost(cls, session_object, ip_type, sftp_operation, port,
                             filepath, prompt, dest_address, username,
                             password, filepath_dest):
        """sftp(test both put and get).This keyword can be used to transfer
        file from source _system to destination system or vice versa.
        It checks the size after transfer in both get and put.

        :Arguments:
            1. session_object(string)  = name of the Linux machine on which\
                                      to execute
            2. ip_type(string) = iptype of the dest system through \
                                 which it needs to be connected.
                                 needs to be one of \
                                 (ip/ipv4/dns/lmp_ip/lmp_ipv6).It has to be \
                                 present in the input data file.
            3. sftp_operation(string) = get/put/both
            4. port(string) = source port
            5. filepath(string) = file with filepath in source\
                                  system(used for put)
            6. prompt(string)  = prompt of the source system
            7. dest_address(string) = ipv4 address or defaulted to lcn ip
            8. username(string) = username of the dest system
            9. password(string) = password of the dest system
            9. filepath_dest(string) = file with filepath in destination\
                               system(used for get)
        :Returns:
            1. bool (True/False)

        """
        put = True if ("put" in sftp_operation or "both" in sftp_operation) \
            else False
        get = True if ("get" in sftp_operation or "both" in sftp_operation) \
            else False

        status_get = False if get else True
        status_put = False if put else True

        filedir, filename = (file_Utils.getDirName(filepath),
                             file_Utils.getFileName(filepath))
        filedir_dest, filename_dest = (file_Utils.getDirName(filepath_dest),
                                       file_Utils.getFileName(filepath_dest))

        sftp_cmd = "sftp"
        if ip_type == "ipv6":
            sftp_cmd = "sftp6"

        # move into the path
        session_object.send_command(".*", prompt, "cd {}".format(filedir))
        command = sftp_cmd + "  -oPort={0} {1}@{2}".format(port, username,
                                                           dest_address)

        # check whether file is available
        putfilepresent = cls.file_exists_on_remote(session_object, prompt,
                                                   filename)
        if putfilepresent:
            # check the put file size
            put_file_size = cls.get_file_size(session_object, prompt, filename)

        else:
            pNote("Specified put file:{} not found".format(filename), "error")

        # Starting the sftp connection
        status = cls.start_sftp_on_remote(session_object, command,
                                          password, prompt)
        if status:
            session_object.send_command(".*", ">", "cd {}".format(filedir_dest))

            if putfilepresent and put:
                status_put = cls.sftp_put_from_remote(session_object,
                                                      filename, filedir)
                put_file_size_transf = cls.get_file_size(session_object, ">",
                                                         filename,
                                                         session="sftp")
                if status_put:
                    pNote("Actual put file size:{0} Transferred put file size"
                          ":{1}".format(str(put_file_size), str(put_file_size_transf)))
                    if str(put_file_size) == str(put_file_size_transf):
                        status_put = True
                        pNote("Transferred put file size matches the origin")
                    else:
                        status_put = False
                        pNote("Transferred put file size does not"
                              "match the origin")

            if get:
                # check whether file is available
                getfilepresent = cls.file_exists_on_remote(session_object, ">",
                                                           filename_dest)

                if getfilepresent:
                    gfile_size = cls.get_file_size(session_object, ">",
                                                   filename_dest,
                                                   session="sftp")
                    status_get = cls.sftp_get_from_remote(session_object,
                                                          filename_dest,
                                                          filedir_dest)

                    # exiting the sftp terminal
                    session_object.send_command(".*", prompt, "exit")

                    if status_get:
                        # check the get file size after transfer
                        gfile_size_transf = cls.get_file_size(session_object,
                                                              prompt,
                                                              filename_dest)

                        pNote("Actual get file size:{0} Transferred get file"
                              "size:{1}".format(str(gfile_size), str(gfile_size_transf)))
                        if str(gfile_size) == str(gfile_size_transf):
                            status_get = True
                            pNote("Transferred get file size matches the origin")
                        else:
                            status_get = False
                            pNote("Transferred get file size matches the origin")
                else:
                    pNote("Specified get file:{} not found".format(filename_dest),
                          "error")

            else:
                session_object.send_command(".*", prompt, "exit")

            status = status_get and status_put
        else:
            status = False
        return status