예제 #1
0
  def run(self, configFile, otu, threads):
    rc = ReadConfig()
    projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = False)

    ggDB = self.ggDB.replace('##', str(otu), 1)
    print 'Mapping reads to the GreenGenes DB at: ' + ggDB + '\n'

    if not os.path.exists(ggDB + '.amb'):
      print 'Indexing GreenGenes DB:'
      os.system('bwa index -a is ' + ggDB)
      print ''
    else:
      print 'GreenGenes DB is already indexed.\n'

    for sample in sampleParams:
      print 'Mapping reads in sample: ' + sample

      pairs = sampleParams[sample]['pairs']
      singles = sampleParams[sample]['singles']

      # align and map each pair
      for i in xrange(0, len(pairs), 2):
        pair1 = pairs[i]
        pair2 = pairs[i+1]
        bamPrefix = projectParams['output_dir'] + ntpath.basename(pair1)
        mapPair(ggDB, pair1, pair2, bamPrefix, threads)

      # align and map each single-ended read file
      for i in xrange(0, len(singles)):
        bamPrefix = projectParams['output_dir'] + ntpath.basename(singles[i])
        mapSingle(ggDB, singles[i], bamPrefix, threads)
예제 #2
0
    def run(self, configFile, threads, evalue, bQuiet):
        rc = ReadConfig()
        projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)
        os.makedirs(projectParams['output_dir'] + 'extracted_lsu')

        self.bQuiet = bQuiet

        for sample in sampleParams:
            pairs = sampleParams[sample]['pairs']
            singles = sampleParams[sample]['singles']

            # identify 16S sequences in paired-end reads
            self.processPairs(pairs, threads, evalue, projectParams['output_dir'], sample)

            # identify 16S sequences in single-end reads
            self.processSingles(singles, threads, evalue, projectParams['output_dir'], sample)
예제 #3
0
    def run(self, configFile, contigFile, assemblies16S, binDir, threads):
        rc = ReadConfig()
        projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)

        # check if links directory already exists
        linkFile = os.path.join(projectParams['output_dir'], 'linksToBin')
        if not os.path.exists(linkFile):
            os.makedirs(linkFile)
        else:
            rtn = raw_input('Remove previously identified links (Y or N)? ')
            if rtn.lower() == 'y' or rtn.lower() == 'yes':
                files = os.listdir(linkFile)
                for f in files:
                    os.remove(os.path.join(linkFile, f))
            else:
                sys.exit()

        outputDir = os.path.join(projectParams['output_dir'], 'linksToBin')

        # create combined file with reference sequences and assembled 16S sequences
        print 'Combining unbinned reference sequences with de novo assembled 16S sequences.'
        combinedFile = os.path.join(outputDir, 'scaffolds.combined.fasta')
        os.system('cat ' + contigFile + ' ' + assemblies16S + ' > ' + combinedFile)

        # create combined 16S read files
        print 'Combining 16S/18S reads from all samples.'
        reads1 = ''
        reads2 = ''
        for sample in sampleParams:
            extractedPrefix = os.path.join(projectParams['output_dir'], 'extracted', sample)
            pairs = sampleParams[sample]['pairs']
            for i in xrange(0, len(pairs), 2):
                pair1Base = ntpath.basename(pairs[i])
                pair2Base = ntpath.basename(pairs[i+1])

                classificationFile1 = extractedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.union.SSU.fasta'
                classificationFile2 = extractedPrefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.union.SSU.fasta'

                reads1 += classificationFile1 + ' '
                reads2 += classificationFile2 + ' '

        os.system('cat ' + reads1 + ' > ' + os.path.join(outputDir, 'ssu.1.fasta'))
        os.system('cat ' + reads2 + ' > ' + os.path.join(outputDir, 'ssu.2.fasta'))

        # identify 16S sequences in paired-end reads
        self.link16S(combinedFile, os.path.join(outputDir, 'ssu.1.fasta'), os.path.join(outputDir, 'ssu.2.fasta'), binDir, threads, outputDir)
예제 #4
0
  def run(self, configFile, mappingQual, minLength):
    self.mappingQualityThreshold = mappingQual
    self.minLength = minLength

    rc = ReadConfig()
    projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)

    for sample in sampleParams:
      outputDir = projectParams['output_dir']
      prefix = outputDir + sample
      pairs = sampleParams[sample]['pairs']
      singles = sampleParams[sample]['singles']

      # identify 16S sequences in paired-end reads
      self.processPairs(pairs, outputDir, prefix)

      # identify 16S sequences in single-end reads
      self.processSingles(singles, outputDir, prefix)
예제 #5
0
파일: login.py 프로젝트: yandeqing/apitest
    def tearDown(self):
        """
        执行测试代码后的数据存储
        :return:
        """
        info = self.info
        if info['code'] == 0:
            # set user token to config file
            config = ReadConfig()
            token = info['result']['token']
            secret = info['result']['secret']
            config.set_headers("token", token)
            config.set_headers("secret", secret)

            userlogin = common_utils.get_jsonfrom_file("../../userlogin.json")
            config.set_headers("token", userlogin['token'])
            config.set_headers("secret", userlogin['secret'])
            config.set_headers("uid", userlogin['uid'])

            self.logger.info("step7:执行完毕,保存下一步测试需要用到的数据")
        else:
            pass
        self.logger.info("========执行" + self.case_name + "用例结束=======")
예제 #6
0
by: 老屋
des:
1、用例创建原则,测试文件名必须以“test_”开头,测试函数必须以“test”开头,测试类必须以Test开头。
2、运行方式:
  > python3 run_tests.py  (回归模式,生成HTML报告)
  > python3 run_tests.py -m debug  (调试模式)
"""
import os
import time
import logging
import pytest
import click
from readConfig import ReadConfig

# 读取配置信息做变量
r = ReadConfig()
BASE_DIR = r.BASE_DIR
REPORT_DIR = r.report_dir()
cases_path = r.case_paths()
max_fail = r.max_fail()
rerun = r.rerun()

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def init_env(now_time):
    """
    初始化测试报告目录
    """
예제 #7
0
 def __init__(self, driver):
     self.config = ReadConfig()
     self.driver = driver
     self.baseurl = self.config.get_config('HTTP', 'host')
     self.log = Log()
    def run(self, configFile, threads):
        rc = ReadConfig()
        projectParams, _ = rc.readConfig(configFile, outputDirExists=True)

        # create directory to store putative 16S genes
        dirPutative16S = projectParams['output_dir'] + 'putativeSSU/'
        if not os.path.exists(dirPutative16S):
            print '[Error] Putative 16S gene reads expected in: ' + dirPutative16S
            sys.exit()

        # extract GreenGene Ids of putative 16S genes
        ggIds = set()
        files = os.listdir(dirPutative16S)
        for f in files:
            if f.endswith('fasta'):
                ggIds.add(int(f.split('.')[0]))

        print 'Putative 16S genes to assemble: ' + str(len(ggIds))

        scaffoldInfo = {}
        for ggId in ggIds:
            print 'Assembling ' + str(ggId) + ': '
            print ''

            pair1 = dirPutative16S + str(ggId) + '.1.fasta'
            pair2 = dirPutative16S + str(ggId) + '.2.fasta'
            single = dirPutative16S + str(ggId) + '.singletons.fasta'

            outputDir = dirPutative16S + str(ggId) + '_assembly_spades'
            if os.path.exists(outputDir):
                shutil.rmtree(outputDir)

            cmd = 'spades.py --only-assembler -o ' + outputDir + ' -t ' + str(
                threads)
            if os.stat(single
                       ).st_size > 0:  # check if file contains any sequences
                cmd += ' -s ' + single
            if os.stat(pair1).st_size > 0:
                cmd += ' -1 ' + pair1 + ' -2 ' + pair2

            os.system(cmd)

            scaffoldInfo[ggId] = self.parseScaffoldInfo(outputDir)

        print '\n*********************************'
        allScaffoldsFile = projectParams[
            'output_dir'] + 'assembled_scaffolds.16S.fasta'
        fout = open(allScaffoldsFile, 'w')
        print 'Assembly results: '
        for ggId in scaffoldInfo:
            print '  Assembly of ' + str(ggId) + ' produce ' + str(
                len(scaffoldInfo[ggId])) + ' scaffold(s): ' + ' '.join(
                    scaffoldInfo[ggId])

            if not os.path.isfile(dirPutative16S + str(ggId) +
                                  '_assembly_spades/scaffolds.fasta'):
                print '    Failed to build scaffolds for ' + str(ggId)
                continue

            index = 0
            for line in open(dirPutative16S + str(ggId) +
                             '_assembly_spades/scaffolds.fasta'):
                if line[0] == '>':
                    lineSplit = line.split('_')
                    seqLen = lineSplit[3]

                    fout.write('>16S_' + str(ggId) + '-' + str(index) + ' ' +
                               seqLen + '\n')

                    index += 1
                else:
                    fout.write(line)
        fout.close()

        print ''
        print '  All assembled 16S contigs written to: ' + allScaffoldsFile
예제 #9
0
 def get_code_num(self):
     self.driver.get("{}/user/casemanage.html?state=1".format(ReadConfig().get_user_url()))
     num = self.driver.find_element_by_xpath("//div[@class='fl']/a[2]/span").text
     return int(num)
예제 #10
0
class SendMail():

    re = ReadConfig()
    #配置SMTP属性
    host = re.get_email('mail_host')
    username = re.get_email('mail_user')
    pwd = re.get_email('mail_pass')

    #配置邮件发送属性
    sender = re.get_email('sender')
    receiver = re.get_email('receiver')
    subject = re.get_email('subject')
    content = re.get_email('content')

    # 发送html格式邮件
    msg = MIMEMultipart()

    # 配置附件的属性
    def config_file(self):

        # 调用获取最新文件的方法
        file = self.find_new_file()
        # 添加附件,并打开文件
        f = open(file, 'rb')
        mail_body = f.read()

        # 创建消息对象
        filemsg = MIMEText(mail_body, 'plain', 'utf-8')
        # print(filemsg)

        filemsg["Content-Type"] = 'application/octet-stream'
        filemsg["Content-Disposition"] = 'attachment; filename=report.html'

        self.msg.attach(filemsg)

        self.msg['From'] = self.sender
        self.msg['To'] = self.receiver
        self.msg['subject'] = '接口测试报告'
        self.msg.attach(MIMEText('附件为接口自动化测试报告,请查收', 'plain', 'utf-8'))

    def send_email(self):

        self.config_file()

        try:
            # 创建一个 SMTP() 对象
            r = smtplib.SMTP()
            # 通过 connect 方法连接 smtp 主机
            r.connect(host=self.host)
            # 邮箱账号登录校验
            r.login(user=self.username, password=self.pwd)
            # 发送邮件
            r.sendmail(self.sender, self.receiver, self.msg.as_string())
            print('邮件发送成功')

        except Exception as msg:
            print('邮件发送失败', msg)
        finally:
            r.close()

    # 查找最新的文件
    def find_new_file(self):
        # 获取当前路径
        current_path = os.path.dirname(os.path.abspath(__file__))
        print('---current', current_path)

        # 获取报告的存放路径
        filePath = os.path.dirname(current_path) + '/' + 'report'
        fileList = os.listdir(filePath)
        #print(fileList)

        fileList = os.listdir(filePath)

        # 定义一个字典来接收文件的路径及文件名
        fileDict = {}
        # 定义一个列表来接收文件的时间
        fileTime = []

        #查找这个文件列表中每个文件的路径及文件名
        for iName in fileList:
            # 拼接文件路径和文件名
            filename = filePath + "/" + iName

            # 获取该文件的修改时间
            iTime = os.path.getmtime(filename)
            print(iTime)
            # 将文件的修改时间追加到时间列表中
            fileTime.append(iTime)
            # 将文件名iName作为字典的value,文件的修改时间iTime作为字典的key存入
            fileDict[iTime] = iName
            # fileD现在是空字典,把文件名和时间以键值对形式填充
        # print(fileDict, fileTime)

        # 查找时间列表中最新的文件
        sendfilekey = max(fileTime)

        #  把这个时间对应的文件名找出来,通过key查找value
        sendfile = fileDict[sendfilekey]
        # print(sendfile)
        sendfile = filePath + "/" + sendfile
        return sendfile
예제 #11
0
import pymysql
from readConfig import ReadConfig
from Base.BaseLog import MyLog

config_database = ReadConfig("DATABASE").readconfig()


class MyDB:
    global host, username, password, port, database, config
    host = config_database["host"]
    username = config_database["username"]
    password = config_database["password"]
    port = config_database["port"]
    database = config_database["database"]
    config = {
        'host': host,
        'user': username,
        'passwd': password,
        'port': port,
        'db': database
    }

    def __init__(self):
        self.log = MyLog.get_log()
        self.logger = self.log.get_logger()
        self.db = None
        self.cursor = None

    def connectDB(self):
        try:
            self.db = pymysql.connect(**config)
예제 #12
0
class ConfigEmail():

    #读取ini文件配置属性
    re = ReadConfig()
    host = re.get_email('mail_host')
    sender = re.get_email('sender')
    receiver = re.get_email('receiver')
    user = re.get_email('mail_user')
    pwd = re.get_email('mail_pass')
    subject = re.get_email('subject')
    content = re.get_email('content')

    #配置邮件属性
    msg = MIMEMultipart()
    msg['from'] = sender
    msg['to'] = receiver
    msg['subject'] = Header(subject, 'utf-8')
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    def config_file(self):
        #配置附件属性
        file = self.find_file()
        print(file)
        sendfile = open(file, 'rb').read()
        att = MIMEText(sendfile, 'plain', 'utf-8')
        att["Content-Type"] = 'application/octet-stream'
        att["Content-Disposition"] = 'attachment; filename=report.html'
        self.msg.attach(att)
        self.msg['From'] = self.sender
        self.msg['To'] = self.receiver
        self.msg['Subject'] = 'Python SMTP 附件邮件测试'
        self.msg.attach(MIMEText('UI自动化报告邮件,如果想查看详情请查收附件', 'plain', 'utf-8'))

    def find_file(self):
        #查找最新文件
        current_path = os.path.dirname(os.path.abspath(__file__))
        # print('current',current_path)
        filePath = os.path.dirname(current_path) + "/" + 'testreport'
        # print('filepath',filePath)

        fileList = os.listdir(filePath)
        # print(fileList)
        fileDict = {}
        fileTime = []
        for i in fileList:
            filename = filePath + "/" + i
            iTime = os.path.getmtime(filename)
            fileTime.append(iTime)
            fileDict[iTime] = i
        # print(fileDict,fileTime)

        sendfilekey = max(fileTime)
        sendfile = fileDict[sendfilekey]
        # print(sendfile)
        sendfile = filePath + "/" + sendfile
        return sendfile

    #发送邮件
    def send_mail(self):
        try:
            r = smtplib.SMTP()
            r.connect(host=self.host)
            r.login(user=self.user, password=self.pwd)
            r.sendmail(self.sender, self.receiver, msg=self.msg.as_string())

        except Exception as msg:
            print('邮件发送失败!')
            print(msg)
        else:
            print('邮件发送成功')
        finally:
            r.close()


#
# if __name__ == '__main__':
# #     pass
# c = ConfigEmail()
# c.send_mail()
예제 #13
0
from tool.readExcel import readExcel
from tool.common import PublicMethod
import unittest
import const
from readConfig import ReadConfig
from tool.Logger import Log
import HtmlTestRunner

read_config = ReadConfig()
log = Log()


class testLoginApi(unittest.TestCase):
    '''登录测试'''
    def setUp(self):
        self.file = read_config.get_test_file('test_file')
        self.URL_prefix = read_config.get_http("url")

    def test_login(self):
        '''测试登录接口'''
        # 获取excel内容
        test_File = const.TESTFILE + self.file
        # test_File = r'C:\Users\吴运超\PycharmProjects\Autotest\test_Feil/'+self.file
        excel = readExcel(test_File)
        name = excel.getName
        data = excel.getData
        msg = excel.getMsg
        log.info(msg)
        url = excel.getUrl
        method = excel.getMethod
        id = excel.getId
예제 #14
0
from selenium.webdriver.support.ui import WebDriverWait

from front_login import *
from readConfig import ReadConfig
from db import DbOperate

# 有头
driver = webdriver.Chrome()
# 无头浏览器
# from selenium.webdriver.chrome.options import Options
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# driver = webdriver.Chrome(chrome_options=chrome_options)

driver.maximize_window()
driver.get(ReadConfig().get_root_url())


class FunctionName(type):
    def __new__(cls, name, bases, attrs, *args, **kwargs):
        count = 0
        attrs["__Func__"] = []
        for k, v in attrs.items():
            # 专利
            if "patent_" in k:
                attrs["__Func__"].append(k)
                count += 1

        attrs["__FuncCount__"] = count
        return type.__new__(cls, name, bases, attrs)
    def run(self, configFile, threads):
        rc = ReadConfig()
        projectParams, _ = rc.readConfig(configFile, outputDirExists = True)

        # create directory to store putative 16S genes
        dirPutative16S = projectParams['output_dir'] + 'putativeSSU/'
        if not os.path.exists(dirPutative16S):
            print '[Error] Putative 16S gene reads expected in: ' + dirPutative16S
            sys.exit()

        # extract GreenGene Ids of putative 16S genes
        ggIds = set()
        files = os.listdir(dirPutative16S)
        for f in files:
            if f.endswith('fasta'):
                ggIds.add(int(f.split('.')[0]))

        print 'Putative 16S genes to assemble: ' + str(len(ggIds))

        scaffoldInfo = {}
        for ggId in ggIds:
            print 'Assembling ' + str(ggId) + ': '
            print ''

            pair1 = dirPutative16S + str(ggId) + '.1.fasta'
            pair2 = dirPutative16S + str(ggId) + '.2.fasta'
            single = dirPutative16S + str(ggId) + '.singletons.fasta'

            outputDir = dirPutative16S + str(ggId) + '_assembly_spades'
            if os.path.exists(outputDir):
                shutil.rmtree(outputDir)

            cmd = 'spades.py --only-assembler -o ' + outputDir + ' -t ' + str(threads)
            if os.stat(single).st_size > 0: # check if file contains any sequences
                cmd += ' -s ' + single
            if os.stat(pair1).st_size > 0:
                cmd += ' -1 ' + pair1 + ' -2 ' + pair2

            os.system(cmd)

            scaffoldInfo[ggId] = self.parseScaffoldInfo(outputDir)

        print '\n*********************************'
        allScaffoldsFile = projectParams['output_dir'] + 'assembled_scaffolds.16S.fasta'
        fout = open(allScaffoldsFile, 'w')
        print 'Assembly results: '
        for ggId in scaffoldInfo:
            print '  Assembly of ' + str(ggId) + ' produce ' + str(len(scaffoldInfo[ggId])) + ' scaffold(s): ' + ' '.join(scaffoldInfo[ggId])

            if not os.path.isfile(dirPutative16S + str(ggId) + '_assembly_spades/scaffolds.fasta'):
                print '    Failed to build scaffolds for ' + str(ggId)
                continue

            index = 0
            for line in open(dirPutative16S + str(ggId) + '_assembly_spades/scaffolds.fasta'):
                if line[0] == '>':
                    lineSplit = line.split('_')
                    seqLen = lineSplit[3]

                    fout.write('>16S_' + str(ggId) + '-' + str(index) + ' ' + seqLen + '\n')

                    index += 1
                else:
                    fout.write(line)
        fout.close()

        print ''
        print '  All assembled 16S contigs written to: ' + allScaffoldsFile
예제 #16
0
import json
import requests

# from business import buyerLogin
from readConfig import ReadConfig
from getToken import GetToken
# 执行订单确认
ReadConfig = ReadConfig()

host=ReadConfig.get_config("HTTP","host")
token=GetToken().getBuyertoken()
# host='http://www.raincard.cn'
def confirmOrder():

    url = '/api/v1/order/confirm/create'
    cookies = {"buyer_token": token}
    params = {
        'sku_json': '[{"sku_id":"S007M9O0YO","buy_vol":1,"price":1,"money_unit":"CNY"}]',
        'shop_id':126,
        "use_coupon_code":"-1",
        "address_id":75
    }

    re = requests.post(host + url, data=params,cookies=cookies)
    print('url=', re.url)
    print('params=', str(params))
    print(re.json())



    v = json.loads(re.text)
예제 #17
0
import redis
from readConfig import ReadConfig

HOST = ReadConfig().redis_host()
PWD = int(ReadConfig().redis_password())
# print(HOST,type(HOST), PWD,type(PWD))

# 移动端使用数据库4
pool = redis.ConnectionPool(host=HOST, port=6379, db=4, password=PWD, encoding='utf-8')
conn = redis.Redis(connection_pool=pool)


class DbOperate:
    def add(self, db, elem):
        if isinstance(elem, list):
            for el in elem:
                res = conn.sadd(db, el)
                print(res, el)
        if isinstance(elem, str):
            res = conn.sadd(db, elem)
            print(res, elem)

    def del_elem(self, db, elem):
        return conn.srem(db, elem)

    def get_length(self, db):
        return conn.scard(db)

    def is_member(self, db, elem):
        return conn.sismember(db, elem)
예제 #18
0
        writeProc.start()

        for p in calcProc:
            p.start()

        for p in calcProc:
            p.join()

        writerQueue.put(None)
        writeProc.join()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Extract 16S/18S sequences from metagenomic data using HMMs.",
                                          formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('config_file', help='project config file.')

    parser.add_argument('-t', '--threads', help='number of threads', type=int, default = 1)
    parser.add_argument('-e', '--evalue', help='e-value threshold for identifying hits', default = '1e-5')
    parser.add_argument('-a', '--align_len', type=float, help='fraction of read that must align for identifying hits', default = '0.5')
    parser.add_argument('-q', '--quiet', help='suppress all output', action='store_true')

    args = parser.parse_args()

    # Read config file
    rc = ReadConfig()
    projectParams, sampleParams = rc.readConfig(args.config_file, outputDirExists = False)

    extract16S = Extract16S()
    extract16S.run(projectParams, sampleParams, args.threads, args.evalue, args.align_len, args.quiet)
    def run(self, configFile, threads, kmerLen, minContigLen):
        rc = ReadConfig()
        projectParams, _ = rc.readConfig(configFile, outputDirExists = True)

        # create directory to store putative 16S genes
        dirPutative16S = projectParams['output_dir'] + 'putativeSSU/'
        if not os.path.exists(dirPutative16S):
            print '[Error] Putative 16S gene reads expected in: ' + dirPutative16S
            sys.exit()

        # extract GreenGene Ids of putative 16S genes
        ggIds = set()
        files = os.listdir(dirPutative16S)
        for f in files:
            if f.endswith('fasta'):
                ggIds.add(int(f.split('.')[0]))

        print 'Putative 16S genes to assemble: ' + str(len(ggIds))

        contigInfo = {}
        for ggId in ggIds:
            print 'Assembling ' + str(ggId) + ': '
            print ''

            pair1 = dirPutative16S + str(ggId) + '.1.fasta'
            pair2 = dirPutative16S + str(ggId) + '.2.fasta'
            single = dirPutative16S + str(ggId) + '.singletons.fasta'

            outputDir = dirPutative16S + str(ggId) + '_assembly'
            if os.path.exists(outputDir):
                shutil.rmtree(outputDir)

            cmd = 'mpiexec -n ' + str(threads) + ' Ray -k ' + str(kmerLen) + ' -minimum-contig-length ' + str(minContigLen) + ' -o ' + outputDir
            if os.stat(single).st_size > 0: # check if file contains any sequences
                cmd += ' -s ' + single
            if os.stat(pair1).st_size > 0:
                cmd += ' -p ' + pair1 + ' ' + pair2

            os.system(cmd)

            contigInfo[ggId] = self.parseContigInfo(outputDir)

        print '\n*********************************'
        allContigsFile = projectParams['output_dir'] + 'assembled_contigs.16S.fasta'
        fout = open(allContigsFile, 'w')
        print 'Assembly results: '
        for ggId in contigInfo:
            print '  Assembly of ' + str(ggId) + ' produce ' + str(len(contigInfo[ggId])) + ' contig(s): ' + ' '.join(contigInfo[ggId])

            index = 0
            for line in open(dirPutative16S + str(ggId) + '_assembly/Contigs.fasta'):
                if line[0] == '>':
                    lineSplit = line.split()
                    seqLen = lineSplit[1]

                    fout.write('>16S_' + str(ggId) + '-' + str(index) + ' ' + seqLen + '\n')

                    index += 1
                else:
                    fout.write(line)
        fout.close()

        print ''
        print '  All assembled 16S contigs written to: ' + allContigsFile
예제 #20
0
import requests
from readConfig import ReadConfig
from common.log import Log

localReadConfig = ReadConfig()

class ConfigHttp:
    def __init__(self):
        self.host = localReadConfig.get_http("baseurl")
        self.port = localReadConfig.get_http("port")
        self.timeout = localReadConfig.get_http("timeout")
        self.logger = Log().get_logger()
        self.headers = {}
        self.params = {}
        self.data = {}
        self.url = ""
        self.files = {}

    def set_url(self, url, host=""):
        if host == "":
            self.url= self.host + url
        else:
            self.url = host + url

    def set_headers(self, header):
        self.headers = header

    def set_params(self, param):
        self.params = param

    def set_data(self, data):
예제 #21
0
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from datetime import datetime
import threading
from readConfig import ReadConfig
from Base.BaseLog import MyLog
import zipfile
import glob

PATH = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p))
# print(PATH("../"))

config_email = ReadConfig("EMAIL").readconfig()


class Email:
    def __init__(self):
        global host, user, sender, passwd, port, recevier, title
        host = config_email["mailhost"]
        user = config_email["mailuser"]
        sender = config_email["mailsender"]
        passwd = config_email["mailpass"]
        port = config_email["mailport"]
        recevier = config_email["recevier"]
        # print(recevier)
        # recevier = "*****@*****.**"
        title = config_email["subject"]
예제 #22
0
class Action(object):
    def __init__(self, driver):
        self.config = ReadConfig()
        self.driver = driver
        self.baseurl = self.config.get_config('HTTP', 'host')
        self.log = Log()

    def _open(self):
        self.driver.get(self.baseurl)
        self.driver.maximize_window()

    '''
        定位元素,参数locator为元祖类型
        locator = ('id','xxx')
        driver.find_element(locator)
    

    '''

    # def find_element(self,timeout=20,*loc):
    #     try:
    #         WebDriverWait(self.driver,timeout).until(lambda driver:driver.find_element(*loc).is_displayed())
    #         return self.driver.find_element(*loc)
    #     except:
    #         print("%s 页面中未能找到 %s 元素" % (self,loc))
    def find_element(self, loc, timeout=20):
        try:
            WebDriverWait(self.driver, timeout,
                          0.2).until(EC.presence_of_element_located(loc))
            return self.driver.find_element(loc[0], loc[1])
        except:
            self.log.debug('元素%s未找到!' % (loc[1]))

    def find_elements(self, loc, timeout=20):
        try:
            WebDriverWait(self.driver, timeout,
                          0.2).until(EC.presence_of_element_located(loc))
            return self.driver.find_elements(loc[0], loc[1])
        except:
            self.log.debug('元素%s未找到!' % (loc[1]))

    def click(self, loc, timeout=30):
        ele = self.find_element(loc, timeout)
        try:
            ele.click()
        except Exception as e:
            print(e)
            self.js_click(ele)

        # except:
        #     print('元素%s点击失败! ' % (loc[1]))

    def send_keys(self,
                  loc,
                  vaule,
                  time=20,
                  clear_first=True,
                  enter_end=False,
                  click_first=False):
        try:
            ele = self.find_element(loc, time)
            if click_first:
                self.js_click(ele)
            if clear_first:
                # self.sleep(5)
                # ele.clear()
                # self.sleep(5)
                ele.send_keys(Keys.CONTROL + 'a')
                ele.send_keys(Keys.BACKSPACE)
            ele.send_keys(vaule)
            if enter_end:
                ele.send_keys(Keys.ENTER)
        except AttributeError:
            self.log.debug('元素%s输入文本失败!' % (loc[1]))

    def get_text(self, loc, time=20):
        try:
            ele = self.find_element(loc, time)
            return ele.text
        except:
            self.log.debug('元素%s未获取到文本!' % (loc[1]))

    def get_pagesource(self):
        return self.driver.page_source

    def is_element_exit(self, loc, timeout=20):
        '''判断元素是否存在'''
        try:
            WebDriverWait(self.driver, timeout,
                          0.2).until(EC.presence_of_element_located(loc))
            return True
        except:
            return False

    def highlight(self, element):
        '''高亮元素'''
        self.driver.execute_script(
            "arguments[0].setAttribute('style', arguments[1]);", element,
            "border: 2px solid red;")
        time.sleep(3)

    def js_click(self, ele):
        '''js注入点击事件'''
        # ele = self.find_element(loc)

        # element = self.driver.find_element(loc)
        self.driver.execute_script("arguments[0].click();", ele)

    # def js_clear(self,ele):
    #     # ele.sendKeys(Keys.chord(Keys.CONTROL, "a"))
    #     # ele.sendKeys(Keys.DELETE)
    #     ele.send_keys(Keys.CONTROL, "a")
    #     ele.sendKeys(Keys.DELETE)

    def mouse_hover(self, element):
        '''鼠标悬停'''
        ActionChains(self.driver).move_to_element(element)
        time.sleep(3)

    def mouse_double_click(self, element):
        '''鼠标双击'''
        ActionChains(self.driver).double_click(element)
        time.sleep(3)

    def mouse_release(self):
        '''释放鼠标'''
        ActionChains(self.driver).release()

    def scroll_into_view(self, loc):
        '''滚动直到元素可见'''
        ele = self.driver.find_element(loc[0], loc[1])
        self.driver.execute_script("arguments[0].scrollIntoView();", ele)

    def get_current_time(self):
        '''获取当前时间'''

        curTime = time.strftime("%Y-%m-%d %H:%M:%S",
                                time.localtime(time.time()))
        return curTime

    def move_time(self, startTime, move_unit, move_value):
        '''日期移动'''
        re_time = ''
        move_int = int(move_value)
        # start_time = datetime.datetime.now()
        start_time = datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
        if move_unit == 'second':
            re_time = (start_time + datetime.timedelta(seconds=move_int)
                       ).strftime("%Y-%m-%d %H:%M:%S")
        elif move_unit == 'minate':
            re_time = (start_time + datetime.timedelta(minutes=move_int)
                       ).strftime("%Y-%m-%d %H:%M:%S")
        elif move_unit == 'hour':
            re_time = (start_time + datetime.timedelta(hours=move_int)
                       ).strftime("%Y-%m-%d %H:%M:%S")
        elif move_unit == 'day':
            re_time = (start_time + datetime.timedelta(days=move_int)
                       ).strftime("%Y-%m-%d %H:%M:%S")
        elif move_unit == 'week':
            re_time = (start_time + datetime.timedelta(weeks=move_int)
                       ).strftime("%Y-%m-%d %H:%M:%S")
        return re_time

    def sleep(self, s):
        time.sleep(s)
예제 #23
0
from common.readExcel import ReadExcel
import os, yaml
import unittest, requests
from readConfig import ReadConfig
from common.read_token import get_token
from ddt import ddt, data
from common.readRequests import SendRequests

baseUrl = ReadConfig().get_config('HTTP', "newurl")
path = os.path.join(os.path.dirname(os.getcwd()), 'resource', 'test_api1.xlsx')
testcast = ReadExcel.readExcel(path, 'createorder')

#获取根目录
ypath = os.path.join(os.path.dirname(os.getcwd()), 'common', 'order.yaml')
print('根目录为:%s' % ypath)


@ddt
class TestOrderPage(unittest.TestCase):
    def setUp(self):
        self.s = requests.session()

    def tearDown(self):
        pass

    @data(*testcast)
    def test_api(self, data):
        expect_result = int(data['expect_result'].split(':')[1])
        # 获取token 并放在yaml上
        token = get_token()
        print('yaml中的token:%s' % token)
예제 #24
0
# -*- coding:utf-8 -*-
# @Time  : 2019/8/12 10:04
# @Author: dongyani
# @interfacetest: http://apiv1.starschina.com/cms/v1.2/researchreport/list

from common.configHttp import RunMain
from readConfig import ReadConfig
from common.configMysql import OperationDbInterface
from common.getSign import get_Sign
from common.AES_CBC import AES_CBC
from datetime import datetime
import common.url as url
import requests, unittest, json, time

baseurl = url.baseurl()
version = ReadConfig().get_app('version')
app_key = ReadConfig().get_app('app_key')
aes = AES_CBC()
headers = RunMain().headers()
mysql = OperationDbInterface()

class test_Researchreport_list(unittest.TestCase):
    """测试研报列表"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = baseurl + '/cms/v1.2/researchreport/list'
        self.researchreport_detail = mysql.select_one('select * FROM cms.researchreport ORDER BY RAND() limit 1;')
        self.researchreport_title = mysql.select_all('select researchreport.title FROM cms.researchreport;')

    def test_researchreport_list_01(self):
예제 #25
0
 def getBuyertoken(self):
     '''获取登录的token'''
     token = ReadConfig.get_config("DATABASE", "token")
     print(token)
     return token
import unittest, os
import common.log as Log
import types
from common.common import get_xls, my_assert
from ddt import ddt, data, unpack, file_data
from readConfig import ReadConfig
from common.common import request
model = __name__
if model is '__main__':
    model = 'papi_hao_xin_qing'


@ddt(model=ReadConfig.getConfig().get_model("model"))
class PapiHaoXinQing(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.log = Log.MyLog.get_log().logger
        cls.model = model
        # param = import_module('settings')
        # print(param)

    @file_data(ReadConfig.getConfig().get_case(model))
    @request()
    @my_assert()
    def test(self, status_code, res, *args, assert_res=None, **kwargs):
        self.log.info(res)
        self.log.info(kwargs)
        if assert_res is not None:
            for ar in assert_res:
                if isinstance(ar, types.GeneratorType):
                    for a in ar:
예제 #27
0
# -*- coding:utf-8 -*-
#@Time  : 2019/7/31 16:08
#@Author: dongyani
#@interfacetest: http://apiv1.starschina.com/ims/v1.0/user/info

from readConfig import ReadConfig
from common.md5_sms import timeStamp_md5
from datetime import datetime
from common.getSign import get_Sign
from common.configHttp import RunMain
import common.url as url
import unittest,requests,time

baseurl = url.baseurl()
version = ReadConfig().get_app('version')
app_key = ReadConfig().get_app('app_key')
telephone = ReadConfig().get_app('telephone')
headers = RunMain().headers_get()
md5 = timeStamp_md5()

class test_Userinfo(unittest.TestCase):
    """测试用户信息"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = baseurl + '/ims/v1.0/user/info'
        self.timeStamp = int(time.mktime(datetime.now().timetuple()))
        self.access_token = md5.encrypt_md5(self.timeStamp)

    def get_url_params(self):
        timeStamp = int(time.mktime(datetime.now().timetuple()))
        url_params = '{"app_version":"%(version)s",' \
예제 #28
0
#@Time  : 2019/7/10 10:23
#@Author: pengjuan
#@interfacetest: http://apiv1.starschina.com/cms/v1.0/stream/randlist

from common.AES_CBC import AES_CBC
from common.configHttp import RunMain
from readConfig import ReadConfig
from common.getSign import get_Sign
import common.url as url
import unittest, requests, json, datetime, time

global false, null, true

headers = RunMain().headers()
baseurl = url.baseurl()
version = ReadConfig().get_app("version")
app_key = ReadConfig().get_app("app_key")
aes = AES_CBC()


# 获取随机排序的直播列表
class test_randlist(unittest.TestCase):
    """测试获取随机排序的直播列表接口"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = baseurl + "/cms/v1.2/stream/randlist"

    # 将解密后的字符串转为字典
    def decrypt_to_dict(self, text, split_num, str_split):
        decrypt = str(aes.decrypt(
            text, 'r'))[split_num:].split(str_split)[0] + str_split
예제 #29
0
    def run(self, configFile, otu, seqIdentityThreshold, minSeqCutoff, bPairsAsSingles, bSingleEnded, bQuiet):
        self.bQuiet = bQuiet

        rc = ReadConfig()
        projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)

        ggRefDistFile = self.ggRefDist.replace('##', str(otu))
        neighbours = self.getNeighbours(ggRefDistFile, seqIdentityThreshold)

        # create directory to store putative 16S genes
        dirPutative16S = projectParams['output_dir'] + 'putativeSSU/'
        if not os.path.exists(dirPutative16S):
            os.makedirs(dirPutative16S)
        else:
            rtn = raw_input('Remove previously recovered 16S reads (Y or N)? ')
            if rtn.lower() == 'y' or rtn.lower() == 'yes':
                files = os.listdir(dirPutative16S)
                for f in files:
                    if f.endswith('fasta'):
                        os.remove(dirPutative16S + '/' + f)
            else:
                sys.exit()

        referenceSeqHits = {}
        for sample in sampleParams:
            if not self.bQuiet:
                print ''
                print sample + ':'

            extractedPrefix = os.path.join(projectParams['output_dir'], 'extracted', sample)
            classifiedPrefix = os.path.join(projectParams['output_dir'], 'classified' + sample)
            pairs = sampleParams[sample]['pairs']
            singles = sampleParams[sample]['singles']

            for i in xrange(0, len(pairs), 2):
                pair1Base = ntpath.basename(pairs[i])
                pair2Base = ntpath.basename(pairs[i+1])

                classificationFile1 = classifiedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.intersect.16S.tsv'
                classificationFile2 = classifiedPrefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.intersect.16S.tsv'

                if not self.bQuiet:
                    print '  Processing files: '
                    print '    ' + classificationFile1
                    print '    ' + classificationFile2

                pairFile1 = extractedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.intersect.SSU.fasta'
                pairFile2 = extractedPrefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.intersect.SSU.fasta'

                self.identifyConsistentPairs(referenceSeqHits, pairFile1, pairFile2, classificationFile1, classificationFile2, neighbours, bPairsAsSingles, bSingleEnded)

                if bSingleEnded:
                    classificationFile = classifiedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.difference.16S.tsv'

                    if not self.bQuiet:
                        print '  Processing file: ' + classificationFile

                    singleFile = extractedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.difference.SSU.fasta'
                    self.addSingletons(referenceSeqHits, singleFile, classificationFile)

            if bSingleEnded:
                for single in singles:
                    singleBase = ntpath.basename(single)
                    classificationFile = classifiedPrefix + '.' + singleBase[0:singleBase.rfind('.')] + '.16S.tsv'

                    if not self.bQuiet:
                        print '  Processing file: ' + classificationFile

                    singleFile = extractedPrefix + '.' + singleBase[0:singleBase.rfind('.')] + '.SSU.fasta'
                    self.addSingletons(referenceSeqHits, singleFile, classificationFile)

        self.extractRecoverable16S(referenceSeqHits, neighbours, minSeqCutoff, dirPutative16S)
예제 #30
0
#!/usr/bin/env python3
from readConfig import ReadConfig
from record import SensorReading

myConfig = ReadConfig()

myReadings = SensorReading()

humidity_avg = myConfig.checkHumidVsAverage(myReadings.getHumidity())

temp_avg = myConfig.checkTempVsAverage(myReadings.getTemp())

myReadings.setHumidDiff(humidity_avg)

myReadings.setTempDiff(temp_avg)

myReadings.saveResults()
예제 #31
0
import requests
from readConfig import ReadConfig
from Base.BaseLog import MyLog
import os

PATH = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p))
config_http = ReadConfig("HTTP").readconfig()


class Http:
    def __init__(self, login):
        global scheme, host, port, timeout
        scheme = config_http['scheme']

        if login == "login":
            host = config_http['baseurl_login']
        elif login == "list":
            host = config_http['baseurl_list']

        port = config_http['port']
        timeout = config_http['timeout']
        self.log = MyLog.get_log()
        self.logger = self.log.get_logger()
        self.header = {}
        self.params = {}
        self.data = {}
        self.url = None
        self.files = {}
        self.state = 0

    def set_url(self, url):
예제 #32
0
from common.logger import Logging
from page_obj.base import Page
from readConfig import ReadConfig

logger = Logging('find_course').getlog()
config = ReadConfig()
moneyis = 198.00


class study_centre(Page):
    def __init__(self, driver):
        Page.__init__(self, driver)
        self.config_element = {
            "选择一个课程": [
                'css',
                '#page1 > div > div > div > div.course-aside.panel-md > div.course-about > h3 > a'
            ],
            "已完成": ['css', '#myTabs > li:nth-child(2) > a'],
            "助教": ['xpath', '//*[@id="course_user_menu"]/a[3]'],
            "助教_已完成": ['css', '#myTabs > li:nth-child(2) > a'],
            "助教_已取消": ['xpath', '//*[@id="myTabs"]/li[3]'],
            "宝典": ['xpath', '//*[@id="course_user_menu"]/a[5]'],
            "宝典获取": ['id', 'tab1-tab'],
            "宝典支出": ['css', '#myTabs > li:nth-child(2)'],
            "转赠": [
                'css',
                'body > div:nth-child(11) > div.container > div > div.stay-r > div > div.panel-body.relate > div.book-recharge > button'
            ],
            "对方id": ['id', 'user_id'],
            "对方账号": ['id', 'phone_or_email'],
            "转赠宝典": ['id', 'max_score'],
예제 #33
0
파일: redis_demo.py 프로젝트: wujide/tools
 def __init__(self, db_num):
     local_config = ReadConfig()
     host = local_config.get_redis('host')
     password = local_config.get_redis('password')
     pool = redis.ConnectionPool(host=host, password=password, db=db_num, decode_responses=True)
     self.r = redis.Redis(connection_pool=pool)
예제 #34
0
 def __init__(self):
     self._readConfig=ReadConfig()
     self._os_auth_url=self._readConfig.base.os_auth_url
     self._admin_os_tenant_name = self._readConfig.base.admin_os_tenant_name
     self._admin_os_username = self._readConfig.base.admin_os_username
     self._admin_os_password = self._readConfig.base.admin_os_password
예제 #35
0
 def __init__(self):
     config = ReadConfig().getConfig()
예제 #36
0
    def run(self, configFile, db, threads, bQuiet):
        rc = ReadConfig()
        projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)

        # check if classification directory already exists
        if not os.path.exists(os.path.join(projectParams['output_dir'], 'classified')):
            os.makedirs(os.path.join(projectParams['output_dir'], 'classified'))
        else:
            rtn = raw_input('Remove previously classified reads (Y or N)? ')
            if rtn.lower() == 'y' or rtn.lower() == 'yes':
                files = os.listdir(projectParams['output_dir'] + 'classified')
                for f in files:
                    os.remove(projectParams['output_dir'] + 'classified/' + f)
            else:
                sys.exit()

        dbFile = self.dbFiles[db]
        taxonomyFile = self.taxonomyFiles[db]

        if not bQuiet:
            print 'Classifying reads with: ' + dbFile
            print 'Assigning taxonomy with: ' + taxonomyFile
            print 'Threads: ' + str(threads)
            print ''

        # create list of all sequence to classify
        mothurSeqFileList = ''
        for sample in sampleParams:
            prefix = os.path.join(projectParams['output_dir'], 'extracted', sample)
            pairs = sampleParams[sample]['pairs']
            singles = sampleParams[sample]['singles']

            for i in xrange(0, len(pairs), 2):
                pair1Base = ntpath.basename(pairs[i])
                pair1File = prefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.intersect.SSU.fasta'

                pair2Base = ntpath.basename(pairs[i+1])
                pair2File = prefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.intersect.SSU.fasta'

                diffFile = prefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.difference.SSU.fasta'

                mothurSeqFileList += pair1File + '-' + pair2File + '-' + diffFile + '-'

            for single in singles:
                singleBase = ntpath.basename(single)
                singleFile = prefix + '.' + singleBase[0:singleBase.rfind('.')] + '.SSU.fasta'

                mothurSeqFileList += singleFile + '-'

        # classify with mothur
        mothurSeqFileList = mothurSeqFileList[0:-1] # remove trailing dash
        self.classify(mothurSeqFileList, dbFile, taxonomyFile, threads, bQuiet)

        # rename classification file for consistency with down-stream processing
        print 'Final classifications written to: '
        for filename in mothurSeqFileList.split('-'):
            if 'GG' in db:
                inputName = filename[0:filename.rfind('.')] + '.full.wang.taxonomy'
            else:
                inputName = filename[0:filename.rfind('.')] + '.SSURef_111_NR_taxonomy.wang.taxonomy'
            outputName = inputName.replace('/extracted/','/classified/')
            outputName = outputName.replace('SSU.full.wang.taxonomy','16S.tsv')
            os.system('mv ' + inputName + ' ' + outputName)
            print '  ' + outputName
예제 #37
0
    def trademark_order(self):
        self.driver = front_login(ReadConfig().get_user(),
                                  ReadConfig().get_password())
        self.driver.get(detail_url)
        self.driver.maximize_window()

        print(self.driver.current_url)
        print(self.driver.title)
        # 点击立即购买
        self.driver.find_element_by_xpath(
            ".//div[@id='productId']/a[1]").click()
        # 进入下单页
        locator_for_order = (By.XPATH, ".//tbody/tr[@class='tr-comm']/td[1]")
        WebDriverWait(self.driver, 30,
                      0.5).until(EC.element_to_be_clickable(locator_for_order))
        # 提取商标信息
        self.goods_type4 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[1]").text
        self.goods_name4 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[2]").text
        self.goods_code4 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[3]").text
        self.goods_price4 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[4]").text
        self.goods_offical4 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[5]").text
        self.goods_total_price1 = self.driver.find_element_by_xpath(
            ".//tbody/tr[@class='tr-comm']/td[6]").text

        # 处理价格
        self.goods_total_price2 = self.driver.find_element_by_xpath(
            ".//div[@class='fwfBox']//div/em").text
        self.goods_total_price2 = process_price(self.goods_total_price2)

        self.goods_total_price3 = self.driver.find_element_by_xpath(
            ".//div[@class='totalPrice']//div/b").text
        self.goods_total_price3 = process_price(self.goods_total_price3)

        print(self.goods_type4, self.goods_name4, self.goods_code4,
              self.goods_price4, self.goods_offical4, self.goods_total_price1,
              self.goods_total_price2, self.goods_total_price3)

        # 下单
        self.driver.find_element_by_xpath(".//a[@id='lnkPay']").click()
        # 进入支付页面
        # 获取可用余额
        get_usable_balance = self.driver.find_element_by_xpath(
            ".//div[@class='balance-radio']//span").text
        get_usable_balance = process_price(get_usable_balance)

        # 选择余额支付
        # self.driver.find_element_by_xpath(".//div[@class='balance-radio']//span").click()

        # 已使用余额
        used_balance = self.driver.find_element_by_xpath(
            ".//label[@id='lbbalance']").text
        used_balance = process_price(used_balance)
        # used_balance = 0

        # 选择支付宝支付
        self.driver.find_element_by_xpath(
            ".//div[@id='zfbzf']/a[@dataid='1']").click()
        pay_state = "支付宝"
        # 选择微信支付
        # self.driver.find_element_by_xpath(".//div[@id='zfbzf']/a[@dataid='4']").click()
        # pay_state = "微信"

        # 获取所有显示价格
        goods_pay_price1 = self.driver.find_element_by_xpath(
            ".//div[@class='fwfBox']/div/div[1]/em").text
        goods_pay_price1 = process_price(goods_pay_price1)

        goods_pay_for_balance = self.driver.find_element_by_xpath(
            ".//div[@class='fwfBox']/div/div[2]/em").text
        goods_pay_for_balance = process_price(goods_pay_for_balance)

        goods_pay_price2 = self.driver.find_element_by_xpath(
            ".//div[@class='fwfBox']/div/div[3]/em").text
        goods_pay_price2 = process_price(goods_pay_price2)

        goods_pay_price3 = self.driver.find_element_by_xpath(
            ".//div[@class='top']/b").text
        goods_pay_price3 = process_price(goods_pay_price3)

        print([
            goods_pay_price1, goods_pay_for_balance, goods_pay_price2,
            goods_pay_price3, get_usable_balance, used_balance
        ])

        # 支付
        self.driver.find_element_by_xpath(".//a[@id='lnkPay']").click()

        # 进入二维码页面
        # 判断支付总金额是否为0
        if float(goods_pay_price3):
            # 进入二维码页面
            windows = self.driver.window_handles
            self.driver.switch_to.window(windows[-1])

            path = "./screen/screen{}.png".format(self.timetemp)
            # 等待二维码加载
            time.sleep(3)
            # locator_for_QR = (By.XPATH, "//canvas")
            # WebDriverWait(self.driver, 50, 0.5).until(EC.element_to_be_clickable(locator_for_QR))

            QR_price1 = self.driver.find_element_by_xpath(
                ".//span[@id='J_basePriceArea']/strong").text
            QR_price2 = self.driver.find_element_by_xpath(
                ".//div[@class='qrcode-header']/div[2]").text
            print("QR_price1", QR_price1, "QR_price2", QR_price2)
            if not QR_price1:
                QR_price1 = 0
            if not QR_price2:
                QR_price2 = 0

            # 截图
            self.driver.save_screenshot(path)
            time.sleep(0.5)
            self.driver.close()
            self.driver.switch_to.window(windows[0])
            # 点击已完成支付
            self.driver.find_element_by_xpath(
                ".//div[@class='wczfBtn']/input").click()
            print("二维码价格:", [QR_price1, QR_price2])

        else:
            QR_price1, QR_price2 = 0, 0
            sleep(2)
            path = "./screen/Sucess{}.png".format(self.timetemp)
            self.driver.save_screenshot(path)

            submit_status = self.driver.find_element_by_xpath(
                ".//div[@class='comm']/p").text
            # self.driver.find_element_by_link_text(u"确定").click()
            print('submit_status', submit_status)
            self.driver.get(self.trade_manage_url)

        # 进入个人中心,等待页面加载完毕
        locator_for_case = (
            By.XPATH,
            "//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[2]/td[2]/a[1]"
        )
        WebDriverWait(self.driver, 30,
                      0.5).until(EC.element_to_be_clickable(locator_for_case))

        # 获取案件信息
        center_order_number = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[1]/td/span[1]"
        ).text
        # goods_order_number = goods_order_number.replace("订单号:", "")
        center_pay_state = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[1]/td/span[3]"
        ).text

        center_goods_name = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[2]/td/span[1]"
        ).text
        center_goods_name = center_goods_name.replace("商品名称:", "")
        center_goods_type = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[2]/td/span[2]"
        ).text
        center_goods_type = center_goods_type.replace("商品分类:", "")

        center_case_code = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[2]/td/span[3]"
        ).text
        center_case_code = center_case_code.replace("案件编号:", "").strip()
        # 交易状态
        center_case_trade_state = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[2]/tbody[1]/tr[2]/td[3]/div[@class='proess']"
        ).text
        center_case_price = self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[@class='zc-payment-comm']//tr[2]/td[4]/span"
        ).text
        print("交易状态:", [
            center_order_number, center_pay_state, center_goods_name,
            center_case_code, center_case_price
        ])

        # 商标详情
        self.driver.find_element_by_xpath(
            ".//table[@class='zc-payment-comm']/tbody/tr[2]/td[2]/a[1]").click(
            )
        windows = self.driver.window_handles
        self.driver.switch_to.window(windows[-1])
        goods_detail_name2 = self.driver.find_element_by_xpath(
            ".//div[@class='title']/h2").text
        goods_trade_state = self.driver.find_element_by_xpath(
            ".//div[@class='tm-mark-detail-money']/div/span[1]").text
        print("交易状态", goods_trade_state)
        print("goods_detail_name2", goods_detail_name2)
        self.driver.switch_to.window(windows[0])
        # self.driver.close()

        # 订单详情
        self.driver.find_element_by_xpath(
            ".//div[@class='zc-case-table']/table[2]//td[@class='same pay']/a[2]"
        ).click()
        windows = self.driver.window_handles
        self.driver.switch_to.window(windows[-1])
        time.sleep(1)
        # 支付方式,处理后类型float
        time.sleep(1)

        # locator_for_detail = (By.XPATH, ".//div[@class='caseComm']/div[1]/p[2]")
        # WebDriverWait(self.driver, 30, 0.5).until(EC.element_to_be_clickable(locator_for_detail))

        order_detail_pay_state = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[2]").text
        order_detail_pay_state = process_order_infos(order_detail_pay_state)
        order_detail_pay_state = "支付宝"
        # 总费用,处理后类型float
        order_detail_total_price = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[3]/span").text
        order_detail_total_price = turn_to_float(
            get_price(order_detail_total_price)[0])
        # 红包支付金额,处理后类型float
        order_detail_red_packet = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[4]").text
        order_detail_red_packet = turn_to_float(
            get_price(order_detail_red_packet)[0])
        # 余额支付,处理后类型float
        order_detail_balance_pay = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[5]").text
        order_detail_balance_pay = turn_to_float(
            get_price(order_detail_balance_pay)[0])
        # 应付总额,处理后类型float
        order_detail_should_total = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[6]").text
        print("总额", order_detail_should_total)
        all_price = get_price(order_detail_should_total)
        print("所有价格", all_price)
        order_detail_should_total = turn_to_float(all_price[0])
        # 总费用
        order_detail_should_total_all = turn_to_float(all_price[1])
        # 红包支付金额
        order_detail_should_total_red = turn_to_float(all_price[2])
        # 余额支付金额
        order_detail_should_total_balance = turn_to_float(all_price[3])
        # 应付总额2
        order_detail_should_total2 = turn_to_float(all_price[4])

        # 付款时间
        order_detail_pay_time = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[1]/p[8]").text
        order_detail_pay_time = process_order_infos(order_detail_pay_time)
        aa = {
            "order_detail_total_price": order_detail_total_price,
            "order_detail_red_packet": order_detail_red_packet,
            "order_detail_balance_pay": order_detail_balance_pay,
            "order_detail_should_total": order_detail_should_total,
            "order_detail_should_total_all": order_detail_should_total_all,
            "order_detail_should_total_red": order_detail_should_total_red,
            "order_detail_should_total_balance":
            order_detail_should_total_balance,
            "order_detail_should_total2": order_detail_should_total2,
            "order_detail_pay_time": order_detail_pay_time
        }
        print("订单详情", aa)
        # 收件人
        order_detail_receiver = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[2]/p[2]").text
        order_detail_receiver = process_order_infos(order_detail_receiver)
        # 收件地址
        order_detail_receive_address = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[2]/p[3]").text
        order_detail_receive_address = process_order_infos(
            order_detail_receive_address)
        # 手机号
        order_detail_receive_phone = self.driver.find_element_by_xpath(
            ".//div[@class='caseComm']/div[2]/p[4]").text
        order_detail_receive_phone = process_order_infos(
            order_detail_receive_phone)
        bb = {
            "order_detail_receiver": order_detail_receiver,
            "order_detail_receive_address": order_detail_receive_address,
            "order_detail_receive_phone": order_detail_receive_phone
        }
        print("收件信息", bb)
        # self.driver.quit()

        # 删除订单
        self.driver.get(ReadConfig().get_order_list())

        locator = (By.LINK_TEXT, u'删除')
        # 等待页面加载完毕
        WebDriverWait(self.driver, 30,
                      0.5).until(EC.element_to_be_clickable(locator))
        # # 读取订单号
        # order_number = self.driver.find_element_by_xpath("//tr[@class='tit-bt']/td[1]/span[1]").text
        # # 多个案件一个订单,只获取到了第一个案件号
        case_name = self.driver.find_element_by_xpath(
            "//tr/td[@class='name name-title']/span[1]").text
        # case_number = self.driver.find_element_by_xpath("//tr/td[@class='name name-title']/span[3]").text
        # case_number = case_number.replace(" ", "")
        # print("order_number", order_number)
        print("case_info", case_name)
        # print("case_info", case_number)
        self.driver.find_element_by_xpath(
            "(.//tr/td[@class='delete-btn']/a)[1]").click()
        # self.driver.find_element_by_link_text(u"删除").click()
        # self.driver.switch_to_alert()
        time.sleep(1)
        # self.driver.find_element_by_link_text(u"确定").click()
        # 必须等一会,才能获取弹框
        sleep(1)
        try:
            # 关闭弹框
            aler = self.driver.switch_to.alert
            delete_staus = aler.text
            print('delete_staus', delete_staus)
            aler.accept()
            time.sleep(1)
            self.driver.refresh()
            # 存储
        except Exception as e:
            print(e)
            self.driver.refresh()  # 刷新页面

        return {
            "goods_order_name": self.goods_name4,
            "goods_order_type": process_type(self.goods_type4),
            "goods_order_price": float(self.goods_price4),
            "goods_order_code": self.goods_code4,
            "goods_offical4": float(self.goods_offical4),
            "goods_order_total_price1": float(self.goods_total_price1),
            "goods_order_total_price2": float(self.goods_total_price2),
            "goods_order_total_price3": float(self.goods_total_price3),
            "goods_QR_price1": float(QR_price1),
            "goods_QR_price2": float(QR_price2),
            "goods_pay_price1": float(goods_pay_price1),
            "goods_pay_for_balance": float(goods_pay_for_balance),
            "goods_pay_price2": float(goods_pay_price2),
            "goods_pay_price3": float(goods_pay_price3),
            "get_usable_balance": float(get_usable_balance),
            "used_balance": float(used_balance),
            "pay_state": pay_state,
            "center_order_number": center_order_number,
            "center_pay_state": center_pay_state,
            "center_goods_name": center_goods_name,
            "center_goods_type": center_goods_type,
            "center_case_code": center_case_code,
            "center_case_price": float(center_case_price),
            "goods_trade_state": goods_trade_state,
            "goods_detail_name2": goods_detail_name2,
            "order_detail_pay_state": order_detail_pay_state,
            "order_detail_total_price": order_detail_total_price,
            "order_detail_red_packet": order_detail_red_packet,
            "order_detail_balance_pay": order_detail_balance_pay,
            "order_detail_should_total": order_detail_should_total,
            "order_detail_should_total_all": order_detail_should_total_all,
            "order_detail_should_total_red": order_detail_should_total_red,
            "order_detail_should_total_balance":
            order_detail_should_total_balance,
            "order_detail_should_total2": order_detail_should_total2,
            "order_detail_receiver": order_detail_receiver,
            "order_detail_receive_address": order_detail_receive_address,
            "order_detail_receive_phone": order_detail_receive_phone
        }
예제 #38
0
    def run(self, configFile, otu, seqIdentityThreshold, minSeqCutoff, bPairsAsSingles, bSingleEnded, bQuiet):
        self.bQuiet = bQuiet

        rc = ReadConfig()
        projectParams, sampleParams = rc.readConfig(configFile, outputDirExists = True)

        ggRefDistFile = self.ggRefDist.replace('##', str(otu))
        neighbours = self.getNeighbours(ggRefDistFile, seqIdentityThreshold)

        # create directory to store putative 16S genes
        dirPutative16S = projectParams['output_dir'] + 'putativeSSU/'
        if not os.path.exists(dirPutative16S):
            os.makedirs(dirPutative16S)
        else:
            rtn = raw_input('Remove previously recovered 16S reads (Y or N)? ')
            if rtn.lower() == 'y' or rtn.lower() == 'yes':
                files = os.listdir(dirPutative16S)
                for f in files:
                    if f.endswith('fasta'):
                        os.remove(dirPutative16S + '/' + f)
            else:
                sys.exit()

        referenceSeqHits = {}
        for sample in sampleParams:
            if not self.bQuiet:
                print ''
                print sample + ':'

            extractedPrefix = projectParams['output_dir'] + 'extracted/' + sample
            classifiedPrefix = projectParams['output_dir'] + 'classified/' + sample
            pairs = sampleParams[sample]['pairs']
            singles = sampleParams[sample]['singles']

            for i in xrange(0, len(pairs), 2):
                pair1Base = ntpath.basename(pairs[i])
                pair2Base = ntpath.basename(pairs[i+1])

                classificationFile1 = classifiedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.intersect.16S.tsv'
                classificationFile2 = classifiedPrefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.intersect.16S.tsv'

                if not self.bQuiet:
                    print '  Processing files: '
                    print '    ' + classificationFile1
                    print '    ' + classificationFile2

                pairFile1 = extractedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.intersect.SSU.fasta'
                pairFile2 = extractedPrefix + '.' + pair2Base[0:pair2Base.rfind('.')] + '.intersect.SSU.fasta'

                self.identifyConsistentPairs(referenceSeqHits, pairFile1, pairFile2, classificationFile1, classificationFile2, neighbours, bPairsAsSingles, bSingleEnded)

                if bSingleEnded:
                    classificationFile = classifiedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.difference.16S.tsv'

                    if not self.bQuiet:
                        print '  Processing file: ' + classificationFile

                    singleFile = extractedPrefix + '.' + pair1Base[0:pair1Base.rfind('.')] + '.difference.SSU.fasta'
                    self.addSingletons(referenceSeqHits, singleFile, classificationFile)

            if bSingleEnded:
                for single in singles:
                    singleBase = ntpath.basename(single)
                    classificationFile = classifiedPrefix + '.' + singleBase[0:singleBase.rfind('.')] + '.16S.tsv'

                    if not self.bQuiet:
                        print '  Processing file: ' + classificationFile

                    singleFile = extractedPrefix + '.' + singleBase[0:singleBase.rfind('.')] + '.SSU.fasta'
                    self.addSingletons(referenceSeqHits, singleFile, classificationFile)

        self.extractRecoverable16S(referenceSeqHits, neighbours, minSeqCutoff, dirPutative16S)
예제 #39
0
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
import os, send_email
from framework import report_template, base_page
from readConfig import ReadConfig
http_dir = ReadConfig().get_linux_dir('http_dir')
# 定义输出的文件位置和名字
#DIR = os.path.dirname(os.path.abspath(__file__))[0:15] #当前文件位置
#DIR = './test_case/' #当前文件位置
#将testrunner放在根目录下时,logger的路径也要改为./当目录层

dir = os.getcwd()  #当前文件位置
now = time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time()))
report_title = '电子发票H5的详细测试报告'
report_description = '用例执行结果:'

report_dir = './test_report/'  #../是返回上级目录 ./表示当前目录层
#report_dir = './test_report/'
filename = now + "-report.html"
report_name = report_dir + filename

summary_name = now + '-summary.html'
summary_path = dir + '/test_report/' + summary_name
summary_html = open(summary_path, 'w', encoding='utf-8')

# discover方法执行测试套件
#testsuite = unittest.defaultTestLoader.discover(start_dir = DIR +'test_case/ ' ,pattern='test*.py',top_level_dir=None)#pattern 是方法的格式,start_dir是待执行用例的目录,


def create_suite():