How to use _sdk_path method in robotframework-androidlibrary

Best Python code snippet using robotframework-androidlibrary_python

Sdk.py

Source:Sdk.py Github

copy

Full Screen

1##############################################################################2# Copyright (c) 2018 by Paul Scherrer Institute, Switzerland3# All rights reserved.4# Authors: Oliver Bruendler5##############################################################################6########################################################################################################################7# Import Statements8########################################################################################################################9from PsiPyUtils.TempFile import TempFile10from PsiPyUtils.TempWorkDir import TempWorkDir11from PsiPyUtils.ExtAppCall import ExtAppCall12import os, sys13import shutil14from distutils import dir_util15import pyparsing as pp16import glob17from typing import Iterable, NamedTuple18class SdkStdErrNotEmpty(Exception):19 pass20class SdkExitCodeNotZero(Exception):21 pass22LibInfo = NamedTuple("LibInfo", [("path", str),("name", str)])23########################################################################################################################24# Class Defintion25########################################################################################################################26class Sdk:27 """28 This class allows building SDK projects from the command line.29 Usage example:30 sdk = Sdk("SDK_2017_2", "myWs", "2017.2")31 sdk.CreateEmtpyWorkspace()32 sdk.ImportProjects( hwPath="D:/dbpm/BPM_FPGA/Vivado/soc.sdk/soc_wrapper_hw_platform_0",33 bspPath="D:/dbpm/BPM_FPGA/Vivado/soc.sdk/bsp",34 appPath="D:/dbpm/BPM_FPGA/Vivado/soc.sdk/sw")35 sdk.UpdateHwSpec("D:/dbpm/BPM_FPGA/Vivado/soc/SdkExport/soc_wrapper.hdf")36 sdk.BuildWorkspace()37 sdk.CreateBitWithSw("Debug", "soc_i/processor/microblaze_0", "out.bit")38 sdk.CleanWorkpace()39 """40 ####################################################################################################################41 # Public Methods42 ####################################################################################################################43 def __init__(self, sdkPathEnv : str, version : str):44 """45 Initialize an SDK workspace to build.46 :param sdkPathEnv: Environment variable that points to the SDk installation. This can be used to have multiple47 SDK installations in parallel and have an environment variable pointint to each one. By48 choosing the right environment variable, one can choose the SDK version to use.49 :param version: Toolversion in the form "2017.2". This version string may be used in future for the case that50 commands or paths change between versions.51 """52 if sdkPathEnv not in os.environ:53 raise Exception("Enviromental variable {} does not exists. Please specify it".format(sdkPathEnv))54 self._sdk_path = os.environ[sdkPathEnv]55 self.workspace = None56 self.stderr = ""57 self.stdout = ""58 self.allStdOut = ""59 self._SetPaths()60 def UseExistingWorkspace(self, workspace : str, hw_name : str = None, bsp_name : str = None):61 """62 :param workspace: Path of the workspace to use.63 WARNING: This method is deprecated! Use "CreateEmptyWorkspace" and "ImportProjects" instead64 """65 self.workspace = os.path.abspath(workspace)66 self.hwName = hw_name67 self.bspName = bsp_name68 def CreateEmtpyWorkspace(self, workspace : str):69 """70 Delete the workspace folder if it exists and create a new, completely empty folder.71 :param workspace: Path of the workspace to use.72 """73 out = ""74 err = ""75 shutil.rmtree(workspace, ignore_errors=True)76 os.mkdir(workspace)77 self.UseExistingWorkspace(workspace)78 def ImportProjects(self, hwPath : str, bspPath : str, appPath : str, libPaths : Iterable[str] = None, debug : bool = False):79 """80 Import projects into workspace81 :param hwPath: Path to the HW project82 :param bspPath: Path to the BSP project83 :param appPath: Path to the application project84 :param libPaths: Path to additional library projects (to be built before the application)85 :param debug: Optional parameter. If true, the standard output is printed to the console. In this case the automatic checking for86 errors is disabled, so it shall only be used for debugging purposes.87 """88 importClauses = ""89 self.hwName = os.path.split(hwPath)[-1] if hwPath is not None else None90 self.hwPath = hwPath91 self.appName = os.path.split(appPath)[-1] if appPath is not None else None92 self.appPath = appPath93 self.bspName = os.path.split(bspPath)[-1] if bspPath is not None else None94 self.bspPath = bspPath95 for path in [hwPath, bspPath, appPath]:96 if path is not None:97 importClauses += "importprojects {} \n".format(os.path.abspath(path).replace("\\", "/"))98 if libPaths is None:99 libPaths = []100 self.libInfo = [LibInfo(path=p, name=os.path.split(p)[-1]) for p in libPaths]101 for li in self.libInfo:102 importClauses += "importprojects {} \n".format(os.path.abspath(li.path).replace("\\", "/"))103 self._RunSdk(importClauses, debug)104 def UpdateHwSpec(self, hdfPath : str, debug : bool = False):105 """106 Update the HW specification with a new .hdf file107 :param hdfPath: Path to the new HDF file108 :param debug: Optional parameter. If true, the standard output is printed to the console. In this case the automatic checking for109 errors is disabled, so it shall only be used for debugging purposes.110 """111 # Parse MSS file to restore OS Settings later112 # .. This is a workaround for the issue that the BSP settings are overwritten by the Xilinx tools.113 # .. Replacement is done after updating the spec114 PP_END = pp.CaselessKeyword("END")115 PP_OS = pp.CaselessKeyword("BEGIN OS") + pp.OneOrMore(pp.Combine(~PP_END + pp.restOfLine())) + PP_END116 mssFile = glob.glob(os.path.join(self.workspace, self.bspName, "*.mss"))[0]117 os_block = None118 with open(mssFile) as f:119 content = f.read()120 for t, s, e in PP_OS.scanString(content):121 os_block = content[s:e]122 #Update HW Spec123 tclStr = ""124 tclStr += "updatehw -hw {} -newhwspec {}\n".format(self.hwName, os.path.abspath(hdfPath).replace("\\","/"))125 try:126 self._RunSdk(tclStr, debug)127 # Ignore expected error and Restore MSS File, second part of workaround described above128 except SdkStdErrNotEmpty as e:129 #Ignore expected error130 if "ERROR: psu_cortexr5 does not support psu_iou_scntr" in str(e):131 pass132 else:133 raise e134 with open(mssFile) as f:135 content = f.read()136 for t, s, e in PP_OS.scanString(content):137 content = content.replace(content[s:e], os_block)138 with open(mssFile, "w+") as f:139 f.write(content)140 #Update BSP141 tclStr = ""142 tclStr += "regenbsp -bsp {}\n".format(self.bspName)143 self._RunSdk(tclStr, debug)144 def CopyToSrcLoc(self):145 """146 Copy the projects from the workspace back to their source locations.147 This is required as workaround for the fact, that XSCT always copies all sources into the project (instead of linking them)148 """149 for name, dir in zip((self.hwName, self.bspName, self.appName), (self.hwPath, self.bspPath, self.appPath)):150 if name is not None:151 dir_util.copy_tree(self.workspace + "/" + name, dir)152 for li in self.libInfo:153 dir_util.copy_tree(self.workspace + "/" + li.name, li.path)154 def ExecuteXsctCommands(self, commands : Iterable[str] = None, debug : bool = False):155 """156 Execute some XSCT commands in the workspace. This is often useful for customization and bug-workarounds.157 :param commands: XSCT commands (iterable containing each command as separate string)158 :param debug: Optional parameter. If true, the standard output is printed to the console. In this case the automatic checking for159 errors is disabled, so it shall only be used for debugging purposes.160 """161 if commands is not None:162 tclStr = ""163 for cmd in commands:164 tclStr += "{}\n".format(cmd)165 self._RunSdk(tclStr, debug)166 def BuildWorkspace(self, debug : bool = False):167 """168 Clean and build bsp and app in workspace169 :param debug: Optional parameter. If true, the standard output is printed to the console. In this case the automatic checking for170 errors is disabled, so it shall only be used for debugging purposes.171 """172 tclStr = ""173 tclStr += "projects -clean -type all\n"174 tclStr += "projects -build -type bsp -name {}\n".format(self.bspName)175 for li in self.libInfo:176 tclStr += "projects -build -type app -name {}\n".format(li.name)177 tclStr += "projects -build -type app -name {}\n".format(self.appName)178 self._RunSdk(tclStr, debug)179 #WORKAROUND: XSCT always copies all sources into the project (instead of linking them). So after building they180 # must be copied back to ensure the original location contains correct files (e.g. the .mss file181 # must be stored)182 self.CopyToSrcLoc()183 def CreateBitWithSw(self, appBuildConfig: str, procName: str, outFile: str):184 """185 Create a bit file that contains the freshly built software. This command can only be used after the186 ImportProjects() command was called.187 :param appBuildConfig: Application configuration to use (usually "Debug" or "Release")188 :param procName: Name of the processor to use (e.g. soc_i/microblaze_0)189 :param outFile: Path of the output .bit file to write (relative to the HW project dir)190 """191 with TempWorkDir("/".join([self.workspace, self.hwName])):192 mmi = list(filter(lambda x: x.endswith(".mmi"), os.listdir()))[0]193 prefix = mmi.split(".")[0]194 mmi = os.path.abspath(os.curdir) + "/" + mmi195 bitin = os.path.abspath(os.curdir) + "/" + prefix + ".bit"196 appDir = "/".join([self.workspace, self.appName, appBuildConfig])197 with TempWorkDir(appDir):198 try:199 elfName = list(filter(lambda x: x.endswith(".elf"), os.listdir()))[0]200 except IndexError:201 raise Exception("No ELF file found in application directory " + appDir)202 elf = os.path.abspath(os.curdir) + "/" + elfName203 with TempWorkDir("/".join([self.workspace, self.hwName])):204 call = ExtAppCall(".",205 "{} -meminfo {} -data {} -bit {} -proc {} -out {} -force".format(self._updatememCmd, mmi,206 elf, bitin, procName,207 outFile))208 call.run_sync()209 self._UpdateStdOut(call)210 def CleanWorkpace(self):211 """212 Delete complete workspace213 """214 shutil.rmtree(self.workspace, ignore_errors=True)215 def ClearAllStdOut(self):216 """217 Clear the standard output history218 """219 self.allStdOut = ""220 ####################################################################################################################221 # Public Properties222 ####################################################################################################################223 @property224 def StdErr(self):225 """226 Get standard error output of the last command executed227 :return: stderr output of the last command228 """229 return self.stderr230 @property231 def StdOut(self):232 """233 Get standard output of the last command executed234 :return: stdout output of the last command235 """236 return self.stdout237 @property238 def AllStdOut(self):239 """240 Get all standard output of all commands executed since the last execution of ClearAllStdOut().241 :return: stdout output242 """243 return self.allStdOut244 ####################################################################################################################245 # Private Methods246 ####################################################################################################################247 def _UpdateStdOut(self, call : ExtAppCall):248 self.stderr = call.get_stderr()249 self.stdout = call.get_stdout()250 self.allStdOut += self.stdout251 #Remove expected error messages252 stderr = self.stderr253 stderr = stderr.replace("Xlib: extension \"RANDR\" missing on display \":1\".","").strip() #Expected error from xvfb254 if len(stderr) != 0:255 raise SdkStdErrNotEmpty("STDERR not empty:\n<includes expected errors!>\n" + self.stderr)256 if call.get_exit_code() != 0:257 raise SdkExitCodeNotZero("Command exited with code {}".format(call.get_exit_code()))258 def _SetPaths(self):259 if sys.platform.startswith("win"):260 os.environ["PATH"] += ";{}/bin".format(self._sdk_path).replace("/", "\\")261 os.environ["PATH"] += ";{}/gnu/microblaze/nt/bin".format(self._sdk_path).replace("/", "\\")262 os.environ["PATH"] += ";{}/gnu/arm/nt/bin".format(self._sdk_path).replace("/", "\\")263 os.environ["PATH"] += ";{}/gnu/microblaze/linux_toolchain/nt64_be/bin".format(self._sdk_path).replace("/", "\\")264 os.environ["PATH"] += ";{}/gnu/aarch32/nt/gcc-arm-linux-gnueabi/bin".format(self._sdk_path).replace("/", "\\")265 os.environ["PATH"] += ";{}/gnu/aarch32/nt/gcc-arm-none-eabi/bin".format(self._sdk_path).replace("/", "\\")266 os.environ["PATH"] += ";{}/gnu/aarch64/nt/aarch64-linux/bin".format(self._sdk_path).replace("/", "\\")267 os.environ["PATH"] += ";{}/gnu/aarch64/nt/aarch64-none/bin".format(self._sdk_path).replace("/", "\\")268 os.environ["PATH"] += ";{}/gnu/armr5/nt/gcc-arm-none-eabi/bin".format(self._sdk_path).replace("/", "\\")269 os.environ["PATH"] += ";{}/tps/win64/cmake-3.3".format(self._sdk_path).replace("/", "\\")270 self._xsctCmd = "xsct.bat"271 self._updatememCmd = "updatemem.bat"272 elif sys.platform.startswith("linux"):273 os.environ["PATH"] += ":{}/bin".format(self._sdk_path)274 os.environ["PATH"] += ":{}/gnu/microblaze/lin/bin".format(self._sdk_path)275 os.environ["PATH"] += ":{}/gnu/arm/lin/bin".format(self._sdk_path)276 os.environ["PATH"] += ":{}/gnu/microblaze/linux_toolchain/lin64_le/bin".format(self._sdk_path)277 os.environ["PATH"] += ":{}/gnu/aarch32/lin/gcc-arm-linux-gnueabi/bin".format(self._sdk_path)278 os.environ["PATH"] += ":{}/gnu/aarch32/lin/gcc-arm-none-eabi/bin".format(self._sdk_path)279 os.environ["PATH"] += ":{}/gnu/aarch64/lin/aarch64-linux/bin".format(self._sdk_path)280 os.environ["PATH"] += ":{}/gnu/aarch64/lin/aarch64-none/bin".format(self._sdk_path)281 os.environ["PATH"] += ":{}/gnu/armr5/lin/gcc-arm-none-eabi/bin".format(self._sdk_path)282 os.environ["PATH"] += ":{}/tps/lnx64/cmake-3.3".format(self._sdk_path)283 # required to suppress non-real error message related to graphics framework (tool bug), Xvfb must be running284 os.environ["DISPLAY"] = ":1"285 self._xsctCmd = "xsct"286 self._updatememCmd = "updatemem"287 else:288 raise Exception("Unsupported OS")289 def _RunSdk(self, tclString : str, debug : bool = False):290 with TempWorkDir(self.workspace):291 with TempFile("__sdk.tcl") as f:292 #Write Temporary TCL293 f.write("setws .\n") #Set workspace294 f.write(tclString)295 f.flush()296 if not debug:297 call = ExtAppCall(".", "{} __sdk.tcl".format(self._xsctCmd))298 call.run_sync()299 self._UpdateStdOut(call)300 else:...

Full Screen

Full Screen

build_using_sdk.py

Source:build_using_sdk.py Github

copy

Full Screen

...12from src.build import toolchain13from src.build.util import file_util14_ARC_ROOT = build_common.get_arc_root()15_NDK_PATH = os.path.join(_ARC_ROOT, 'third_party', 'ndk')16_SDK_PATH = build_common.get_android_sdk_path()17_TOOLS_ROOT = os.path.join(_ARC_ROOT, 'third_party', 'tools')18def _build_apk(source_path, use_ndk, use_clang, build_path,19 install_apk, debug, verbose):20 if not os.path.isdir(_SDK_PATH):21 raise Exception('Missing SDK path: ' + str(_SDK_PATH))22 print23 print '--------------------------'24 print 'Building ' + os.path.basename(install_apk)25 print '--------------------------'26 # We use this work directory in order to allow us to completely27 # create it from scratch every time we build. We cannot do that28 # to the build_path since files in there (like the build.log)29 # should not be deleted on every run.30 work_path = os.path.join(build_path, 'work')...

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 robotframework-androidlibrary 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