Best Python code snippet using autotest_python
fileFactory.py
Source:fileFactory.py
1import sys2COMMENT = "#" # or "//"3COMMENT_SECTION = COMMENT+"[section]"4COMMENT_FILE = COMMENT+"[file]"5BLUEPRINT_COMMENT = "#"6BLUEPRINT_SEP = "#"7class BakingError(BaseException): pass8class UnbakingError(BaseException): pass9def errPrint(*a, **kw):10 print(*a, **kw, file=sys.stderr)11def passFile(filename, mode, function, *a, **kw):12 if filename=="-":13 if "r" in mode:14 return function(sys.stdin, *a, **kw)15 elif "w" in mode:16 return function(sys.stdout, *a, **kw)17 else:18 with open(filename, mode) as f:19 return function(f, *a, **kw)20def parseBlueprint(inp):21 parts = []22 for l in inp.readlines():23 l = l.strip()24 if l.startswith(BLUEPRINT_COMMENT): continue # ignore comments (lines starting with #)25 fnd = l.find(BLUEPRINT_SEP);26 if fnd == -1:27 parts.append((l, "")) # unnamed section, everything before first named28 else:29 parts.append((l[:fnd].rstrip(), l[fnd+len(BLUEPRINT_SEP):].lstrip()))30 return parts31class BakingComponentFile:32 __slots__ = """33 filename34 sections35 sectionsUnused36 """.split()37 38 def __init__(self, fn):39 # parse whole file and search for comments40 self.filename = fn41 self.sections = {}42 curSection = ""43 curContent = ""44 def pushSection():45 nonlocal self, curSection, curContent46 if curSection or curContent:47 self.sections[curSection] = curContent48 curSection = None49 curContent = ""50 51 with open(fn, "rt") as f:52 for i, l in enumerate(f.readlines()):53 ll = l.strip()54 if ll.startswith(COMMENT_SECTION):55 pushSection()56 curSection = ll[len(COMMENT_SECTION):].lstrip()57 if curSection in self.sections:58 errPrint("%s: line %i: section %s appeared twice"%(fn, i+1, curSection))59 else:60 curContent += l61 pushSection()62 self.sectionsUnused = list(self.sections.keys())63 def getSectionContent(self, section):64 try: sec = self.sections[section]65 except KeyError:66 errPrint("There is no section", section or "<unnamed>", "in", self.filename)67 raise68 try: self.sectionsUnused.remove(section)69 except ValueError: errPrint("Section", section, "used again")70 return sec71class BakingSession:72 __slots__ = """73 files74 """.split()75 76 def __init__(self):77 self.files = {}78 def getSectionContent(self, fn, section):79 try:80 file = self.files[fn]81 except KeyError:82 file = self.files[fn] = BakingComponentFile(fn)83 return file.getSectionContent(section)84 85 def finish(self):86 for f in self.files.values():87 if f.sectionsUnused:88 errPrint(f.filename + ": Unused sections:")89 for s in sorted(f.sectionsUnused):90 errPrint(" -", s or "<unnamed>")91def assembleBlueprint(outp, blueprint):92 bs = BakingSession()93 for fn, section in blueprint:94 if COMMENT_FILE:95 if section:96 print(COMMENT_FILE, fn+"#"+section, file=outp)97 else:98 print(COMMENT_FILE, fn, file=outp)99 secContent = bs.getSectionContent(fn, section)100 if secContent[-1:] != "\n": secContent+="\n"101 outp.write(secContent)102 103 bs.finish()104def bake(fnBlueprint, fnOutput):105 blueprint = passFile(fnBlueprint, "rt", parseBlueprint)106 passFile(fnOutput, "wt", assembleBlueprint, blueprint)107class UnbakingComponentFile:108 __slots__ = """109 filename110 content111 sections112 """.split()113 def __init__(self, filename):114 self.filename = filename115 self.content = ""116 self.sections = []117 def putSection(self, section, content):118 while section in self.sections:119 errPrint(self.filename+": Duplicate sections", section)120 section = section + "(%i)"%len(self.sections)121 self.sections.append(section)122 123 if content[-1:] != '\n':124 content += '\n'125 if section:126 self.content += COMMENT_SECTION + " " + section + "\n"127 self.content += content128 else:129 # pull unnamed section to the front130 self.content = content+self.content131 return section132 133class UnbakingSession:134 __slots__ = """135 blueprint136 files137 """.split()138 139 def __init__(self):140 self.blueprint = []141 self.files = {}142 def putSection(self, filename, section, content):143 try:144 file = self.files[filename]145 except KeyError:146 file = self.files[filename] = UnbakingComponentFile(filename)147 section = file.putSection(section, content)148 self.blueprint.append((filename, section))149 150def disassemble(inp):151 bs = UnbakingSession()152 curFileSection = ""153 curContent = ""154 def pushSection():155 nonlocal bs, curFileSection, curContent156 if curFileSection == "": return # move unnamed to first section157 fnd = curFileSection.find("#")158 if fnd == -1:159 curFile = curFileSection160 curSection = ""161 else:162 curFile = curFileSection[:fnd].rstrip()163 curSection = curFileSection[fnd+1:].lstrip()164 165 bs.putSection(curFile, curSection, curContent)166 curContent = ""167 168 for i, l in enumerate(inp.readlines()):169 ll = l.strip()170 if ll.startswith(COMMENT_FILE):171 pushSection()172 curFileSection = ll[len(COMMENT_FILE):].lstrip()173 else:174 curContent += l175 pushSection()176 return bs177 178def createBlueprint(inp, blueprint):179 for fn, section in blueprint:180 fnSection = (fn+BLUEPRINT_SEP+section if section else fn)181 print(fnSection, file=inp)182# writes to files in current working directory183def unbake(fnInput, fnBlueprint):184 unbaked = passFile(fnInput, "rt", disassemble)185 passFile(fnBlueprint, "wt", createBlueprint, unbaked.blueprint)186 for cf in unbaked.files.values():187 # when there are relative path, the unbaking process could lead to writing to188 # other directories, this could be a security problem189 if ".." in cf.filename: raise UnbakingError("Parent directory filenames disabled")190 with open(cf.filename, "wt") as f:191 f.write(cf.content)...
.DeepLinkingCompliance.py
Source:.DeepLinkingCompliance.py
1#!/usr/bin/env python2import subprocess3import os4import re5import sys6import pathlib7class DeepLinkingCompliance:8 def __init__(self):9 self.temporaryFileStorePath = ".MagicDeeplinkConfig/AddedNewSwiftFilesList.txt"10 self.compliantViewControllerNames = []11 12 # self.getAddedSwiftFilesOnProject()13 # self.checkFilesForViewControllers()14 # if len(self.compliantViewControllerNames) > 0:15 # self.checkInfoPlistForClassMapping()16'''17 # This function will find new swift files on project by using git diff command. Basically it will differentiate files with UMA-Origin and store list of files in temporary file.18 def getAddedSwiftFilesOnProject(self):19 self.create_file = subprocess.run(["touch", self.temporaryFileStorePath])20 self.git_branch_added_file_list = subprocess.run(["git", "diff", "--name-only", "--diff-filter=cdmrtuxb", "origin/UMA-Origin"], input=self.create_file.stdout, capture_output=True)21 self.list_only_uma_only_files = subprocess.run(["grep", "UMA/UMA_Main"], input=self.git_branch_added_file_list.stdout, capture_output=True)22 self.filter_swift_files_only = subprocess.run(["grep", ".*\\.swift$"], input=self.list_only_uma_only_files.stdout, capture_output=True)23 self.exclude_tests_files = subprocess.run(["grep", "-v", "Tests"], input=self.filter_swift_files_only.stdout, capture_output=True)24 self.store_output_in_file = subprocess.run(["tee", self.temporaryFileStorePath], input=self.exclude_tests_files.stdout, capture_output=True)25 26 # Get array from temporary files and access each file path27 def checkFilesForViewControllers(self):28 lines = []29 print("cd ..")30 with open(self.temporaryFileStorePath) as f:31 lines = f.readlines()32 self.deleteTempFile()33 for line in lines:34 self.processFileForProtocolCompliance(line)35 36 # Each files which are added need to check that it is UIViewController or not and check for that confirms Routing Protocol by using regex.37 def processFileForProtocolCompliance(self, fileContents):38 textfile = open(fileContents.strip(), 'r')39 filetext = textfile.read()40 41 textfile.close()42 43 # Check if class extends UIViewController and does implement RoutingProtocol44 pattern = re.compile("class\s+(.*)\s*:(?=(.|\n)*UIViewController)(?=(.|\n)*RoutingProtocol)(.|\n)*{")45 matches = re.findall(pattern, filetext)46 # Match so class extends UIViewController and implements RoutingProtocol pull out class name and stor in array47 if len(matches) > 0:48 self.compliantViewControllerNames.append(matches[0][0])49 else:50 patternCheckViewController = re.compile("class\s+(.*)\s*:(?=(.|\n)*UIViewController)(.|\n)*{")51 matchesCheckViewController = re.findall(patternCheckViewController, filetext)52 if len(matchesCheckViewController) > 0:53 # Generic error message pass in xcode and exit further process.54 print("error: RoutingProtocol Missing: Please add RoutingProtocol and configure inside {} this file. For more details please read this page https://confluence.safeway.com/display/DMH/Magic+Deeplinking".format(fileContents))55 print("exit 0")56 try:57 subprocess.check_output(shell=True,stderr=subprocess.STDOUT)58 except subprocess.CalledProcessError as e:59 raise RuntimeError("command return with error (code {}): {}".format(e.returncode, e.output))60 # Check configuration on plist file with that class name. that exists or not.61 def checkInfoPlistForClassMapping(self):62 DeepLinkingPushsectionMappingPlist = open("UMA/UMA_Main/MagicDeepLinking/DeepLinkingPushsectionMapping.plist", 'r')63 deeplinkPlist = DeepLinkingPushsectionMappingPlist.read()64 DeepLinkingPushsectionMappingPlist.close()65 for viewcontroller in self.compliantViewControllerNames:66 if viewcontroller in deeplinkPlist:67 print("configuration found")68 else:69 # Generic error message pass in xcode and exit further process.70 print("error: Missing {} configuration in DeepLinkingPushsectionMapping.plist: Please add RouterName as key and {} as value in DeepLinkingPushsectionMapping.plist. For more details please read this page https://confluence.safeway.com/display/DMH/Magic+Deeplinking".format(viewcontroller, viewcontroller))71 print("exit 0")72 try:73 subprocess.check_output(shell=True,stderr=subprocess.STDOUT)74 except subprocess.CalledProcessError as e:75 raise RuntimeError("command return with error (code {}): {}".format(e.returncode, e.output))76 77 def deleteTempFile(self):78 file = pathlib.Path(self.temporaryFileStorePath)79 file.unlink()80 '''81print("Hello")...
riscv_data_page_gen.py
Source:riscv_data_page_gen.py
1"""2Copyright 2020 Google LLC3Copyright 2020 PerfectVIPs Inc.4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11"""12import logging13import vsc14import random15from collections import defaultdict16from pygen_src.riscv_instr_pkg import pkg_ins, data_pattern_t17from pygen_src.riscv_instr_gen_config import cfg18@vsc.randobj19class riscv_data_page_gen:20 def __init__(self):21 self.data_page_str = []22 self.mem_region_setting = defaultdict(list)23 @staticmethod24 def gen_data(idx, pattern, num_of_bytes, data):25 temp_data = 026 data = [0] * num_of_bytes27 for i in range(len(data)):28 if pattern == data_pattern_t.RAND_DATA:29 temp_data = random.randrange(0, (2**8) - 1)30 data[i] = temp_data31 elif pattern == data_pattern_t.INCR_VAL:32 data[i] = (idx + i) % 25633 return data34 def gen_data_page(self, hart_id, pattern, is_kernel=0, amo=0):35 tmp_str = ""36 temp_data = []37 page_size = 038 self.data_page_str.clear()39 if is_kernel:40 self.mem_region_setting = cfg.s_mem_region41 elif amo:42 self.mem_region_setting = cfg.amo_region43 else:44 self.mem_region_setting = cfg.mem_region45 for i in range(len(self.mem_region_setting)):46 logging.info("mem_region_setting {}".format(self.mem_region_setting[i]))47 for i in range(len(self.mem_region_setting)):48 logging.info("Generate data section: {} size:0x{} xwr:0x{}".format(49 self.mem_region_setting[i].name,50 self.mem_region_setting[i].size_in_bytes,51 self.mem_region_setting[i].xwr))52 if amo:53 if cfg.use_push_data_section:54 self.data_page_str.append(".pushsection .{},\"aw\",@progbits;"55 .format(self.mem_region_setting[i].name))56 else:57 self.data_page_str.append(".section .{},\"aw\",@progbits;"58 .format(self.mem_region_setting[i].name))59 self.data_page_str.append("{}:".format(self.mem_region_setting[i].name))60 else:61 if cfg.use_push_data_section:62 self.data_page_str.append(".pushsection .{},\"aw\",@progbits;"63 .format(pkg_ins.hart_prefix(hart_id) +64 self.mem_region_setting[i].name))65 else:66 self.data_page_str.append(".section .{},\"aw\",@progbits;"67 .format(pkg_ins.hart_prefix(hart_id) +68 self.mem_region_setting[i].name))69 self.data_page_str.append("{}:".format(pkg_ins.hart_prefix(hart_id) +70 self.mem_region_setting[i].name))71 page_size = self.mem_region_setting[i].size_in_bytes72 for i in range(0, page_size, 32):73 if page_size - 1 >= 32:74 temp_data = self.gen_data(idx=i, pattern=pattern,75 num_of_bytes=32, data=temp_data)76 else:77 temp_data = self.gen_data(idx=i, pattern=pattern,78 num_of_bytes=page_size - 1, data=temp_data)79 tmp_str = pkg_ins.format_string(".word {}".format(pkg_ins.format_data(temp_data)),80 pkg_ins.LABEL_STR_LEN)81 self.data_page_str.append(tmp_str)82 if cfg.use_push_data_section:...
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!!