def send_message(cls, webhook, msg): logger('jira').info("msg: %s", msg) header = {'Content-type': 'application/json'} resp = requests.post(url=webhook, data=json.dumps(msg), headers=header) logger('jira').info("resp: %s", resp.json()) return resp
def get_response_content(method, url, data, headers, is_header): """ 自定义检查接口的返回结果 :param method: 请求方法 :param url: 接口地址 :param data: 请求参数 :param headers: headers :param is_header: 是否有header :return: content -- 自定义检查的返回结果 """ content = [] try: if method == 'POST' or method == 'post': if is_header == 'YES' or is_header == 'yes': res = requests.post(url, data, headers=headers) else: res = requests.post(url, json.loads(data)) code = res.json().get('code') # 获取code值 msg = res.json().get('msg') # 获取msg值 result = res.json().get('result') # 获取result值 content.append(code) content.append(msg) content.append(result) else: res = requests.get(url, data) code = res.json().get('code') msg = res.json().get('msg') result = res.json().get('result') content.append(code) content.append(msg) content.append(result) return content except Exception as e: logger().error('请求失败:{}'.format(e))
def test_api(method, url, data, headers, is_header): """ 自定义的接口测试方法 :param method: 请求方法 :param url: 接口地址 :param data: 请求参数 :param headers: headers :param is_header: 是否有header :return: result -- 接口返回的结果 """ """ 1、判断接口请求方式、选择对应的请求 2、判断是否有header,选择对应请求 """ try: if method == 'POST' or method == 'post': # post请求 if is_header == 'YES' or is_header == 'yes': # 有header res = requests.post(url, data, headers=headers) else: # 无header res = requests.post(url, json.loads(data)) result = res.json() else: # get请求 res = requests.get(url, data) result = res.json() return result except Exception as e: logger().error('请求时失败:{}'.format(e))
def transform_data(cls, data): try: data = _pre_process_data(data) title, text = _assemble_message(data) return _pack_response(title=title, text=text) except AttributeError as e: logger('jira').info('Invalid data format: data={data}\n exception={exc}\n trace={trace}'.\ format(data=data, exc=e, trace=traceback.format_exc())) return {} except Exception as e: logger('jira').info('Incredible Exception: data={data}\n exception={exc}\n trace={trace}'.\ format(data=data, exc=e, trace=traceback.format_exc())) return {}
def webhook(site): access_token = request.args.get('access_token') data = request.get_json() logger().info('\n[{begin}\naccess_token:{token}\n{data}\n{end}]\n'.format(begin=site, token=access_token, data=formating(data), end=site)) webhook = get_webhook(site, access_token) if not webhook: return jsonify(ok=False, error='Invalid webhook') with SiteLocator.get_factory(site) as client_cls: msg = client_cls.transform_data(data) resp = client_cls.send_message(webhook, msg) logger().info("resp: %s", resp) return jsonify(ok=True)
def setUp(self): self.driver = browsersManager("Chrome") self.driver.maximize_window() self.driver.get("http://www.baidu.com") self.driver.implicitly_wait(10) self.logger = logger("path", consoleLevel=logging.INFO, logFile="logger.txt", fileLevel=logging.DEBUG) self.logger.info("浏览器启动ing")
def write_to_excel(path, sheetName, row, col, string): """ 1、向Excel中写入内容 2、openpyxl操作Excel时,索引是与Excel本身的序号对应,而不是从0开始,而是从1开始 3、在执行写入操作时,Excel文件必须是关闭的,否则报错 :param path: Excel路径 :param sheetName: sheetName :param row: 行 :param col: 列 :param string: 写入单元格的内容 :return: """ try: workbook = openpyxl.load_workbook(path) sheet = workbook[sheetName] sheet.cell(row=row, column=col).value = string workbook.save(path) # logger().info('操作成功') except Exception as e: logger().info('操作失败:{}'.format(e))
def run_case(self, sheet): """ 读取Excel中的测试用例,并执行测 :param sheet: sheet :return: result -- 接口返回的结果 """ row = excel.get_row(sheet) # 获取Excel测试用例的行 for i in range(1, row): # 通过for循环的方式,遍历取出Excel所有的用例 id = int(excel.get_cell_content(sheet, i, conf.CASE_ID - 1)) host = conf.host url = excel.get_cell_content(sheet, i, conf.CASE_URL - 1) data = excel.get_cell_content(sheet, i, conf.CASE_DATA - 1) method = excel.get_cell_content(sheet, i, conf.CASE_METHOD - 1) header = conf.headers is_header = excel.get_cell_content(sheet, i, conf.CASE_HEADER - 1) # testTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) StartTime = datetime.datetime.now() logger().info('Start Time is: {}'.format(StartTime)) result = res.test_api(method, host + url, data, header, is_header) # 执行请求,返回的结果是json格式 actual_msg = result.get('msg') # 接口实际返回的 msg # Excel中的msg;此方法是用xlrd操作Excel,所以索引要用实际值-1 expect_msg = excel.get_cell_content( sheet, i, conf.CASE_CHECK_POINT - 1) # 期望结果 if expect_msg == actual_msg: # 检查通过,将结果写入Excel w.write_to_excel(conf.FILE_PATH, conf.SHEET_NAME, i + 1, conf.CASE_TEST_RESULT, conf.PASS) # 将返回的结果转换成str写入Excel w.write_to_excel(conf.FILE_PATH, conf.SHEET_NAME, i + 1, conf.CASE_RESPONSE, str(result)) w.write_to_excel(conf.FILE_PATH, conf.SHEET_NAME, i + 1, conf.CASE_TEST_TIME, StartTime) logger().info('第{}条用例测试成功'.format(id)) logger().info(result) logger().info( '--------------------------------------------------------------------------' '-----------------------------------------') else: # 检查不通过,将结果写入Excel w.write_to_excel(conf.FILE_PATH, conf.SHEET_NAME, i + 1, conf.CASE_TEST_RESULT, conf.FAIL) w.write_to_excel(conf.FILE_PATH, conf.SHEET_NAME, i + 1, conf.CASE_TEST_TIME, StartTime) logger().info('请求失败') logger().info('第{}条用例测试失败'.format(id))
#!/usr/bin/env python import os import pytest import datetime import api.child from common.log import logger import db.schema as schema from common.config import core_config log = logger("test") class TestChild: def setup_class(self): base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config_file = os.path.join(base_path, 'conf', 'klp.ini') cfg = core_config(config_file) self.meta, self.session, self.engine = schema.init_model(cfg['dburi']) @pytest.mark.parametrize(('name', 'dob', 'sex'), [ ('child 0', datetime.date(2012, 3, 13), 'male'), ('child 1', datetime.date(2013, 3, 13), 'female'), ('child 2', datetime.date(1979, 3, 13), 'tg') ]) def test_create_child(self, name, dob, sex): """ Create a child """ cid = api.child.create(self.session, name, dob, sex) assert cid, "Child not created"
# -*- coding: utf-8 -*- # 基于指数移动平均线的策略 import numpy as np import talib import matplotlib.pyplot as plt from common import log from src.model import norm from trader.strategy import obj log = log.logger("strategy_ema") # # 长期平均和短期平均 # def long_short(data_close, predict_emas, predict_ema, long_range=30, short_range=15): # output = "calm" # # data_EMAs = talib.EMA(np.array(data_close), timeperiod=15) # # data_EMA = talib.EMA(np.array(data_close), timeperiod=30) # # data_WILLR = talib.WILLR(np.array(data_high), np.array(data_low), np.array(data_close), timeperiod=14)
# -*- coding:utf-8 -*- from common.log import logger from function.func import ApiTest import common.excel as excel import config as conf logger().info('♣♣☆☆☆☆☆☆♣♣♣☆☆☆☆☆☆☆☆☆♣ 开始测试 ♣☆☆☆☆☆☆☆☆♣♣♣☆☆☆☆☆☆☆☆☆') """打开Excel""" workbook = excel.open_excel(conf.FILE_PATH) sheet = excel.get_sheet('Case') """执行测试用例""" res = ApiTest().run_case(sheet) logger().info(res) logger().info('♣♣☆☆☆☆☆☆♣♣♣☆☆☆☆☆☆☆☆☆♣ 测试结束 ♣☆☆☆☆☆☆☆☆♣♣♣☆☆☆☆☆☆☆☆☆')
import pytest import allure import json import re from common.tools import compose_url, isdictcontains, simple_request, get_response from common.xlsx import XLSX from common.log import logger logger = logger("AutoTest") xlsx = XLSX() attach_1 = "请求信息" attach_2 = "期望与结果" @allure.feature("接口/api/serverFuzzy") class TestC19878: datas = xlsx.get_data_by_case_id(19878) ids = [x.get("ids") for x in datas] @allure.testcase( "https://zentao.eoitek.net/index.php?m=testcase&f=view&caseID=19878&version=1" ) @pytest.mark.parametrize("data", datas, ids=ids) def test_server_fuzzy(self, data): response = get_response(data) expect = json.loads(data.get("expect")) allure.attach( body= "Expect type is: {}, content is:\n{}\nActual type is: {}, content is:\n{}" .format(type(expect), expect, type(response.json()),
import os import sys from pprint import pformat from pyramid.config import Configurator from pyramid.security import authenticated_userid import pyramid.httpexceptions from pyramid_beaker import set_cache_regions_from_settings from beaker import cache as bcache from pyramid_whoauth.auth import WhoAuthenticationPolicy import db.schema as schema from common.log import logger log = logger("rest") default_config_file = os.path.join(epsilon_base, 'conf', 'epsilon.ini') default_key_file = os.path.join(epsilon_base, 'conf', 'keyfile') conf_dir_path = os.path.join(epsilon_base, 'conf') epsilon_version = get_epsilon_version() def load_epsilon_env(settings={}): """Load up and init the epsilon specific stuff""" epsilon_config_file = settings.get('epsilon_config', default_config_file) epsilon_key_file = settings.get('epsilon_key', default_key_file) print "epsilon:", epsilon_config_file if not os.path.exists(epsilon_config_file): print >> sys.stderr, "Could not find epsilon config file %s" % epsilon_config_file
result = res.json().get('result') # 获取result值 content.append(code) content.append(msg) content.append(result) else: res = requests.get(url, data) code = res.json().get('code') msg = res.json().get('msg') result = res.json().get('result') content.append(code) content.append(msg) content.append(result) return content except Exception as e: logger().error('请求失败:{}'.format(e)) """测试类""" if __name__ == '__main__': url = conf.url method = conf.method data = conf.data logger().info(type(data)) headers = conf.headers is_header = conf.is_header res = test_api(method, url, json.dumps(data), headers, is_header) # content = get_response_content(method, url, json.dumps(data), headers, is_header) logger().info(res) logger().info(res.get('msg')) # logger().info(content)
from common.log import logger logger = logger("MyError") class MyError(Exception): def __init__(self, message): self.message = message logger.error(self.message) def __str__(self): return repr(self.message) class ConfKeyNotFound(MyError): def __init__(self, message): MyError.__init__(self, message) class FormatError(MyError): def __init__(self, message): MyError.__init__(self, message) class MethodError(MyError): def __init__(self, message): MyError.__init__(self, message) class CompareResultError(MyError): def __init__(self, message):
# -*- coding: utf-8 -*- import datetime from sqlalchemy.orm.exc import NoResultFound import db.schema as schema from common.log import logger from .exceptions import NoSuchChild log = logger("api:child") def create(s, name, dob, sex): """ Create a new child. Returns id of the newly created child. """ child = schema.Child(name, dob, sex) s.add(child) s.flush() log.debug("Created %s" % child) return child.id def delete(s, id): """ Delete a child, by id. """ try: child = s.query(schema.Child).get(id) child.deleted = True s.merge(child) s.flush()
import pymysql import sys from common.parseyaml import ParseYaml from common.error import ConfKeyError from common.log import logger logger = logger() class MySql: """ 这个类是为了操作数据库 " 读取数据使用get_data_by_id(id) > TUPLE(CONTENT OF ID) " 写入数据使用write_to_mysql(1, {"gender":"5"}) > NONE 将会更新id为1的行中,gender的字段为5。需要确保数据库有gender字段 """ def __init__(self): conf_obj = ParseYaml() try: conf = conf_obj.get_conf("mysql") self.host = conf["host"] self.port = conf["port"] self.user = conf["user"] self.password = conf["password"] self.database = conf["database"] self.table = conf["table"] except KeyError as e: raise ConfKeyError(e) def connect(self):
# coding: utf-8 import json from common.log import logger import traceback import requests lg = logger('jenkins') webhook = 'https://oapi.dingtalk.com/robot/send?access_token=49679eab1c1d2c16af000de2f61e2803a9071cb38b92e16b05c8ba18f007ccaa' class Jenkins: @classmethod def transform_data(cls, data): try: repo = data.get('display_name') url = data.get('build').get('full_url') phase = data.get('build').get('phase') status = data.get('build').get('status', '') title, text = _pack_msg(repo, url, phase, status) return _pack_response(title, text) except Exception as e: lg.info( 'Incredible Exception: data={data}\n exception={exc}\n trace={trace}' .format(data=data, exc=e, trace=traceback.format_exc())) return {} @classmethod def send_message(cls, webhook, msg):