Best Python code snippet using autotest_python
register.py
Source:register.py
...17 for key, value in valueDict.items():18 win32api.RegSetValueEx(hkey, key, None, win32con.REG_SZ, value)19 finally:20 win32api.RegCloseKey(hkey)21def _set_string(path, value, base=win32con.HKEY_CLASSES_ROOT):22 "Set a string value in the registry."23 win32api.RegSetValue(base,24 path,25 win32con.REG_SZ,26 value)27def _get_string(path, base=win32con.HKEY_CLASSES_ROOT):28 "Get a string value from the registry."29 try:30 return win32api.RegQueryValue(base, path)31 except win32api.error:32 return None33def _remove_key(path, base=win32con.HKEY_CLASSES_ROOT):34 "Remove a string from the registry."35 try:36 win32api.RegDeleteKey(base, path)37 except win32api.error as xxx_todo_changeme1:38 (code, fn, msg) = xxx_todo_changeme1.args39 if code != winerror.ERROR_FILE_NOT_FOUND:40 raise win32api.error(code, fn, msg)41def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):42 """Recursively delete registry keys.43 This is needed since you can't blast a key when subkeys exist.44 """45 try:46 h = win32api.RegOpenKey(base, path)47 except win32api.error as xxx_todo_changeme2:48 (code, fn, msg) = xxx_todo_changeme2.args49 if code != winerror.ERROR_FILE_NOT_FOUND:50 raise win32api.error(code, fn, msg)51 else:52 # parent key found and opened successfully. do some work, making sure53 # to always close the thing (error or no).54 try:55 # remove all of the subkeys56 while True:57 try:58 subkeyname = win32api.RegEnumKey(h, 0)59 except win32api.error as xxx_todo_changeme:60 (code, fn, msg) = xxx_todo_changeme.args61 if code != winerror.ERROR_NO_MORE_ITEMS:62 raise win32api.error(code, fn, msg)63 break64 recurse_delete_key(path + '\\' + subkeyname, base)65 # remove the parent key66 _remove_key(path, base)67 finally:68 win32api.RegCloseKey(h)69def _cat_registrar():70 return pythoncom.CoCreateInstance(71 pythoncom.CLSID_StdComponentCategoriesMgr,72 None,73 pythoncom.CLSCTX_INPROC_SERVER,74 pythoncom.IID_ICatRegister75 )76def _find_localserver_exe(mustfind):77 if not sys.platform.startswith("win32"):78 return sys.executable79 if pythoncom.__file__.find("_d") < 0:80 exeBaseName = "pythonw.exe"81 else:82 exeBaseName = "pythonw_d.exe"83 # First see if in the same directory as this .EXE84 exeName = os.path.join(os.path.split(sys.executable)[0], exeBaseName)85 if not os.path.exists(exeName):86 # See if in our sys.prefix directory87 exeName = os.path.join(sys.prefix, exeBaseName)88 if not os.path.exists(exeName):89 # See if in our sys.prefix/pcbuild directory (for developers)90 if "64 bit" in sys.version:91 exeName = os.path.join(sys.prefix, "PCbuild", "amd64", exeBaseName)92 else:93 exeName = os.path.join(sys.prefix, "PCbuild", exeBaseName)94 if not os.path.exists(exeName):95 # See if the registry has some info.96 try:97 key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver98 path = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE, key)99 exeName = os.path.join(path, exeBaseName)100 except (AttributeError, win32api.error):101 pass102 if not os.path.exists(exeName):103 if mustfind:104 raise RuntimeError("Can not locate the program '%s'" % exeBaseName)105 return None106 return exeName107def _find_localserver_module():108 import win32com.server109 path = win32com.server.__path__[0]110 baseName = "localserver"111 pyfile = os.path.join(path, baseName + ".py")112 try:113 os.stat(pyfile)114 except os.error:115 # See if we have a compiled extension116 if __debug__:117 ext = ".pyc"118 else:119 ext = ".pyo"120 pyfile = os.path.join(path, baseName + ext)121 try:122 os.stat(pyfile)123 except os.error:124 raise RuntimeError(125 "Can not locate the Python module 'win32com.server.%s'" %126 baseName)127 return pyfile128def RegisterServer(clsid,129 pythonInstString=None,130 desc=None,131 progID=None, verProgID=None,132 defIcon=None,133 threadingModel="both",134 policy=None,135 catids=[], other={},136 addPyComCat=None,137 dispatcher=None,138 clsctx=None,139 addnPath=None,140 ):141 """Registers a Python object as a COM Server. This enters almost all necessary142 information in the system registry, allowing COM to use the object.143 clsid -- The (unique) CLSID of the server.144 pythonInstString -- A string holding the instance name that will be created145 whenever COM requests a new object.146 desc -- The description of the COM object.147 progID -- The user name of this object (eg, Word.Document)148 verProgId -- The user name of this version's implementation (eg Word.6.Document)149 defIcon -- The default icon for the object.150 threadingModel -- The threading model this object supports.151 policy -- The policy to use when creating this object.152 catids -- A list of category ID's this object belongs in.153 other -- A dictionary of extra items to be registered.154 addPyComCat -- A flag indicating if the object should be added to the list155 of Python servers installed on the machine. If None (the default)156 then it will be registered when running from python source, but157 not registered if running in a frozen environment.158 dispatcher -- The dispatcher to use when creating this object.159 clsctx -- One of the CLSCTX_* constants.160 addnPath -- An additional path the COM framework will add to sys.path161 before attempting to create the object.162 """163 # backwards-compat check164 # Certain policies do not require a "class name", just the policy itself.165 if not pythonInstString and not policy:166 raise TypeError(167 'You must specify either the Python Class or Python Policy which implement the COM object.')168 keyNameRoot = "CLSID\\%s" % str(clsid)169 _set_string(keyNameRoot, desc)170 # Also register as an "Application" so DCOM etc all see us.171 _set_string("AppID\\%s" % clsid, progID)172 # Depending on contexts requested, register the specified server type.173 # Set default clsctx.174 if not clsctx:175 clsctx = pythoncom.CLSCTX_INPROC_SERVER | pythoncom.CLSCTX_LOCAL_SERVER176 # And if we are frozen, ignore the ones that don't make sense in this177 # context.178 if pythoncom.frozen:179 assert sys.frozen, "pythoncom is frozen, but sys.frozen is not set - don't know the context!"180 if sys.frozen == "dll":181 clsctx = clsctx & pythoncom.CLSCTX_INPROC_SERVER182 else:183 clsctx = clsctx & pythoncom.CLSCTX_LOCAL_SERVER184 # Now setup based on the clsctx left over.185 if clsctx & pythoncom.CLSCTX_INPROC_SERVER:186 # get the module to use for registration.187 # nod to Gordon's installer - if sys.frozen and sys.frozendllhandle188 # exist, then we are being registered via a DLL - use this DLL as the189 # file name.190 if pythoncom.frozen:191 if hasattr(sys, "frozendllhandle"):192 dllName = win32api.GetModuleFileName(sys.frozendllhandle)193 else:194 raise RuntimeError(195 "We appear to have a frozen DLL, but I don't know the DLL to use")196 else:197 # Normal case - running from .py file, so register pythoncom's DLL.198 # Although now we prefer a 'loader' DLL if it exists to avoid some199 # manifest issues (the 'loader' DLL has a manifest, but pythoncom200 # does not)201 pythoncom_dir = os.path.dirname(pythoncom.__file__)202 if pythoncom.__file__.find("_d") < 0:203 suffix = ""204 else:205 suffix = "_d"206 loadername = "pythoncomloader%d%d%s.dll" % (207 sys.version_info[0], sys.version_info[1], suffix)208 if os.path.isfile(os.path.join(pythoncom_dir, loadername)):209 dllName = loadername210 else:211 # just use pythoncom.212 dllName = os.path.basename(pythoncom.__file__)213 _set_subkeys(keyNameRoot + "\\InprocServer32",214 {None: dllName,215 "ThreadingModel": threadingModel,216 })217 else: # Remove any old InProcServer32 registrations218 _remove_key(keyNameRoot + "\\InprocServer32")219 if clsctx & pythoncom.CLSCTX_LOCAL_SERVER:220 if pythoncom.frozen:221 # If we are frozen, we write "{exe} /Automate", just222 # like "normal" .EXEs do223 exeName = win32api.GetShortPathName(sys.executable)224 command = '%s /Automate' % (exeName,)225 else:226 # Running from .py sources - we need to write227 # 'python.exe win32com\server\localserver.py {clsid}"228 exeName = _find_localserver_exe(1)229 exeName = win32api.GetShortPathName(exeName)230 pyfile = _find_localserver_module()231 command = '%s "%s" %s' % (exeName, pyfile, str(clsid))232 _set_string(keyNameRoot + '\\LocalServer32', command)233 else: # Remove any old LocalServer32 registrations234 _remove_key(keyNameRoot + "\\LocalServer32")235 if pythonInstString:236 _set_string(keyNameRoot + '\\PythonCOM', pythonInstString)237 else:238 _remove_key(keyNameRoot + '\\PythonCOM')239 if policy:240 _set_string(keyNameRoot + '\\PythonCOMPolicy', policy)241 else:242 _remove_key(keyNameRoot + '\\PythonCOMPolicy')243 if dispatcher:244 _set_string(keyNameRoot + '\\PythonCOMDispatcher', dispatcher)245 else:246 _remove_key(keyNameRoot + '\\PythonCOMDispatcher')247 if defIcon:248 _set_string(keyNameRoot + '\\DefaultIcon', defIcon)249 else:250 _remove_key(keyNameRoot + '\\DefaultIcon')251 if addnPath:252 _set_string(keyNameRoot + "\\PythonCOMPath", addnPath)253 else:254 _remove_key(keyNameRoot + "\\PythonCOMPath")255 if addPyComCat is None:256 addPyComCat = pythoncom.frozen == 0257 if addPyComCat:258 catids = catids + [CATID_PythonCOMServer]259 # Set up the implemented categories260 if catids:261 regCat = _cat_registrar()262 regCat.RegisterClassImplCategories(clsid, catids)263 # set up any other reg values they might have264 if other:265 for key, value in other.items():266 _set_string(keyNameRoot + '\\' + key, value)267 if progID:268 # set the progID as the most specific that was given to us269 if verProgID:270 _set_string(keyNameRoot + '\\ProgID', verProgID)271 else:272 _set_string(keyNameRoot + '\\ProgID', progID)273 # Set up the root entries - version independent.274 if desc:275 _set_string(progID, desc)276 _set_string(progID + '\\CLSID', str(clsid))277 # Set up the root entries - version dependent.278 if verProgID:279 # point from independent to the current version280 _set_string(progID + '\\CurVer', verProgID)281 # point to the version-independent one282 _set_string(keyNameRoot + '\\VersionIndependentProgID', progID)283 # set up the versioned progID284 if desc:285 _set_string(verProgID, desc)286 _set_string(verProgID + '\\CLSID', str(clsid))287def GetUnregisterServerKeys(288 clsid, progID=None, verProgID=None, customKeys=None):289 """Given a server, return a list of of ("key", root), which are keys recursively290 and uncondtionally deleted at unregister or uninstall time.291 """292 # remove the main CLSID registration293 ret = [("CLSID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT)]294 # remove the versioned ProgID registration295 if verProgID:296 ret.append((verProgID, win32con.HKEY_CLASSES_ROOT))297 # blow away the independent ProgID. we can't leave it since we just298 # torched the class.299 # could potentially check the CLSID... ?300 if progID:...
control_data.py
Source:control_data.py
...136 suite_names.add(suite_name)137 # Rebuild the suite field if necessary.138 if suite_names:139 self.set_suite(','.join(sorted(list(suite_names))))140 def _set_string(self, attr, val):141 val = str(val)142 setattr(self, attr, val)143 def _set_option(self, attr, val, options):144 val = str(val)145 if val.lower() not in [x.lower() for x in options]:146 raise ValueError("%s must be one of the following "147 "options: %s" % (attr,148 ', '.join(options)))149 setattr(self, attr, val)150 def _set_bool(self, attr, val):151 val = str(val).lower()152 if val == "false":153 val = False154 elif val == "true":155 val = True156 else:157 msg = "%s must be either true or false" % attr158 raise ValueError(msg)159 setattr(self, attr, val)160 def _set_int(self, attr, val, min=None, max=None):161 val = int(val)162 if min is not None and min > val:163 raise ValueError("%s is %d, which is below the "164 "minimum of %d" % (attr, val, min))165 if max is not None and max < val:166 raise ValueError("%s is %d, which is above the "167 "maximum of %d" % (attr, val, max))168 setattr(self, attr, val)169 def _set_set(self, attr, val):170 val = str(val)171 items = [x.strip() for x in val.split(',') if x.strip()]172 setattr(self, attr, set(items))173 def set_author(self, val):174 self._set_string('author', val)175 def set_dependencies(self, val):176 self._set_set('dependencies', val)177 def set_doc(self, val):178 self._set_string('doc', val)179 def set_name(self, val):180 self._set_string('name', val)181 def set_run_verify(self, val):182 self._set_bool('run_verify', val)183 def set_sync_count(self, val):184 self._set_int('sync_count', val, min=1)185 def set_suite(self, val):186 self._set_string('suite', val)187 def set_time(self, val):188 self._set_option('time', val, ControlData.TEST_TIME_LIST)189 def set_test_class(self, val):190 self._set_string('test_class', val.lower())191 def set_test_category(self, val):192 self._set_string('test_category', val.lower())193 def set_test_type(self, val):194 self._set_option('test_type', val, list(CONTROL_TYPE.names))195 def set_test_parameters(self, val):196 self._set_set('test_parameters', val)197 def set_job_retries(self, val):198 self._set_int('job_retries', val)199 def set_bug_template(self, val):200 if type(val) == dict:201 setattr(self, 'bug_template', val)202 def set_require_ssp(self, val):203 self._set_bool('require_ssp', val)204 def set_build(self, val):205 self._set_string('build', val)206 def set_builds(self, val):207 if type(val) == dict:208 setattr(self, 'builds', val)209 def set_max_result_size_kb(self, val):210 self._set_int('max_result_size_KB', val)211 def set_priority(self, val):212 self._set_int('priority', val)213 def set_fast(self, val):214 self._set_bool('fast', val)215 def set_update_type(self, val):216 self._set_string('update_type', val)217 def set_source_release(self, val):218 self._set_string('source_release', val)219 def set_target_release(self, val):220 self._set_string('target_release', val)221 def set_target_payload_uri(self, val):222 self._set_string('target_payload_uri', val)223 def set_source_payload_uri(self, val):224 self._set_string('source_payload_uri', val)225 def set_source_archive_uri(self, val):226 self._set_string('source_archive_uri', val)227 def set_attributes(self, val):228 # Add subsystem:default if subsystem is not specified.229 self._set_set('attributes', val)230 if not any(a.startswith('subsystem') for a in self.attributes):231 self.attributes.add('subsystem:default')232def _extract_const(expr):233 assert(expr.__class__ == compiler.ast.Const)234 assert(expr.value.__class__ in (str, int, float, unicode))235 return str(expr.value).strip()236def _extract_dict(expr):237 assert(expr.__class__ == compiler.ast.Dict)238 assert(expr.items.__class__ == list)239 cf_dict = {}240 for key, value in expr.items:...
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!!