How to use _raw method in pytest-benchmark

Best Python code snippet using pytest-benchmark

escpos.py

Source:escpos.py Github

copy

Full Screen

...32 if (self.device == INVALID_HANDLE_VALUE):33 # windll.user32.MessageBoxW(0, u'未找到打印机,请等待 Windows 识别设备完成', u'提示', 0)34 raise NoUSBPrinterError()3536 def _raw(self, msg):37 """ Print any of the commands above, or clear text """38 if type(msg) == unicode:39 msg = msg.encode('gbk')40 cmd = c_char_p(msg)41 size = wintypes.DWORD(len(msg))42 tmp = byref(wintypes.DWORD())43 self.WriteUsb(self.device, cmd, size, tmp)4445 def barcode(self, code, type, width=64, height=4, pos='BLW', font='A'):46 """ Print Barcode """47 # Align Bar Code()48 self._raw(TXT_ALIGN_CT)49 # Height50 if height >= 2 or height <= 6:51 self._raw(BARCODE_HEIGHT)52 else:53 raise BarcodeSizeError()54 # Width55 if width >= 1 or width <= 255:56 self._raw(BARCODE_WIDTH)57 else:58 raise BarcodeSizeError()59 # Font60 if font.upper() == "B":61 self._raw(BARCODE_FONT_B)62 else: # DEFAULT FONT: A63 self._raw(BARCODE_FONT_A)64 # Position65 if pos.upper() == "OFF":66 self._raw(BARCODE_TXT_OFF)67 elif pos.upper() == "BOTH":68 self._raw(BARCODE_TXT_BTH)69 elif pos.upper() == "ABOVE":70 self._raw(BARCODE_TXT_ABV)71 else: # DEFAULT POSITION: BELOW72 self._raw(BARCODE_TXT_BLW)73 # Type74 if type.upper() == "UPC-A":75 self._raw(BARCODE_UPC_A)76 elif type.upper() == "UPC-E":77 self._raw(BARCODE_UPC_E)78 elif type.upper() == "EAN13":79 self._raw(BARCODE_EAN13)80 elif type.upper() == "EAN8":81 self._raw(BARCODE_EAN8)82 elif type.upper() == "CODE39":83 self._raw(BARCODE_CODE39)84 elif type.upper() == "ITF":85 self._raw(BARCODE_ITF)86 elif type.upper() == "NW7":87 self._raw(BARCODE_NW7)88 elif type.upper() == "CODE128":89 self._raw(BARCODE_CODE128)90 code = self._code128(code)91 else:92 raise BarcodeTypeError()93 # Print Code94 if code:95 self._raw(code)96 else:97 raise BarcodeCodeError()9899 def _code128(self, msg):100 # 长度 2-16101 size = len(msg)102 if (size < 2 or size > 16 or (size % 2) != 0):103 return False104 # 纯数字 双数105 m = ''106 i = 1107 code = BARCODE_CODE128_C108 for d in msg:109 if i == 1:110 m = d111 i = 2112 continue113 if i == 2:114 i = 1115 code = code + chr(int(m + d))116 return chr(len(code)) + code117 pass118119 def text(self, txt):120 """ Print alpha-numeric text """121 if txt:122 self._raw(txt)123 else:124 raise TextError()125126 def set(self, align='left', font='a', type='normal', width=1, height=1):127 """ Set text properties """128 # Align129 if align.upper() == "CENTER":130 self._raw(TXT_ALIGN_CT)131 elif align.upper() == "RIGHT":132 self._raw(TXT_ALIGN_RT)133 elif align.upper() == "LEFT":134 self._raw(TXT_ALIGN_LT)135 # Font136 if font.upper() == "B":137 self._raw(TXT_FONT_B)138 else: # DEFAULT FONT: A139 self._raw(TXT_FONT_A)140 # Type141 if type.upper() == "B":142 self._raw(TXT_BOLD_ON)143 self._raw(TXT_UNDERL_OFF)144 elif type.upper() == "U":145 self._raw(TXT_BOLD_OFF)146 self._raw(TXT_UNDERL_ON)147 elif type.upper() == "U2":148 self._raw(TXT_BOLD_OFF)149 self._raw(TXT_UNDERL2_ON)150 elif type.upper() == "BU":151 self._raw(TXT_BOLD_ON)152 self._raw(TXT_UNDERL_ON)153 elif type.upper() == "BU2":154 self._raw(TXT_BOLD_ON)155 self._raw(TXT_UNDERL2_ON)156 elif type.upper == "NORMAL":157 self._raw(TXT_BOLD_OFF)158 self._raw(TXT_UNDERL_OFF)159 # Width160 if width == 2 and height != 2:161 self._raw(TXT_NORMAL)162 self._raw(TXT_2WIDTH)163 elif height == 2 and width != 2:164 self._raw(TXT_NORMAL)165 self._raw(TXT_2HEIGHT)166 elif height == 2 and width == 2:167 self._raw(TXT_2WIDTH)168 self._raw(TXT_2HEIGHT)169 else: # DEFAULT SIZE: NORMAL170 self._raw(TXT_NORMAL)171172 def cut(self, mode=''):173 """ Cut paper """174 # Fix the size between last line and cut175 # TODO: handle this with a line feed176 self._raw("\n\n\n\n\n\n")177 if mode.upper() == "PART":178 self._raw(PAPER_PART_CUT)179 else: # DEFAULT MODE: FULL CUT180 self._raw(PAPER_FULL_CUT)181182 def cashdraw(self, pin):183 """ Send pulse to kick the cash drawer """184 if pin == 2:185 self._raw(CD_KICK_2)186 elif pin == 5:187 self._raw(CD_KICK_5)188 else:189 raise CashDrawerError()190191 def hw(self, hw):192 """ Hardware operations """193 if hw.upper() == "INIT":194 self._raw(HW_INIT)195 self._raw(TXT_ZH_CN)196 elif hw.upper() == "SELECT":197 self._raw(HW_SELECT)198 elif hw.upper() == "RESET":199 self._raw(HW_RESET)200 else: # DEFAULT: DOES NOTHING201 pass202203 def control(self, ctl):204 """ Feed control sequences """205 if ctl.upper() == "LF":206 self._raw(CTL_LF)207 elif ctl.upper() == "FF":208 self._raw(CTL_FF)209 elif ctl.upper() == "CR":210 self._raw(CTL_CR)211 elif ctl.upper() == "HT":212 self._raw(CTL_HT)213 elif ctl.upper() == "VT":214 self._raw(CTL_VT)215216 def close(self):217 # 关闭218 self.CloseUsb(self.device)219 # windll.user32.MessageBoxW(0, u'开始打印,请等待打印完成', u'提示', 0)220221222# Errors223224class Error(Exception):225 """ Base class for ESC/POS errors """226227 def __init__(self, msg, status=None):228 Exception.__init__(self) ...

Full Screen

Full Screen

behavior.py

Source:behavior.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from entity.entity import *3class BaseBehavior(object):4 CONTEXT = []5 def __init__(self, _raw):6 self.attck_ids = ''7 self.date = None8 self.relation = ''9 def getname(self):10 return self.__class__.__name__11 def get_value(self):12 pass13 def get_attribute_names(self):14 attrs = ['timestamp', 'relation', 'attckids', 'behaviortype', 'value']15 for _attr in self.__class__.CONTEXT:16 attrs.extend([_attr + '.' + prop for prop in self.__dict__[_attr].__class__.PROPS])17 return attrs18 def serialize(self):19 serobj = {'timestamp': self.date, 'relation': self.relation, 'attckids': self.attck_ids,20 'behaviortype': self.getname(), 'value': self.get_value()}21 for _attr in self.__class__.CONTEXT:22 _obj = self.__dict__[_attr]23 serobj.update({_attr + '.' + prop: _obj[prop] for prop in _obj.__class__.PROPS})24 return serobj25 @staticmethod26 def deserialize(_raw):27 mappings = {28 'ProcessBehavior': ProcessBehavior,29 'NetworkBehavior': NetworkBehavior,30 'FileBehavior': FileBehavior,31 'RegistryBehavior': RegistryBehavior,32 }33 behav_data = {}34 behav_data['datetime'] = _raw['timestamp']35 behav_data['relation'] = _raw['relation']36 cols = list(_raw.keys())37 for col in cols:38 if '.' in col:39 if col.split('.')[0] not in behav_data.keys():40 behav_data[col.split('.')[0]] = {}41 behav_data[col.split('.')[0]][col.split('.')[1]] = _raw[col]42 _instance = mappings[_raw['behaviortype']](behav_data)43 _instance.attck_ids = _raw['attckids']44 return _instance45class ProcessBehavior(BaseBehavior):46 CONTEXT = ['parent', 'current', 'file', 'endpoint']47 def __init__(self, _raw):48 super(ProcessBehavior, self).__init__(_raw)49 self.parent = ProcessEntity(_raw['parent'])50 self.current = ProcessEntity(_raw['current'])51 self.file = FileEntity(_raw['file'])52 self.date = _raw['datetime']53 self.endpoint = EndPointEntity(_raw['endpoint'])54 self.relation = _raw['relation']55 def __str__(self):56 return '{} Endpoint({}) on {}: ({} {}) -{}-> ({} {})'.format(self.__class__.__name__, self.endpoint['uuid'],57 self.date, self.parent['image'],58 self.parent['cmdline'], self.relation,59 self.current['image'], self.current['cmdline'])60 def get_value(self):61 return '({} {}) -{}-> ({} {})'.format(self.parent['image'], self.parent['cmdline'], self.relation,62 self.current['image'], self.current['cmdline'])63class NetworkBehavior(BaseBehavior):64 CONTEXT = ['process', 'network', 'file', 'endpoint']65 def __init__(self, _raw):66 super(NetworkBehavior, self).__init__(_raw)67 self.process = ProcessEntity(_raw['process'])68 self.network = NetworkEntity(_raw['network'])69 self.file = FileEntity(_raw['file'])70 self.date = _raw['datetime']71 self.endpoint = EndPointEntity(_raw['endpoint'])72 self.relation = _raw['relation']73 def __str__(self):74 return '{} Endpoint({}) on {}: {} -{}-> {}({})'.format(self.__class__.__name__, self.endpoint['uuid'],75 self.date, self.process['image'], self.relation,76 self.network['rhost'], self.network['rip'])77 def get_value(self):78 return '{} -{}-> {}({})'.format(self.process['image'], self.relation, self.network['rhost'],79 self.network['rip'])80class FileBehavior(BaseBehavior):81 CONTEXT = ['process', 'file', 'endpoint']82 def __init__(self, _raw):83 super(FileBehavior, self).__init__(_raw)84 self.process = ProcessEntity(_raw['process'])85 self.file = FileEntity(_raw['file'])86 self.date = _raw['datetime']87 self.endpoint = EndPointEntity(_raw['endpoint'])88 self.relation = _raw['relation']89 def __str__(self):90 return '{} Endpoint({}) on {}: {} -{}-> {}'.format(self.__class__.__name__, self.endpoint['uuid'], self.date,91 self.process['image'], self.relation, self.file['path'])92 def get_value(self):93 return '{} -{}-> {}'.format(self.process['image'], self.relation, self.file['path'])94class RegistryBehavior(BaseBehavior):95 CONTEXT = ['process', 'reg', 'file', 'endpoint']96 def __init__(self, _raw):97 super(RegistryBehavior, self).__init__(_raw)98 self.process = ProcessEntity(_raw['process'])99 self.reg = RegistryEntity(_raw['reg'])100 self.file = FileEntity(_raw['file'])101 self.date = _raw['datetime']102 self.endpoint = EndPointEntity(_raw['endpoint'])103 self.relation = _raw['relation']104 def __str__(self):105 return '{} Endpoint({}) on {}: {} -{}-> {} {} {}'.format(self.__class__.__name__, self.endpoint['uuid'],106 self.date, self.process['image'], self.relation,107 self.reg['path'], self.reg['key'], self.reg['value'])108 def get_value(self):109 return '{} -{}-> {} {} {}'.format(self.process['image'], self.relation, self.reg['path'], self.reg['key'],110 self.reg['value'])111BEHAVIOR_SETS = [112 ProcessBehavior,113 NetworkBehavior,114 FileBehavior,115 RegistryBehavior,...

Full Screen

Full Screen

account.py

Source:account.py Github

copy

Full Screen

1import os2import csv3from common.logger import logger4from common.config import config5from common.utils import utils6class Account:7 @logger.catch8 def __init__(self, csv_file="../config/account.csv"):9 example = os.path.abspath("../config/account_example.csv")10 os.chdir(os.path.dirname(__file__))11 self._path = os.path.abspath(csv_file)12 if not os.path.exists(self._path):13 logger.error(f"No such file [{self._path}]")14 if os.path.exists(example):15 logger.error(f"Please rename [{example}] to [{self._path}]")16 raise FileNotFoundError(f"No such file [{self._path}]")17 self._csv_file = None18 self._raw = []19 self._read_csv()20 @logger.catch21 def _read_csv(self):22 del_rows = []23 self._csv_file = csv.reader(open(self._path, encoding='utf-8-sig'))24 for i, row in enumerate(self._csv_file):25 if row == [] or "#" in row[0]:26 del_rows.append(i + 1)27 else:28 self._raw.append(row)29 logger.debug(f"Del line(s): {del_rows}.")30 self._raw = self._raw[1:]31 logger.debug(f"Loaded [{self._path}]")32 logger.debug(f"Total {len(self._raw)} account(s) in [{self._path}]")33 @logger.catch34 def refresh(self):35 self._raw.clear()36 self._read_csv()37 logger.debug(f"Refreshed [{self._path}]")38 def ID(self, i):39 return self._raw[i][0]40 def sail_date(self, i):41 return self._raw[i][1]42 def wechat_push(self, i):43 return self._raw[i][2]44 def email_push(self, i):45 return self._raw[i][3]46 def sendkey(self, i):47 return self._raw[i][4]48 def userid(self, i):49 return self._raw[i][5]50 def email(self, i):51 return self._raw[i][6]52 @property53 def row(self):54 return len(self._raw)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-benchmark automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful