Best Python code snippet using Airtest
fuchsia.py
Source:fuchsia.py
1# Copyright (C) 2018 Google Inc. All rights reserved.2#3# Redistribution and use in source and binary forms, with or without4# modification, are permitted provided that the following conditions are5# met:6#7# * Redistributions of source code must retain the above copyright8# notice, this list of conditions and the following disclaimer.9# * Redistributions in binary form must reproduce the above10# copyright notice, this list of conditions and the following disclaimer11# in the documentation and/or other materials provided with the12# distribution.13# * Neither the name of Google Inc. nor the names of its14# contributors may be used to endorse or promote products derived from15# this software without specific prior written permission.16#17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.28import logging29import os30import select31import socket32import subprocess33import sys34import threading35from blinkpy.common import exit_codes36from blinkpy.common.path_finder import get_chromium_src_dir37from blinkpy.web_tests.port import base38from blinkpy.web_tests.port import driver39from blinkpy.web_tests.port import factory40from blinkpy.web_tests.port import linux41from blinkpy.web_tests.port import server_process42# Modules loaded dynamically in _import_fuchsia_runner().43# pylint: disable=invalid-name44fuchsia_target = None45qemu_target = None46# pylint: enable=invalid-name47# Imports Fuchsia runner modules. This is done dynamically only when FuchsiaPort48# is instantiated to avoid dependency on Fuchsia runner on other platforms.49def _import_fuchsia_runner():50 sys.path.insert(0, os.path.join(get_chromium_src_dir(), 'build/fuchsia'))51 # pylint: disable=import-error52 # pylint: disable=invalid-name53 # pylint: disable=redefined-outer-name54 global fuchsia_target55 import target as fuchsia_target56 global qemu_target57 import qemu_target as qemu_target58 # pylint: enable=import-error59 # pylint: enable=invalid-name60 # pylint: disable=redefined-outer-name61# Path to the content shell package relative to the build directory.62CONTENT_SHELL_PACKAGE_PATH = 'gen/content/shell/content_shell/content_shell.far'63# HTTP path prefix for the HTTP server.64PERF_TEST_PATH_PREFIX = '/PerformanceTests'65LAYOUT_TEST_PATH_PREFIX = '/LayoutTests'66# Paths to the directory where the fonts are copied to. Must match the path in67# content/shell/app/blink_test_platform_support_fuchsia.cc .68FONTS_DEVICE_PATH = '/system/fonts'69# Number of content_shell instances to run in parallel.70MAX_WORKERS = 871PROCESS_START_TIMEOUT = 2072_log = logging.getLogger(__name__)73def _subprocess_log_thread(pipe, prefix):74 try:75 while True:76 line = pipe.readline()77 if not line:78 return79 _log.error('%s: %s', prefix, line)80 finally:81 pipe.close()82class SubprocessOutputLogger(object):83 def __init__(self, process, prefix):84 self._process = process85 self._thread = threading.Thread(86 target=_subprocess_log_thread,87 args=(process.stdout, prefix))88 self._thread.daemon = True89 self._thread.start()90 def __del__(self):91 self.close()92 def close(self):93 self._process.kill()94class _TargetHost(object):95 def __init__(self, build_path, ports_to_forward):96 try:97 self._target = None98 self._target = qemu_target.QemuTarget(99 build_path, 'x64', ram_size_mb=8192)100 self._target.Start()101 self._setup_target(build_path, ports_to_forward)102 except:103 self.cleanup()104 raise105 def _setup_target(self, build_path, ports_to_forward):106 # Tell SSH to forward all server ports from the Fuchsia device to107 # the host.108 forwarding_flags = [109 '-O', 'forward', # Send SSH mux control signal.110 '-N', # Don't execute command111 '-T' # Don't allocate terminal.112 ]113 for port in ports_to_forward:114 forwarding_flags += ['-R', '%d:localhost:%d' % (port, port)]115 self._proxy = self._target.RunCommandPiped([],116 ssh_args=forwarding_flags,117 stderr=subprocess.PIPE)118 # Copy content_shell package to the device.119 device_package_path = \120 os.path.join('/data', os.path.basename(CONTENT_SHELL_PACKAGE_PATH))121 self._target.PutFile(122 os.path.join(build_path, CONTENT_SHELL_PACKAGE_PATH),123 device_package_path)124 pm_install = self._target.RunCommandPiped(125 ['pm', 'install', device_package_path],126 stderr=subprocess.PIPE)127 output = pm_install.stderr.readlines()128 pm_install.wait()129 if pm_install.returncode != 0:130 # Don't error out if the package already exists on the device.131 if len(output) != 1 or 'ErrAlreadyExists' not in output[0]:132 raise Exception('Failed to install content_shell: %s' % \133 '\n'.join(output))134 def run_command(self, *args, **kvargs):135 return self._target.RunCommandPiped(*args,136 stdin=subprocess.PIPE,137 stdout=subprocess.PIPE,138 stderr=subprocess.PIPE,139 **kvargs)140 def cleanup(self):141 if self._target:142 # TODO(sergeyu): Currently __init__() always starts Qemu, so we can143 # just shutdown it. Update this logic when reusing target devices144 # for multiple test runs.145 self._target.Shutdown()146 self._target = None147class FuchsiaPort(base.Port):148 port_name = 'fuchsia'149 SUPPORTED_VERSIONS = ('fuchsia',)150 FALLBACK_PATHS = {'fuchsia': ['fuchsia'] + linux.LinuxPort.latest_platform_fallback_path()}151 def __init__(self, host, port_name, **kwargs):152 super(FuchsiaPort, self).__init__(host, port_name, **kwargs)153 self._operating_system = 'fuchsia'154 self._version = 'fuchsia'155 # TODO(sergeyu): Add support for arm64.156 self._architecture = 'x86_64'157 self.server_process_constructor = FuchsiaServerProcess158 # Used to implement methods that depend on the host platform.159 self._host_port = factory.PortFactory(host).get(**kwargs)160 self._target_host = self.get_option('fuchsia_target')161 self._zircon_logger = None162 _import_fuchsia_runner()163 def _driver_class(self):164 return ChromiumFuchsiaDriver165 def _path_to_driver(self, target=None):166 return self._build_path_with_target(target, CONTENT_SHELL_PACKAGE_PATH)167 def __del__(self):168 if self._zircon_logger:169 self._zircon_logger.close()170 def setup_test_run(self):171 super(FuchsiaPort, self).setup_test_run()172 try:173 self._target_host = _TargetHost(174 self._build_path(), self.SERVER_PORTS)175 if self.get_option('zircon_logging'):176 self._zircon_logger = SubprocessOutputLogger(177 self._target_host.run_command(['dlog', '-f']),178 'Zircon')179 # Save fuchsia_target in _options, so it can be shared with other180 # workers.181 self._options.fuchsia_target = self._target_host182 except fuchsia_target.FuchsiaTargetException as e:183 _log.error('Failed to start qemu: %s.', str(e))184 return exit_codes.NO_DEVICES_EXIT_STATUS185 def clean_up_test_run(self):186 if self._target_host:187 self._target_host.cleanup()188 self._target_host = None189 def num_workers(self, requested_num_workers):190 # Run a single qemu instance.191 return min(MAX_WORKERS, requested_num_workers)192 def check_sys_deps(self, needs_http):193 # There is nothing to check here. If we have the package built we should194 # be able to run it.195 return exit_codes.OK_EXIT_STATUS196 def requires_http_server(self):197 """HTTP server is always required to avoid copying the tests to the VM.198 """199 return True200 def start_http_server(self, additional_dirs, number_of_drivers):201 additional_dirs[PERF_TEST_PATH_PREFIX] = self._perf_tests_dir()202 additional_dirs[LAYOUT_TEST_PATH_PREFIX] = self.layout_tests_dir()203 super(FuchsiaPort, self).start_http_server(204 additional_dirs, number_of_drivers)205 def path_to_apache(self):206 return self._host_port.path_to_apache()207 def path_to_apache_config_file(self):208 return self._host_port.path_to_apache_config_file()209 def default_smoke_test_only(self):210 return True211 def get_target_host(self):212 return self._target_host213class ChromiumFuchsiaDriver(driver.Driver):214 def __init__(self, port, worker_number, pixel_tests, no_timeout=False):215 super(ChromiumFuchsiaDriver, self).__init__(216 port, worker_number, pixel_tests, no_timeout)217 def _base_cmd_line(self):218 return ['run', 'content_shell']219 def _command_from_driver_input(self, driver_input):220 command = super(ChromiumFuchsiaDriver, self)._command_from_driver_input(221 driver_input)222 if command.startswith('/'):223 relative_test_filename = \224 os.path.relpath(command, self._port.layout_tests_dir())225 command = 'http://127.0.0.1:8000' + LAYOUT_TEST_PATH_PREFIX + \226 '/' + relative_test_filename227 return command228# Custom version of ServerProcess that runs processes on a remote device.229class FuchsiaServerProcess(server_process.ServerProcess):230 def __init__(self, port_obj, name, cmd, env=None,231 treat_no_data_as_crash=False, more_logging=False):232 super(FuchsiaServerProcess, self).__init__(233 port_obj, name, cmd, env, treat_no_data_as_crash, more_logging)234 def _start(self):235 if self._proc:236 raise ValueError('%s already running' % self._name)237 self._reset()238 # Fuchsia doesn't support stdin stream for packaged applications, so the239 # stdin stream for content_shell is routed through a separate TCP240 # socket. Open a local socket and then pass the address with the port as241 # --stdin-redirect parameter. content_shell will connect to this address242 # and will use that connection as its stdin stream.243 listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)244 listen_socket.bind(('127.0.0.1', 0))245 listen_socket.listen(1)246 stdin_port = listen_socket.getsockname()[1]247 command = ['%s=%s' % (k, v) for k, v in self._env.items()] + \248 self._cmd + \249 ['--no-sandbox', '--stdin-redirect=%s:%s' %250 (qemu_target.HOST_IP_ADDRESS, stdin_port)]251 proc = self._port.get_target_host().run_command(command)252 # Wait for incoming connection from content_shell.253 fd = listen_socket.fileno()254 read_fds, _, _ = select.select([fd], [], [], PROCESS_START_TIMEOUT)255 if fd not in read_fds:256 listen_socket.close()257 proc.kill()258 raise driver.DeviceFailure(259 'Timed out waiting connection from content_shell.')260 # Python's interfaces for sockets and pipes are different. To masquerade261 # the socket as a pipe dup() the file descriptor and pass it to262 # os.fdopen().263 stdin_socket, _ = listen_socket.accept()264 fd = stdin_socket.fileno() # pylint: disable=no-member265 stdin_pipe = os.fdopen(os.dup(fd), "w", 0)266 stdin_socket.close()267 proc.stdin.close()268 proc.stdin = stdin_pipe...
main.py
Source:main.py
1# -*- coding: utf-8 -*-2import os3import re4import time5import pexpect, sys6class Android_app_test(object):7 def __init__(self, num):8 self.data = []9 self.num = num10 # self.app = 'com.tencent.mobileqq'11 # self.activity = 'com.tencent.mobileqq.activity.SplashActivity'12 self.local_app = 'GWM_2021_07_08.apk'13 self.device = 'RKW8XSGQAUCIAUTS'14 self.app = 'com.gwm.thailand'15 self.activity = 'com.beans.gwm.ui.MainActivity'16 self.path_to_apk = '/data/local/tmp'17 def check_devices(self):18 '''æ£æ¥è®¾å¤æ¯å¦è¿æ¥æåï¼å¦ææåè¿åTrueï¼å¦åè¿åFalse'''19 try:20 deviceInfo = os.popen('adb devices').read()21 print('deviceInfo:', deviceInfo, deviceInfo.split('\n')[1])22 if 'device' in deviceInfo.split('\n')[1]:23 os.popen('adb -s %s shell' % self.device)24 print('=' * 21, 'å·²è¿æ¥è®¾å¤,å¼å§æµè¯', '=' * 21)25 print(self.deviceInfo())26 return True27 else:28 return False29 except Exception as e:30 print(e)31 def check_install(self):32 try:33 applist = os.popen('adb -s %s shell pm list packages' % self.device).read()34 # print('applist:\n', applist)35 for string_line in applist.split('\n'):36 for string_str in string_line.split(':'):37 # print('*' * 10, string_str, '*' * 10)38 if 'com.gwm.thailand' == string_str:39 print('=' * 21, 'apk is installed before', '=' * 21)40 return True41 return False42 except Exception as e:43 print(e)44 def deviceInfo(self):45 '''è·å设å¤åºç¡ä¿¡æ¯(å¦ï¼ååãåå·ãç³»ç»çæ¬)'''46 deviceName = os.popen('adb -s %s shell getprop ro.product.model' % self.device).read()47 platformVersion = os.popen('adb -s %s shell getprop ro.build.version.release' % self.device).read()48 producer = os.popen('adb -s %s shell getprop ro.product.brand' % self.device).read()49 return "ææºåå·ï¼%s %sï¼ç³»ç»çæ¬ï¼Android %s" % (50 producer.replace('\n', ''), deviceName.replace('\n', ''), platformVersion.replace('\n', ''))51 def start_adb(self):52 '''è¿è¡adbå½ä»¤ï¼å¹¶è®°å½å¯å¨èæ¶'''53 print('adb -s %s shell am start -W %s/%s' % (self.device, self.app, self.activity))54 start = 'adb -s %s shell am start -W %s/%s' % (self.device, self.app, self.activity)55 # data = re.findall(r'.*ThisTime: (.*?)TotalTime:(.*?)WaitTime: (.*?)Complete',56 # os.popen(start).read().replace('\n', ''))57 data = re.findall(r'.*TotalTime:(.*?)WaitTime: (.*?)Complete',58 os.popen(start).read().replace('\n', ''))59 if len(data) == 0:60 print("adbå½ä»¤æ§è¡åºéï¼æ°æ®ä¸ºç©º")61 else:62 self.data.append(int(data[0][0]))63 # print(type(data),data)64 return data65 def stop_adb(self):66 '''ç»æç¨åºè¿è¡'''67 stop = 'adb -s %s shell am force-stop %s' % (self.device, self.app)68 os.popen(stop)69 def app_install(self):70 try:71 # install = 'adb -s %s install -g -r %s' % (self.device, self.local_app)72 # print('install:', install)73 # os.popen(install)74 adb_push = 'adb -s {0} push {1} {2}/{3}'.format(self.device, self.local_app, self.path_to_apk,75 self.local_app)76 print('adb_push:',adb_push)77 push_response = os.popen(adb_push)78 # print('push_response:', push_response.read())79 pm_install = 'adb -s {0} shell pm install -r {1}/{2}'.format(self.device, self.path_to_apk, self.local_app)80 print('pm_install:', pm_install)81 install_response = os.popen(pm_install)82 time.sleep(3)83 # print('pm_install:', install_response.read())84 except Exception as e:85 print('-' * 10, e, '-' * 10)86 # pexpect.run\pexpect.spawn only for linux87 # print('Installing apk: {0} for device: {1}'.format(self.path_to_apk, self.device))88 # file_name = os.path.basename(self.path_to_apk)89 # print('adb -s {0} push {1} {2}/{3}'.format(self.device, self.local_app, self.path_to_apk, self.local_app))90 # pexpect.run('adb -s {0} push {1} {2}/{3}'.format(self.device, self.local_app,self.path_to_apk, self.local_app))91 # p = pexpect.spawn('adb -s {0} shell'.format(self.device))92 # p.logfile = sys.stdout93 # p.expect('.*shell@.*', 20)94 # p.sendline('pm install {0}/{1}'.format(self.path_to_apk,self.local_app))95 # index = p.expect(['Success', '.*shell@.*'], 120)96 # p.sendline('rm {0}/{1}'.format(self.path_to_apk,self.local_app))97 def app_uninstall(self):98 uninstall = 'adb -s %s uninstall %s' % (self.device, self.app)99 time.sleep(10)100 print('uninstall:', uninstall)101 os.popen(uninstall)102 def run_test_first(self):103 '''app å®è£
åé¦æ¬¡å¯å¨èæ¶æµè¯'''104 self.data.clear()105 if self.check_install() == True:106 self.app_uninstall()107 if self.check_devices() == True:108 self.stop_adb()109 for i in range(self.num):110 print('=' * 20, 'å®è£
åé¦æ¬¡å¨æµè¯ï¼ç¬¬%d次è¿è¡' % (i + 1), '=' * 20)111 self.stop_adb()112 self.app_install()113 time.sleep(3)114 test = self.start_adb()115 print("run_test_cold:", type(test), test)116 # print("ThisTime:%s,TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1], test[0][2]))117 print("TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1]))118 time.sleep(3)119 if i < self.num - 1:120 self.app_uninstall()121 self.stop_adb()122 print('\nå·å¯å¨%s次平åèæ¶ä¸ºï¼%s' % (len(self.data), sum(self.data) / len(self.data)))123 else:124 print("æªè¿æ¥å®å设å¤,请è¿æ¥è®¾å¤ï¼3ç§åéè¯ï¼")125 while True:126 time.sleep(3)127 self.run_test_cold()128 def run_test_cold(self):129 '''app å·å¯å¨èæ¶æµè¯'''130 self.data.clear()131 if self.check_devices() == True:132 self.stop_adb()133 for i in range(self.num):134 print('=' * 20, 'å·å¯å¨æµè¯ï¼ç¬¬%d次è¿è¡' % (i + 1), '=' * 20)135 self.stop_adb()136 self.app_install()137 time.sleep(3)138 test = self.start_adb()139 print("run_test_cold:", type(test), test)140 # print("ThisTime:%s,TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1], test[0][2]))141 print("TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1]))142 time.sleep(3)143 self.stop_adb()144 print('\nå·å¯å¨%s次平åèæ¶ä¸ºï¼%s' % (len(self.data), sum(self.data) / len(self.data)))145 else:146 print("æªè¿æ¥å®å设å¤,请è¿æ¥è®¾å¤ï¼3ç§åéè¯ï¼")147 while True:148 time.sleep(3)149 self.run_test_cold()150 def run_test_hot(self):151 '''app çå¯å¨èæ¶æµè¯'''152 self.data.clear()153 if self.check_devices() == True:154 os.popen('adb -s %s shell am start -W %s/%s' % (self.device, self.app, self.activity))155 time.sleep(3)156 for i in range(self.num):157 print('=' * 20, 'çå¯å¨æµè¯ï¼ç¬¬%d次è¿è¡' % (i + 1), '=' * 20)158 os.popen('adb -s %s shell input keyevent 3' % self.device)159 time.sleep(3)160 test = self.start_adb()161 time.sleep(3)162 # print("ThisTime:%s,TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1], test[0][2]))163 print("TotalTime:%s,WaitTime:%s" % (test[0][0], test[0][1]))164 self.stop_adb()165 print('\nçå¯å¨%s次平åèæ¶ä¸ºï¼%s' % (len(self.data), sum(self.data) / len(self.data)))166 else:167 print("æªè¿æ¥å®å设å¤,请è¿æ¥è®¾å¤ï¼3ç§åéè¯ï¼")168 while True:169 time.sleep(3)170 self.run_test_hot()171if __name__ == '__main__':172 apptest = Android_app_test(1)173 apptest.check_devices()174 print("---check_devices done---")175 if apptest.check_install() == True:176 apptest.app_uninstall()177 print("---app_uninstall done---")178 apptest.app_install()179 print("---app_install done---")180 # apptest.run_test_first()181 # apptest.run_test_cold()...
__init__.py
Source:__init__.py
1from api import os2from api.os import path3dockerfile_tpl = """4FROM gplane/pnpm:{version}5WORKDIR /app6{pm_copy}7{inject_prepare}8{pm_install}9COPY . .10{inject}11{pm_start}12ENTRYPOINT ["docker-entrypoint.sh"]13"""14dotfile_config_tpl = """15location ~ /\\. {16 deny all;17 access_log off;18 log_not_found off;19 return 404;20}21"""22cache_config_tpl = """23location ~* \\.(?:css|js)$ {24 access_log off;25 log_not_found off;26 add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";27}28location ~* \\.(?:jpg|jpeg|gif|png|ico|xml|webp|eot|woff|woff2|ttf|svg|otf)$ {29 access_log off;30 log_not_found off;31 expires 60m;32 add_header Cache-Control "public";33}34"""35try_file_config_tpl = """36location / {37 try_files \\$uri \\$uri/index.html \\$uri/ /;38}39"""40nginx_config_tpl = """41user nginx;42worker_processes auto;43error_log /var/log/nginx/error.log warn;44pid /var/run/nginx.pid;45events {{46 worker_connections 1024;47}}48include /etc/nginx/conf.d/*-root.conf;49http {{50 server_tokens off;51 include /etc/nginx/mime.types;52 default_type application/octet-stream;53 keepalive_timeout 65;54 sendfile on;55 tcp_nopush on;56 port_in_redirect off;57 server {{58 listen 80;59 charset utf-8;60 server_name _;61 real_ip_header x-forwarded-for;62 set_real_ip_from 0.0.0.0/0;63 real_ip_recursive on;64 root /usr/share/nginx/html;65 index {nginx_index};66 {nginx_dotfile_config}67 {nginx_cache_config}68 {nginx_try_file_config}69 include /etc/nginx/conf.d/*-server.conf;70 }}71 include /etc/nginx/conf.d/*-http.conf;72}}73"""74copy_nginx_config_tpl = """75COPY --chown=nginx:nginx ./.tilt/nginx /etc/nginx/conf.d76"""77dockerfile_static_tpl = """78FROM gplane/pnpm:{version} as builder79WORKDIR /app80{pm_copy}81{inject_prepare}82{pm_install}83COPY . .84{inject_prebuild}85{pm_build}86{inject}87FROM nginx:{nginx_version}88RUN cat > /etc/nginx/nginx.conf <<EOF89{nginx_config}90EOF91{copy_nginx_config}92RUN rm -f /usr/share/nginx/html/*93COPY --chown=nginx:nginx --from=builder /app/{nginx_root} /usr/share/nginx/html94{nginx_inject}95"""96def nodejs_template(97 version='alpine', # type: str98 inject_prepare=[], # type: list[str]99 inject=[], # type: list[str]100 cmd=[] # type: list[str]101):102 pm_copy = ''103 pm_install = ''104 pm_start = 'CMD ["node", "index.js"]'105 if os.path.exists('./pnpm-lock.yaml'):106 pm_copy = 'COPY package.json pnpm-lock.yaml ./'107 pm_install = 'RUN pnpm install --prod --frozen-lockfile'108 pm_start = 'CMD ["pnpm", "run", "start"]'109 elif os.path.exists('./yarn.lock'):110 pm_copy = 'COPY package.json yarn.lock ./'111 pm_install = 'RUN yarn install --production --frozen-lockfile && yarn cache clean'112 pm_start = 'CMD ["yarn", "run", "start"]'113 elif os.path.exists('./package.json'):114 pm_copy = 'COPY package*.json ./'115 pm_install = 'RUN npm ci --only=production && npm cache clean --force'116 pm_start = 'CMD ["npm", "run", "start"]'117 if len(cmd) > 0:118 pm_start = 'CMD ["{}"]'.format('", "'.join(cmd))119 dockerfile = dockerfile_tpl.format(120 version=version,121 pm_copy=pm_copy,122 inject_prepare='\n'.join(inject_prepare),123 pm_install=pm_install,124 pm_start=pm_start,125 inject='\n'.join(inject),126 cmd=cmd127 )128 return dockerfile129def nodejs_static_template(130 version='alpine', # type: str131 inject_prepare=[], # type: list[str]132 inject_prebuild=[], # type: list[str]133 inject=[], # type: list[str]134 # nginx135 nginx_version='alpine', # type: str136 nginx_root='public', # type: str137 nginx_index='index.html', # type: str138 nginx_dotfile=True, # type: bool139 nginx_cache=True, # type: bool140 nginx_try_file=True, # type: bool141 nginx_inject=[] # type: list[str]142):143 pm_copy = ''144 pm_install = ''145 pm_build = ''146 if os.path.exists('./pnpm-lock.yaml'):147 pm_copy = 'COPY package.json pnpm-lock.yaml ./'148 pm_install = 'RUN pnpm install --frozen-lockfile'149 pm_build = 'RUN pnpm run build'150 elif os.path.exists('./yarn.lock'):151 pm_copy = 'COPY package.json yarn.lock ./'152 pm_install = 'RUN yarn install --frozen-lockfile && yarn cache clean'153 pm_build = 'RUN yarn run build'154 elif os.path.exists('./package.json'):155 pm_copy = 'COPY package*.json ./'156 pm_install = 'RUN npm ci && npm cache clean --force'157 pm_build = 'RUN npm run build'158 nginx_config = nginx_config_tpl.format(159 nginx_index=nginx_index,160 nginx_dotfile_config=dotfile_config_tpl if nginx_dotfile else '',161 nginx_cache_config=cache_config_tpl if nginx_cache else '',162 nginx_try_file_config=try_file_config_tpl if nginx_try_file else ''163 )164 dockerfile = dockerfile_static_tpl.format(165 version=version,166 pm_copy=pm_copy,167 inject_prepare='\n'.join(inject_prepare),168 pm_install=pm_install,169 inject_prebuild='\n'.join(inject_prebuild),170 pm_build=pm_build,171 inject='\n'.join(inject),172 # nginx173 nginx_version=nginx_version,174 nginx_config=nginx_config,175 copy_nginx_config=copy_nginx_config_tpl if os.path.exists('./.tilt/nginx') else '',176 nginx_root=nginx_root,177 nginx_inject='\n'.join(nginx_inject)178 )...
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!!