Best Python code snippet using tempest_python
checks.py
Source:checks.py
...131 'error', 'exception',132 'critical', 'fatal',133 'trace', 'log'134 ]135 def _find_name(self, node):136 """Return the fully qualified name or a Name or Attribute."""137 if isinstance(node, ast.Name):138 return node.id139 elif (isinstance(node, ast.Attribute)140 and isinstance(node.value, (ast.Name, ast.Attribute))):141 method_name = node.attr142 obj_name = self._find_name(node.value)143 if obj_name is None:144 return None145 return obj_name + '.' + method_name146 elif isinstance(node, six.string_types):147 return node148 else: # could be Subscript, Call or many more149 return None150 def visit_Call(self, node):151 """Look for the 'LOG.*' calls."""152 # extract the obj_name and method_name153 if isinstance(node.func, ast.Attribute):154 obj_name = self._find_name(node.func.value)155 if isinstance(node.func.value, ast.Name):156 method_name = node.func.attr157 elif isinstance(node.func.value, ast.Attribute):158 obj_name = self._find_name(node.func.value)159 method_name = node.func.attr160 else: # could be Subscript, Call or many more161 return super(CheckLoggingFormatArgs, self).generic_visit(node)162 # obj must be a logger instance and method must be a log helper163 if (obj_name != 'LOG'164 or method_name not in self.LOG_METHODS):165 return super(CheckLoggingFormatArgs, self).generic_visit(node)166 # the call must have arguments167 if not len(node.args):168 return super(CheckLoggingFormatArgs, self).generic_visit(node)169 # any argument should not be a tuple170 for arg in node.args:171 if isinstance(arg, ast.Tuple):172 self.add_error(arg)173 return super(CheckLoggingFormatArgs, self).generic_visit(node)174class CheckOptRegistrationArgs(BaseASTChecker):175 """Verifying the registration of options are well formed176 This class creates a check for single opt or list/tuple of177 opts when register_opt() or register_opts() are being called.178 """179 name = 'check_opt_registrationg_args'180 version = '1.0'181 CHECK_DESC = ('C311: Arguments being passed to register_opt/register_opts '182 'must be a single option or list/tuple of options '183 'respectively. Options must also end with _opt or _opts '184 'respectively.')185 singular_method = 'register_opt'186 plural_method = 'register_opts'187 register_methods = [188 singular_method,189 plural_method,190 ]191 def _find_name(self, node):192 """Return the fully qualified name or a Name or Attribute."""193 if isinstance(node, ast.Name):194 return node.id195 elif (isinstance(node, ast.Attribute)196 and isinstance(node.value, (ast.Name, ast.Attribute))):197 method_name = node.attr198 obj_name = self._find_name(node.value)199 if obj_name is None:200 return None201 return obj_name + '.' + method_name202 elif isinstance(node, six.string_types):203 return node204 else: # could be Subscript, Call or many more205 return None206 def _is_list_or_tuple(self, obj):207 return isinstance(obj, (ast.List, ast.Tuple))208 def visit_Call(self, node):209 """Look for the register_opt/register_opts calls."""210 # extract the obj_name and method_name211 if isinstance(node.func, ast.Attribute):212 if not isinstance(node.func.value, ast.Name):213 return (super(CheckOptRegistrationArgs,214 self).generic_visit(node))215 method_name = node.func.attr216 # obj must be instance of register_opt() or register_opts()217 if method_name not in self.register_methods:218 return (super(CheckOptRegistrationArgs,219 self).generic_visit(node))220 if len(node.args) > 0:221 argument_name = self._find_name(node.args[0])222 if argument_name:223 if (method_name == self.singular_method and224 not argument_name.lower().endswith('opt')):225 self.add_error(node.args[0])226 elif (method_name == self.plural_method and227 not argument_name.lower().endswith('opts')):228 self.add_error(node.args[0])229 else:230 # This covers instances of register_opt()/register_opts()231 # that are registering the objects directly and not232 # passing in a variable referencing the options being233 # registered.234 if (method_name == self.singular_method and235 self._is_list_or_tuple(node.args[0])):...
get_all_doctors.py
Source:get_all_doctors.py
1#!/usr/bin/env python2import re3import csv4import mechanize5import cookielib6import sys, getopt7from bs4 import BeautifulSoup8from unidecode import unidecode9from cp1252 import cp125210from csv_writer import csv_hitta_vardcentraler11reload(sys) 12sys.setdefaultencoding('utf8')13directory = ""14class get_all_doctors(object):15 """class: get_all_doctors"""16 def _init_mech (self):17 """def: _init_mech"""18 mech = mechanize.Browser()19 cj = cookielib.LWPCookieJar()20 mech.set_cookiejar(cj)21 mech.set_handle_equiv(True)22 mech.set_handle_gzip(False)23 mech.set_handle_redirect(True)24 mech.set_handle_referer(True)25 mech.set_handle_robots(False)26 # Follows refresh 0 but not hangs on refresh > 027 mech.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)28 mech.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] 29 return mech30 31 def __init__(self):32 self.doctor_match_result_csvfh = open(directory + '/found_doctors_result.csv', "rb")33 self.doctor_match_result_heading = [34 'URL',35 'SEARCH_NAME',36 'FOUND_NAME',37 'ADDRESS',38 'ZIP',39 'CITY',40 'PHONE',41 'WEBSITE',42 "NAME_MATCH?",43 "ADDRESS_MATCH?",44 "ZIP_MATCH?",45 "CITY_MATCH?",46 "PHONE_MATCH?",47 "VARDCENTRAL",48 'HITTA_OR_ENIRO',49 'COLOR',50 'FOUND_DOCTOR_TAG',51 'FOUND_DOCTORS',52 'FOUND_DOCTORS_URL',53 'MISSING_DOCTORS',54 ]55 self.doctor_match_result_reader = csv.DictReader(self.doctor_match_result_csvfh, fieldnames=self.doctor_match_result_heading, delimiter=";", quotechar='"')56 self.doctor_match_result_reader.next()57 self.doctor_match_result_reader.next()58 self.mech = self._init_mech()59 def _find_name (self, tag):60 """def: _find_name"""61 if tag.string == None: return 062 63 # string = tag.string.encode('cp1252')64 string = tag.string65 name_fields = re.split(r'[, ]+', string)66 if name_fields and len(name_fields) > 1:67 match = 168 for name_field in name_fields:69 name_field_d = unidecode(name_field)70 if not re.search('^[A-Z][a-z]+$', name_field_d):71 match = 072 if match == 1:73 if self.doctor_tag and not re.search('^\s*$', self.doctor_tag):74 if self.doctor_tag != tag.name:75 match = 076 return match77 return 078 79 def get_all_names (self, home_url):80 """def: get_all_names"""81 print "Open: " + home_url82 self.mech.open(home_url)83 #print self.mech.response().read()84 soup = BeautifulSoup(self.mech.response().read(), "html.parser")85 names = soup.find_all(self._find_name)86 names = [name.string for name in names]87 names = list(set(names))88 return names89 90 91 def parse (self):92 """def: parse"""93 for row_h in self.doctor_match_result_reader:94 if not row_h ['FOUND_DOCTORS_URL']: 95 csv_hitta_vardcentraler.write_row_h(row_h)96 continue97 if row_h ['FOUND_DOCTORS_URL'] == "":98 csv_hitta_vardcentraler.write_row_h(row_h)99 continue 100 home_urls = row_h ['FOUND_DOCTORS_URL']101 self.doctor_tag = row_h ['FOUND_DOCTOR_TAG']102 all_names = []103 for home_url in row_h['FOUND_DOCTORS_URL'].split("|"):104 names = self.get_all_names (home_url)105 all_names = all_names + names106 all_names_str = '|'.join(all_names)107 row_h["FOUND_ALL_NAMES"] = cp1252(all_names_str)108 csv_hitta_vardcentraler.write_row_h(row_h)109 110 111if __name__ == "__main__":112 def main(argv): 113 grammar = "kant.xml"114 try: 115 opts, args = getopt.getopt(argv, "d:", ["dir="])116 except getopt.GetoptError:117 Usage()118 if len(opts) == 0:119 Usage()120 return opts121 122 def Usage ():123 print "Usage: python scrape.py -d <Directory>"124 print " Where: <Directory> is the path of the directory where Vardcentraler.csv and other csv files are kept"125 sys.exit(2)126 opts = main(sys.argv[1:])127 directory = opts[0][1]128 heading_all_doctors_names_result=[129 'URL',130 'SEARCH_NAME',131 'FOUND_NAME',132 'ADDRESS',133 'ZIP',134 'CITY',135 'PHONE',136 'WEBSITE',137 'NAME_MATCH?',138 'ADDRESS_MATCH?',139 'ZIP_MATCH?',140 'CITY_MATCH?',141 'PHONE_MATCH?',142 'VARDCENTRAL',143 'HITTA_OR_ENIRO',144 'COLOR',145 'FOUND_DOCTOR_TAG',146 'FOUND_DOCTORS',147 'FOUND_DOCTORS_URL',148 'MISSING_DOCTORS',149 'FOUND_ALL_NAMES',150 ]151 m_csv_hitta_vardcentraler = csv_hitta_vardcentraler(fname= directory + '/get_all_doctors_names_result.csv', heading=heading_all_doctors_names_result)152 m_get_all_doctors = get_all_doctors()...
tools.py
Source:tools.py
...7]8_isref = lambda spec: isinstance(spec, front.TypeIdent) and spec.isref()9_ref = lambda spec: "ref" if _isref(spec) else ""10@strictly11def _find_name(spec: _TypeSpec) -> str:12 if isinstance(spec, (front.UserType, front.levir_builtins.BuiltinType)):13 return spec.name14 elif isinstance(spec, front.TypeIdent):15 return spec.type.name16@strictly17def Type_(spec: _TypeSpec) -> str:18 if _isref(spec):19 return f"ref_{_find_name(spec)}"20 else:21 return f"type_{_find_name(spec)}"22# this allows for the posibility of having catables locals/members later23# however this may not be compatible with inference24for prefix in ("mbr", "var"):25 exec(26 f"""if True:27 @strictly28 def {prefix}_(name:str, type:_TypeSpec) -> str:29 return "{prefix}"+"_"+name30 """31 )32for prefix in ("get", "drop", "dflt", "rel", "rtn", "cntnptr"):33 exec(34 f"""if True:35 @strictly36 def {prefix}_(spec:_TypeSpec) -> str:37 return "{prefix}"+_ref(spec)+"_"+_find_name(spec)38 """39 )40@strictly41def new_(spec: _TypeSpec) -> str:42 if _isref(spec):43 FUCK44 return "new_" + _find_name(spec)45@strictly46def content_(spec: _TypeSpec) -> str:...
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!!