Best Python code snippet using stestr_python
log.py
Source:log.py
...97 if isinstance(record.msg, dict):98 for key in record.msg:99 if isinstance(record.msg[key], Exception):100 record.msg[key] = self._get_trace(record, False)101 self._add_dict(data, record.msg)102 elif isinstance(record.msg, str):103 try:104 self._add_dict(data, json.loads(str(record.msg)))105 except ValueError:106 message = record.getMessage()107 if record.exc_text:108 message += '\n' + record.exc_text109 self._add_dict(data, {'message': message})110 elif isinstance(record.msg, Exception):111 trace = self._get_trace(record)112 self._add_dict(data, {'message': trace})113 else:114 self._add_dict(data, {'message': record.msg})115 def _get_trace(self, record, need_format=True):116 s = ''117 if need_format:118 if hasattr(self, 'formatMessage'):119 s = self.formatMessage(record)120 else:121 s = self._fmt % record.__dict__122 if record.exc_text:123 if s[-1:] != "\n":124 s = s + "\n"125 s = s + record.exc_text126 if hasattr(record, 'stack_info') and record.stack_info:127 if s[-1:] != "\n":128 s = s + "\n"129 s = s + self.formatStack(record.stack_info)130 return s131 @staticmethod132 def _add_dict(data, update):133 for key, value in update.items():134 if not isinstance(key, str):135 key = str(key)136 if not isinstance(value, str):137 value = str(value)138 data[key] = value139class JsonToStdErrHandler(logging.Handler):140 def __init__(self, tag: str):141 self.tag = tag142 super().__init__()143 def emit(self, record):144 data = self.format(record)145 data['tag'] = self.tag146 sys.stderr.write(json.dumps(data) + '\n')...
login.py
Source:login.py
...9 self._user = user10 self._host = host11 self.headers = headers12 # url for website we want to log in to13 self._add_dict(host)14 # create cookie file15 self.cookie_file = DEFAULT_COOKIE_FILE16 # user provided username and password17 self._add_dict(user)18 self.form_params = params19 self._create_user_data()20 # override defaults21 self._add_dict(kw)22 # set up a cookie jar to store cookies23 self._create_cookie_jar()24 # create the opener objects25 self._create_openers()26 # add the headers to mimic a web-browser27 self._add_headers()28 def _create_openers(self):29 """30 """31 self.opener = urllib2.build_opener(32 urllib2.HTTPRedirectHandler(),33 urllib2.HTTPHandler(debuglevel=0),34 urllib2.HTTPSHandler(debuglevel=0),35 urllib2.HTTPCookieProcessor(self.cj)36 )37 def _add_headers(self):38 """39 """40 self.opener.addheaders = self.headers41 def _create_intital_cookie(self):42 """43 """44 response = self.opener.open(self.base_url)45 self.cj.save()46 response = self.login()47 self.login_response = response48 def _add_dict(self, dict):49 """50 """51 for key, val in dict.items():52 setattr(self, key, val)53 def _create_user_data(self):54 """55 """56 data = {}57 for name, element_name in self.form_params.items():58 # collect the params as elementID == user value (like name or password)59 data[element_name] = getattr(self, name)60 # make sure all elements are from user add, such as remember_me.61 for user_key, user_val in self._user.items():62 if data.has_key(user_key): continue...
tokenizer.py
Source:tokenizer.py
2import config3class Tokenizer:4 def __init__(self):5 self._stopwords = self._read_stopwords()6 self._add_dict()7 self.docid_dict = None8 @staticmethod9 def _read_stopwords():10 """Fetch stopwords predefined in file."""11 s = set([line.rstrip() for line in open(config.BASE_DIR + "/indexer/stopwords.txt", 'r', encoding="utf-8")])12 # rstrip() reduces all the ending '\n' for each line13 s.remove('')14 s.add('\n')15 s.add(' ')16 s.add('\u3000')17 return s18 @staticmethod19 def _add_dict():20 print()21 jieba.add_word(u'K线') # financial dictionary can be added later like this.22 print()23 def cut(self, text):24 """Return a list of words appearing in text."""25 tokens = jieba.cut_for_search(text)26 result = list()27 try:28 for tk in tokens:29 if tk not in self._stopwords:30 result.append(tk.lower())31 except Exception as e:32 print(e)33 return result
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!