Best JavaScript code snippet using wpt
test_make.py
Source:test_make.py
1# -*- coding: utf-8 -*-2# Copyright 2008-2015 Canonical3#4# This program is free software: you can redistribute it and/or modify5# it under the terms of the GNU Affero General Public License as6# published by the Free Software Foundation, either version 3 of the7# License, or (at your option) any later version.8#9# This program is distributed in the hope that it will be useful,10# but WITHOUT ANY WARRANTY; without even the implied warranty of11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12# GNU Affero General Public License for more details.13#14# You should have received a copy of the GNU Affero General Public License15# along with this program. If not, see <http://www.gnu.org/licenses/>.16#17# For further info, check http://launchpad.net/filesync-server18"""Test making nodes."""19import uuid20import zlib21from StringIO import StringIO22from twisted.internet import threads, defer23from backends.filesync.data import errors24from ubuntuone.storageprotocol import request, volumes25from ubuntuone.storage.server.testing.testcase import TestWithDatabase26from ubuntuone.storageprotocol.content_hash import content_hash_factory, crc3227NO_CONTENT_HASH = ""28class TestMakeFile(TestWithDatabase):29 """Test make_file command."""30 def test_mkfile(self):31 """Create a file."""32 def auth(client):33 d = client.dummy_authenticate("open sesame")34 d.addCallbacks(lambda r: client.get_root(), client.test_fail)35 d.addCallbacks(36 lambda r: client.make_file(request.ROOT, r, "hola"),37 client.test_fail)38 d.addCallbacks(client.test_done, client.test_fail)39 return self.callback_test(auth)40 def build_mime_test(filename, file_mime):41 """create test cases for mime type checking."""42 def test_mkfile_mime_type(self):43 """Create a file."""44 def auth(client):45 def check_file(result):46 def _check_file():47 try:48 file = self.usr0.get_node(result.new_id)49 except errors.DoesNotExist:50 raise ValueError("storage object is missing")51 assert(file.mimetype == file_mime)52 d = threads.deferToThread(_check_file)53 return d54 d = client.dummy_authenticate("open sesame")55 d.addCallbacks(lambda r: client.get_root(), client.test_fail)56 d.addCallbacks(57 lambda r: client.make_file(request.ROOT, r, filename),58 client.test_fail)59 d.addCallback(check_file)60 d.addCallbacks(client.test_done, client.test_fail)61 return self.callback_test(auth)62 return test_mkfile_mime_type63 test_mkfile_mime1 = build_mime_test("image.png", "image/png")64 test_mkfile_mime2 = build_mime_test("noextension", None)65 test_mkfile_mime3 = build_mime_test("music.mp3", "audio/mpeg")66 test_mkfile_mime4 = build_mime_test("document.doc", "application/msword")67 test_mkfile_mime5 = build_mime_test("test.txt", "text/plain")68 test_mkfile_mime6 = build_mime_test("package.zip", "application/zip")69 del build_mime_test70 def test_mkfile_unicode(self):71 """Create a file."""72 def auth(client):73 d = client.dummy_authenticate("open sesame")74 d.addCallbacks(lambda r: client.get_root(), client.test_fail)75 d.addCallbacks(76 lambda r: client.make_file(request.ROOT, r, u"á"),77 client.test_fail)78 d.addCallbacks(client.test_done, client.test_fail)79 return self.callback_test(auth)80 def test_mkfile2(self):81 """Create a file in a sub directory."""82 def auth(client):83 d = client.dummy_authenticate("open sesame")84 d.addCallbacks(lambda r: client.get_root(), client.test_fail)85 d.addCallbacks(86 lambda r: client.make_dir(request.ROOT, r, "hola"),87 client.test_fail)88 d.addCallbacks(89 lambda r: client.make_file(request.ROOT, r.new_id, "hola"),90 client.test_fail)91 d.addCallbacks(client.test_done, client.test_fail)92 return self.callback_test(auth)93 def test_mkfile3(self):94 """Create two files with different names."""95 def auth(client):96 d = client.dummy_authenticate("open sesame")97 d.addCallbacks(lambda r: client.get_root(), client.test_fail)98 d.addCallbacks(99 lambda r: client.make_file(request.ROOT, r, "hola"),100 client.test_fail)101 d.addCallbacks(lambda r: client.get_root(), client.test_fail)102 d.addCallbacks(103 lambda r: client.make_file(request.ROOT, r, "chau"),104 client.test_fail)105 d.addCallbacks(client.test_done, client.test_fail)106 return self.callback_test(auth)107 def test_mkfile_on_file(self):108 """Create a file on a file"""109 def auth(client):110 d = client.dummy_authenticate("open sesame")111 d.addCallbacks(lambda r: client.get_root(), client.test_fail)112 d.addCallbacks(113 lambda r: client.make_file(request.ROOT, r, "hola"),114 client.test_fail)115 d.addCallbacks(116 lambda r: client.make_file(request.ROOT, r.new_id, "hola"),117 client.test_fail)118 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))119 return self.callback_test(auth)120 def test_mkdir_on_file(self):121 """Create a dir on a file and fail."""122 def auth(client):123 d = client.dummy_authenticate("open sesame")124 d.addCallbacks(lambda r: client.get_root(), client.test_fail)125 d.addCallbacks(126 lambda r: client.make_file(request.ROOT, r, "hola"),127 client.test_fail)128 d.addCallbacks(129 lambda r: client.make_dir(request.ROOT, r.new_id, "hola"),130 client.test_fail)131 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))132 return self.callback_test(auth)133 def test_mkfile_already_exists_empty(self):134 """Create a file on a file that already exists."""135 def auth(client):136 d = client.dummy_authenticate("open sesame")137 d.addCallbacks(lambda r: client.get_root(), client.test_fail)138 d.addCallbacks(139 lambda r: client.make_file(request.ROOT, r, "hola"),140 client.test_fail)141 d.addCallbacks(lambda r: client.get_root(), client.test_fail)142 d.addCallbacks(143 lambda r: client.make_file(request.ROOT, r, "hola"),144 client.test_fail)145 d.addCallbacks(146 lambda x: client.test_done("ok"), client.test_fail)147 return self.callback_test(auth)148 def test_mkfile_already_exists_content(self):149 """Create a file on a file that already exists and have content."""150 data = "*" * 100151 deflated_data = zlib.compress(data)152 hash_object = content_hash_factory()153 hash_object.update(data)154 hash_value = hash_object.content_hash()155 crc32_value = crc32(data)156 size = len(data)157 deflated_size = len(deflated_data)158 def auth(client):159 d = client.dummy_authenticate("open sesame")160 d.addCallback(lambda r: client.get_root())161 d.addCallback(self.save_req, "root")162 d.addCallback(lambda r: client.make_file(request.ROOT, r, "hola"))163 d.addCallback(lambda req: client.put_content(request.ROOT,164 req.new_id, NO_CONTENT_HASH, hash_value, crc32_value,165 size, deflated_size, StringIO(deflated_data)))166 d.addCallback(lambda r: client.make_file(request.ROOT,167 self._state.root, "hola"))168 d.addCallbacks(169 lambda x: client.test_done("ok"), client.test_fail)170 return self.callback_test(auth)171 def test_mkfile_auth_required(self):172 """Require authentication for make_file."""173 def auth(client):174 d = client.make_file(request.ROOT, uuid.uuid4(), "hola")175 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))176 return self.callback_test(auth)177 def test_mkfile_doesnt_exists(self):178 """Make a file with a parent that does not exists. Fail."""179 def auth(client):180 d = client.dummy_authenticate("open sesame")181 d.addCallbacks(lambda r: client.get_root(), client.test_fail)182 d.addCallbacks(183 lambda r: client.make_file(request.ROOT, uuid.uuid4(), "hola"),184 client.test_fail)185 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))186 return self.callback_test(auth)187 def test_mkfile_doesnt_exist_not_uuid(self):188 """Create a file with a parent that is not a valid uuid."""189 def auth(client):190 d = client.dummy_authenticate("open sesame")191 d.addCallbacks(lambda r: client.get_root(), client.test_fail)192 d.addCallbacks(193 lambda r: client.make_file(194 request.ROOT, 'idontexist_imnotanuuid', "hola"),195 client.test_fail)196 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))197 return self.callback_test(auth)198 def test_mkfile_generations(self):199 """Create a file and receive new generation."""200 @defer.inlineCallbacks201 def test(client):202 """Test."""203 yield client.dummy_authenticate("open sesame")204 req = yield client.list_volumes()205 root = [v for v in req.volumes206 if isinstance(v, volumes.RootVolume)][0]207 req = yield client.make_file(request.ROOT, root.node_id, "hola")208 self.assertEqual(req.new_generation, root.generation + 1)209 return self.callback_test(test, add_default_callbacks=True)210class TestMakeDir(TestWithDatabase):211 """Test make_dir command."""212 def test_mkdir(self):213 """Create a directory."""214 def auth(client):215 d = client.dummy_authenticate("open sesame")216 d.addCallbacks(lambda r: client.get_root(), client.test_fail)217 d.addCallbacks(218 lambda r: client.make_dir(request.ROOT, r, "hola"),219 client.test_fail)220 d.addCallbacks(client.test_done, client.test_fail)221 return self.callback_test(auth)222 def test_mkdir_unicode(self):223 """Create a directory."""224 def auth(client):225 d = client.dummy_authenticate("open sesame")226 d.addCallbacks(lambda r: client.get_root(), client.test_fail)227 d.addCallbacks(228 lambda r: client.make_dir(request.ROOT, r, u"¶á"),229 client.test_fail)230 d.addCallbacks(client.test_done, client.test_fail)231 return self.callback_test(auth)232 def test_mkdir_invalid_character(self):233 """Try to create a dir with invalid characters and fail."""234 def auth(client):235 d = client.dummy_authenticate("open sesame")236 d.addCallbacks(lambda r: client.get_root(), client.test_fail)237 d.addCallbacks(238 lambda r: client.make_dir(request.ROOT, r, "hola / "),239 client.test_fail)240 def check(failure):241 """Checks the error returned."""242 self.assertIsInstance(failure.value,243 request.StorageRequestError)244 client.test_done(True)245 d.addCallbacks(client.test_fail, check)246 return self.callback_test(auth)247 def test_mkdir_unicode_surrogates(self):248 """Try to create a dir with unicode data points that are not chars."""249 @defer.inlineCallbacks250 def test(client):251 """Test."""252 yield client.dummy_authenticate("open sesame")253 root = yield client.get_root()254 d = client.make_dir(request.ROOT, root, u"surrogate \udad6")255 res = yield self.assertFailure(d, request.StorageRequestError)256 self.assertEqual(str(res), "INVALID_FILENAME")257 return self.callback_test(test, add_default_callbacks=True)258 def test_mkdir2(self):259 """Create a directory on a sub directory."""260 def auth(client):261 d = client.dummy_authenticate("open sesame")262 d.addCallbacks(lambda r: client.get_root(), client.test_fail)263 d.addCallbacks(264 lambda r: client.make_dir(request.ROOT, r, "hola"),265 client.test_fail)266 d.addCallbacks(267 lambda r: client.make_dir(request.ROOT, r.new_id, "hola"),268 client.test_fail)269 d.addCallbacks(client.test_done, client.test_fail)270 return self.callback_test(auth)271 def test_mkdir3(self):272 """Create two directories."""273 def auth(client):274 d = client.dummy_authenticate("open sesame")275 d.addCallbacks(lambda r: client.get_root(), client.test_fail)276 d.addCallbacks(277 lambda r: client.make_dir(request.ROOT, r, "hola"),278 client.test_fail)279 d.addCallbacks(lambda r: client.get_root(), client.test_fail)280 d.addCallbacks(281 lambda r: client.make_dir(request.ROOT, r, "chau"),282 client.test_fail)283 d.addCallbacks(client.test_done, client.test_fail)284 return self.callback_test(auth)285 def test_mkdir_already_exists(self):286 """Create a directory with a name that already exists."""287 def auth(client):288 d = client.dummy_authenticate("open sesame")289 d.addCallback(lambda r: client.get_root())290 d.addCallback(self.save_req, "root")291 d.addCallback(lambda r: client.make_dir(request.ROOT, r, "hola"))292 d.addCallback(self.save_req, "dir")293 d.addCallback(lambda r: client.make_dir(request.ROOT,294 self._state.root, "hola"))295 def check(req):296 self.assertEqual(req.new_id, self._state.dir.new_id)297 d.addCallback(check)298 d.addCallbacks(client.test_done, client.test_fail)299 return self.callback_test(auth)300 def test_mkdir_auth_required(self):301 """Make dir requires authentication."""302 def auth(client):303 d = client.make_dir(request.ROOT, uuid.uuid4(), "hola")304 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))305 return self.callback_test(auth)306 def test_mkdir_doesnt_exists(self):307 """Make a directory on a node that does not exists."""308 def auth(client):309 d = client.dummy_authenticate("open sesame")310 d.addCallbacks(lambda r: client.get_root(), client.test_fail)311 d.addCallbacks(312 lambda r: client.make_dir(request.ROOT, uuid.uuid4(), "hola"),313 client.test_fail)314 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))315 return self.callback_test(auth)316 def test_mkdir_doesnt_exist_not_uuid(self):317 """Make a directory on a node that is not an uuid."""318 def auth(client):319 d = client.dummy_authenticate("open sesame")320 d.addCallbacks(lambda r: client.get_root(), client.test_fail)321 d.addCallbacks(322 lambda r: client.make_dir(323 request.ROOT, 'idontexist_imnotanuuid', "hola"),324 client.test_fail)325 d.addCallbacks(client.test_fail, lambda x: client.test_done("ok"))326 return self.callback_test(auth)327 def test_mkdir_generations(self):328 """Create a dir and receive new generation."""329 @defer.inlineCallbacks330 def test(client):331 """Test."""332 yield client.dummy_authenticate("open sesame")333 req = yield client.list_volumes()334 root = [v for v in req.volumes335 if isinstance(v, volumes.RootVolume)][0]336 req = yield client.make_dir(request.ROOT, root.node_id, "hola")337 self.assertEqual(req.new_generation, root.generation + 1)...
prog_rpi.py
Source:prog_rpi.py
1# System imports2import RPi.GPIO as GPIO3import time4import sys5import os6from colorama import Fore7import serial8from serial.tools import list_ports9import usb.core10# Local imports11sys.path.append("rpi-lib")12from sp_io import *13from adc import *14from shift_reg import *15from sp_serial import *16from oled import *17GPIO.setwarnings(False)18GPIO.setmode(GPIO.BCM)19RST = 1720EXT = 2321dut_type = None22# Map between IO position on Sea-Picro and location in shift reg chain23IO_TO_SR_MAP = [15, 16, 17, 18, 19, 20, 21, 22, 7, 8, 14, 0, 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13]24# IO list of SP in same order as above25SP_PIN_MAP = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D21", "D23", "D20", "D22", "D26", "D27", "D28", "D29", "D12", "D13", "D14", "D15", "D16"]26# USB strings27RPI_VID = 0x2e8a28RPI_PID = 0x000329CPY_VID = 0x6a6a30CPY_PID = 0x535031global fail_str32fail_str = ""33def flash_circuitpython():34 ''' Flashes circuitpython firmware. '''35 global fail_str36 test_fail = True37 found_rpi = False38 attempt_counter = 039 # Spinlock until RPi bootloader is found40 while found_rpi == False:41 print(f"{Fore.BLUE}Searching for RP2040 bootloader")42 dev = usb.core.find(find_all=1)43 for cfg in dev:44 if cfg.idVendor == RPI_VID and cfg.idProduct == RPI_PID:45 found_rpi = True46 time.sleep(1)47 attempt_counter = attempt_counter + 148 if attempt_counter > 5:49 print(f'{Fore.RED}TIMEOUT TRYING TO FIND BOOTLOADER!')50 fail_str = "CPY"51 test_fail = True52 break53 if found_rpi:54 print(f"{Fore.BLUE}Bootloader found, copying CircuitPython")55 oled_write("Flashing CPY")56 time.sleep(3)57 retval = os.system("cp circuitpy-sea-picro.uf2 /media/pi/RPI-RP2")58 if retval != 0:59 print(f'{Fore.RED}FAILED TO FLASH CIRCUITPYTHON!')60 fail_str = "CPY"61 test_fail = True62 else:63 test_fail = False64 return test_fail65def flash_firmware():66 ''' Flashes test firmware. '''67 global fail_str68 test_fail = True69 found_cpy = False70 attempt_counter = 071 # Spinlock until circuitpython is found72 while found_cpy == False:73 print(f"{Fore.BLUE}Searching for Circuitpython")74 dev = usb.core.find(find_all=1)75 for cfg in dev:76 if cfg.idVendor == CPY_VID and cfg.idProduct == CPY_PID:77 found_cpy = True78 time.sleep(1)79 80 attempt_counter = attempt_counter + 181 if attempt_counter > 15:82 print(f'{Fore.RED}TIMEOUT TRYING TO FIND CIRCUITPYTHON!')83 fail_str = "FW"84 test_fail = True85 break86 if found_cpy:87 print(f"{Fore.BLUE}CircuitPython found, copying test firmware")88 oled_write("Flashing Test FW")89 time.sleep(5)90 retval = os.system("cp -rf circuitpy-files/* /media/pi/CIRCUITPY")91 if retval != 0:92 print(f'{Fore.RED}FAILED TO FLASH TEST FIRMWARE!')93 fail_str = "FW"94 test_fail = True95 else:96 test_fail = False97 sp_reset()98 time.sleep(3)99 return test_fail100def test_ident():101 # Check we have the right /dev/ttyACM port102 global fail_str103 test_fail = True104 send_dut_string("ident")105 ret_str = get_dut_string()106 if ret_str == "ident = Sea-Picro!":107 print(f'{Fore.BLUE}IDENT passed')108 test_fail = False109 else:110 print(f'{Fore.RED}IDENT Failed, possibly wrong /dev/ttyACM port')111 fail_str = "IDENT"112 test_fail = True113 return test_fail114def test_vbus():115 # Check VBUS detection116 global fail_str117 test_fail = True118 send_dut_string("vbus_test")119 ret_str = get_dut_string()120 if ret_str == "vbus = high":121 print(f'{Fore.BLUE}VBUS detect passed')122 test_fail = False123 else:124 print(f'{Fore.RED}VBUS detect failed')125 fail_str = "VBUS"126 return test_fail127def test_led():128 # RGB test time129 global fail_str130 test_fail = True131 print(f'{Fore.YELLOW}Monitor LEDs please')132 send_dut_string("led_rgb")133 134 print(f'{Fore.YELLOW}Did LEDs cycle R/G/B? YES / NO {Fore.WHITE}')135 oled_write("LEDs R/G/B?")136 time.sleep(1) # delay long enough that the operator has seen all colours work137 while True:138 if (not io_read(SW_YES)):139 print(f'{Fore.BLUE}RGB LEDs passed')140 test_fail = False141 send_dut_string("led_off")142 time.sleep(0.1)143 break144 if (not io_read(SW_NO)):145 print(f'{Fore.RED}RGB LEDs failed')146 send_dut_string("led_off")147 time.sleep(0.1)148 fail_str = "RGB"149 break150 return test_fail151def test_cc():152 global fail_str153 cc_val = adc_read("CC")154 if cc_val < 3000:155 print(f'{Fore.BLUE}CC pin passed')156 return False157 else:158 print(f'{Fore.RED}CC pin failed')159 fail_str = "CC"160 return True161def test_io(model):162 global fail_str163 test_fail = False164 for pos in range(0, model):165 shift_out((1 << IO_TO_SR_MAP[pos]))166 send_dut_string("io_test")167 ret_str = get_dut_string()168 array = ret_str[1:-1].split(", ") # Convert to array of strings "True", "False"169 key_fail = False # Used to flag if a key passes it's test or not170 # Loop through array and check val = False unless index == pos171 for index in range(0,model):172 # Case where we expect a key to be pressed173 if index == pos:174 if array[index] == "True":175 pass176 else:177 print(f'{Fore.RED}{SP_PIN_MAP[pos]}: IO {SP_PIN_MAP[index]} was NOT pressed')178 key_fail = True179 test_fail = True180 # Case where we do not expect a key to be pressed181 elif index != pos:182 if array[index] == "False":183 pass184 else:185 print(f'{Fore.RED}{SP_PIN_MAP[pos]}: IO {SP_PIN_MAP[index]} WAS pressed')186 key_fail = True187 test_fail = True188 if not key_fail:189 print(f'{Fore.BLUE}{SP_PIN_MAP[pos]}: IO {SP_PIN_MAP[pos]} passed')190 if test_fail:191 fail_str = "IO"192 return test_fail193def test_dut(model):194 test_fail = False195 oled_write("Testing DUT")196 # Don't continue testing if we can't ident properly197 if test_ident():198 return True199 test_fail = test_fail | test_vbus()200 test_fail = test_fail | test_cc()201 test_fail = test_fail | test_io(model)202 test_fail = test_fail | test_led()203 return test_fail 204# Init all the things!205io_init()206adc_init()207shift_reg_init()208oled_init()209time.sleep(1)210retest = False211test_only = False212# Super loop time213while True:214 if not retest:215 print(f"{Fore.YELLOW}Press YES to begin test!")216 oled_write("Begin Test?", size=20)217 retest = False218 while True:219 # try:220 if (not io_read(SW_YES) or test_only):221 time.sleep(0.1) # Shitty debounce222 led_reset()223 print(f"{Fore.BLUE}Beginning test!")224 test_fail = False225 # Configure tester for EXT or RST226 if (not io_read(SW_EXT_RST)):227 print(f"{Fore.BLUE}Sea-Picro EXT selected")228 oled_write("Testing EXT")229 dut_type = EXT230 else:231 print(f"{Fore.BLUE}Sea-Picro RST selected")232 oled_write("Testing RST")233 dut_type = RST234 # Check if we need to flash cpy or not235 if (not io_read(SW_BOOTLD) and (test_fail == False) and not test_only):236 # Need to reset board to throw into bootloader237 # We also check the reset circuit is working correctly here238 test_fail = sp_bootloader()239 if test_fail == True:240 fail_str = "RESET"241 else:242 test_fail = flash_circuitpython()243 # Check if we need to flash firmare / test code244 if (not io_read(SW_FIRMWARE) and (test_fail == False) and not test_only):245 test_fail = flash_firmware()246 # Check if we need to test the DUT247 if (not io_read(SW_TEST) and (test_fail == False)):248 sp_reset() # Need to power cut here249 test_fail = serial_init()250 if test_fail == True:251 fail_str = "CDC2"252 # Need to power cut here253 else:254 test_fail = test_dut(dut_type)255 256 # If we are just doing the final test, check the reset circuit257 if (io_read(SW_BOOTLD) and io_read(SW_FIRMWARE) and (test_fail == False)) or (test_only and test_fail == False):258 test_fail = sp_bootloader()259 if test_fail == True:260 fail_str = "RESET"261 # Need to power cut here262 test_only = False263 # Advise user on how everything went264 if test_fail == False:265 print(f'{Fore.GREEN}ALL STEPS PASSED!!!')266 print(f"{Fore.YELLOW}Press YES for full test, NO for final test")267 oled_write_dual("Test Passed!", "Y: FULL N: FINAL", size2 = 12)268 retest = True269 led_pass()270 while True:271 if (not io_read(SW_YES)):272 break273 if (not io_read(SW_NO)):274 test_only = True275 break276 elif test_fail == True:277 print(f'{Fore.RED}TEST FAILED: {fail_str}')278 print(f"{Fore.YELLOW}Press YES for full test, NO for final test")279 oled_write_dual(f'FAIL: {fail_str}', "Y: FULL N: FINAL", size2 = 12)280 retest = True281 led_fail()282 while True:283 if (not io_read(SW_YES)):284 break285 if (not io_read(SW_NO)):286 test_only = True287 break288 break289 # except:290 # print(f"{Fore.RED}Something went wrong, let's try again")...
prog_pc.py
Source:prog_pc.py
1#!/bin/python32# Script to program and test sea-picro3import os4import time5import argparse6from colorama import Fore7import serial8from serial.tools import list_ports9import usb.core10import io11from multiprocessing import Process12bl_vid = 0x2e8a13bl_pid = 0x000314cpy_vid = 0x6a6a15cpy_pid = 0x535016TESTER_OKAY = 3217TESTER_ERROR = 3318TESTER_RESET = 3419HARD_RESET = 25520# Order is RST pins anticlockwise, then EXT pins anticlockwise21sp_pin_map = ["D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D21", "D23", "D20", "D22", "D26", "D27", "D28", "D29", "D12", "D13", "D14", "D15", "D16"]22def send_tester_string(string):23 tester_serial_io.write(str(string) + "\r\n")24 tester_serial_io.flush()25def get_tester_string():26 ret_str = tester_serial_io.readline()27 return ret_str28def send_dut_string(string):29 dut_serial_io.write(str(string) + "\r\n")30 dut_serial_io.flush()31def get_dut_string():32 ret_str = dut_serial_io.readline()[0:-1]33 return ret_str34def flash_circuitpython():35 ''' Flashes circuitpython firmware. '''36 test_fail = False37 found_rpi = False38 # Spinlock until RPi bootloader is found39 while found_rpi == False:40 dev = usb.core.find(find_all=1)41 for cfg in dev:42 if cfg.idVendor == bl_vid and cfg.idProduct == bl_pid:43 found_rpi = True44 time.sleep(1)45 time.sleep(3)46 print(f"{Fore.BLUE}RPi Bootloader found, copying CircuitPython")47 retval = os.system("cp circuitpy-sea-picro.uf2 /media/josh/RPI-RP2")48 if retval != 0:49 print(f'{Fore.RED}FAILED TO FLASH CPY !')50 test_fail = True51 return test_fail52def flash_firmware():53 ''' Flashes test firmware. '''54 test_fail = False55 found_cpy = False56 # Spinlock until circuitpython is found57 while found_cpy == False:58 dev = usb.core.find(find_all=1)59 for cfg in dev:60 if cfg.idVendor == cpy_vid and cfg.idProduct == cpy_pid:61 found_cpy = True62 time.sleep(1)63 print(f"{Fore.BLUE}CircuitPython found, copying test firmware")64 time.sleep(5)65 retval = os.system("cp -rf circuitpy-files/* /media/josh/CIRCUITPY")66 if retval != 0:67 print(f'{Fore.RED}FAILED TO FLASH TEST FW !')68 test_fail = True69 else:70 send_tester_string(HARD_RESET)71 return test_fail72def test_ident():73 # Check we have the right /dev/ttyACM port74 test_fail = False75 send_dut_string("ident")76 ret_str = get_dut_string()77 if ret_str == "ident = Sea-Picro!":78 print(f'{Fore.BLUE}IDENT passed')79 else:80 send_tester_string(TESTER_ERROR)81 print(f'{Fore.RED}IDENT Failed, possibly wrong /dev/ttyACM port')82 test_fail = True83 return test_fail84def test_vbus():85 # Check VBUS detection86 test_fail = False87 send_dut_string("vbus_test")88 ret_str = get_dut_string()89 if ret_str == "vbus = high":90 print(f'{Fore.BLUE}VBUS detect passed')91 elif ret_str == "vbus = low":92 send_tester_string(TESTER_ERROR)93 print(f'{Fore.RED}VBUS detect failed')94 else:95 send_tester_string(TESTER_ERROR)96 print(f'{Fore.RED}VBUS detect failed')97 test_fail = True98 return test_fail99def test_led():100 # RGB test time101 test_fail = False102 print(f'{Fore.YELLOW}Monitor LEDs please')103 send_dut_string("led_rgb")104 105 print(f'{Fore.YELLOW}Did LEDs cycle R/G/B? (Y)es / (N)o / (R)epeat{Fore.WHITE}')106 time.sleep(3)107 recv = input()108 if recv.lower() == "y":109 print(f'{Fore.BLUE}RGB LEDs passed')110 send_dut_string("led_rbw") # Party Time!111 elif recv.lower() == "n":112 send_tester_string(TESTER_ERROR)113 print(f'{Fore.RED}RGB LEDs failed')114 test_fail = True115 elif recv.lower() == "r":116 test_led()117 time.sleep(2)118 return test_fail119def test_keys(model):120 ''' Test all IO with test fixture.121 Transmit number according to pin location, which test fixture will pull low, simulating key press.122 DUT will then respond with a bitfield showing IO state. '''123 test_fail = False124 found_cpy = False125 # Spinlock until circuitpython is found126 while found_cpy == False:127 dev = usb.core.find(find_all=1)128 for cfg in dev:129 if cfg.idVendor == cpy_vid and cfg.idProduct == cpy_pid:130 found_cpy = True131 time.sleep(1)132 print("CircuitPython found, beginnig test")133 if model == "rst":134 num_io = 18 # RST has 18 IO135 if model == "ext":136 num_io == 23 # EXT has 23 IO137 for pos in range(1,num_io+1):138 send_tester_string(pos)139 time.sleep(0.02)140 send_dut_string("io_test")141 ret_str = get_dut_string()142 array = ret_str[1:-1].split(", ") # Convert to array of strings "True", "False"143 key_fail = False # Used to flag if a key passes it's test or not144 # Loop through array and check val = False unless index == pos145 for index in range(0,num_io):146 # Case where we expect a key to be pressed147 if index == pos-1:148 if array[index] == "True":149 pass150 else:151 send_tester_string(TESTER_ERROR)152 print(f'{Fore.RED}{sp_pin_map[pos-1]}: IO {sp_pin_map[index]} was NOT pressed')153 key_fail = key_fail or True154 test_fail = True155 # Case where we do not expect a key to be pressed156 elif index != pos-1:157 if array[index] == "False":158 pass159 else:160 send_tester_string(TESTER_ERROR)161 print(f'{Fore.RED}{sp_pin_map[pos-1]}: IO {sp_pin_map[index]} WAS pressed')162 key_fail = key_fail or True163 test_fail = True164 if not key_fail:165 print(f'{Fore.BLUE}{sp_pin_map[pos-1]}: IO {sp_pin_map[pos-1]} passed') # Print passed message if a fail message hasn't been printed166 return test_fail167def test_dut(model):168 test_fail = False169 test_fail = test_fail or test_ident()170 test_fail = test_fail or test_vbus()171 test_fail = test_fail or test_led()172 test_fail = test_fail or test_keys(model)173 return test_fail174if __name__ == "__main__":175 # Connect to test fixture176 tester_serial_io = None177 # ACM0 = arduino178 # ACM1 = cpy repl179 # ACM2 = cpy data180 try:181 uart = serial.Serial("/dev/ttyACM0", 115200, timeout=0.1)182 tester_serial_io = io.TextIOWrapper(io.BufferedRWPair(uart, uart))183 except:184 print(f'{Fore.RED}Conneting to tester failed, possibly wrong /dev/ttyACM port')185 exit()186 parser = argparse.ArgumentParser()187 parser.add_argument("-c", "--circuitpython",action='store_true')188 parser.add_argument("-f", "--firmware", action='store_true')189 parser.add_argument("-r", "--rst_test", action='store_true')190 parser.add_argument("-e", "--ext_test", action='store_true')191 args = parser.parse_args()192 send_tester_string(TESTER_RESET)193 test_fail = False194 if args.circuitpython:195 test_fail = test_fail | flash_circuitpython()196 if args.firmware:197 test_fail = test_fail | flash_firmware()198 time.sleep(5)199 if args.rst_test:200 try:201 data = serial.Serial("/dev/ttyACM2", 115200, timeout=0.1)202 dut_serial_io = io.TextIOWrapper(io.BufferedRWPair(data, data))203 except:204 print(f'{Fore.RED}Conneting to DUT failed, possibly wrong /dev/ttyACM port')205 exit()206 test_fail = test_fail | test_dut("rst")207 if test_fail == False:208 send_tester_string(TESTER_OKAY)209 print(f'{Fore.GREEN}ALL STEPS PASSED!!!')210 elif test_fail == True:211 send_tester_string(TESTER_ERROR)...
ui.form_checker.js
Source:ui.form_checker.js
1if (typeof ui == 'undefined') var ui = {};2ui.FormChecker= {3ERR_STR_NOT_INT: 'The value should be a integer.',4ERR_STR_INT_OUT_OF_RANGE: 'The value should be between ',5ERR_STR_TEXT_TOO_LONG: 'Too many charactors in this widget',6ERR_STR_FILE_IS_NOT_IMAGE: 'This file is is not a image file',7ERR_STR_FILE_SIZE_EXCEED: 'This file is too large',8check_config_error: 9function check_config_error(widgets) {10 var result = [];11 var count = 012 $(widgets).each(13 function (idx, widget) {14 if ($(widget).data('error') == true) {15 count += 1;16 result.push($(widget).attr('title') 17 + ': ' + $(widget).data('error_str') );18 }19 });20 return {'count':count, 'error_values':result};21},22test_int_value:23function test_int_value(widget) {24 var ret = false;25 var c_val = parseInt($(widget).val());26 if (!isNaN(c_val)) {27 $(widget).removeClass('test_fail');28 $(widget).val(c_val);29 $(widget).data('error', false);30 ret = true;31 } else {32 $(widget).addClass('test_fail');33 $(widget).data('error', true);34 $(widget).data('error_str', ui.FormChecker.ERR_STR_NOT_INT);35 }36 return ret;37},38test_int_range:39function test_int_bound(widget, min, max) {40 var ret = false;41 var c_val = parseInt($(widget).val());42 if (isNaN(c_val)) {43 $(widget).addClass('test_fail');44 $(widget).data('error', true);45 $(widget).data('error_str', ui.FormChecker.ERR_STR_NOT_INT);46 } else {47 $(widget).val(c_val);48 if (min < c_val && c_val < max) {49 $(widget).removeClass('test_fail');50 $(widget).data('error', false);51 ret = true;52 } else {53 $(widget).addClass('test_fail');54 $(widget).data('error', true);55 $(widget).data('error_str'56 , ui.FormChecker.ERR_STR_INT_OUT_OF_RANGE 57 + min +' and ' + max);58 }59 }60 return ret;61},62test_text_len_limit:63function test_text_len_limit(widget, max_len) {64 var ret = false;65 if ($(widget).val().length < max_len) {66 $(widget).removeClass('test_fail');67 $(widget).data('error', false);68 ret = true;69 } else {70 $(widget).addClass('test_fail');71 $(widget).data('error', true);72 $(widget).data('error_str', ui.FormChecker.ERR_STR_TEXT_TOO_LONG);73 }74 return ret;75},76test_file_image:77function test_file_image(file) {78 var ret = false;79 var filename = file;80 if (typeof (file) != 'string') {81 filename = file.name;82 }83 if (/.*(jpg|jpeg|png|gif)$/i.test(filename)) {84 ret = true;85 }86 return ret;87},88test_file_size_bound:89function test_file_size_bound(file, bound) {90 var ret = false;91 if (file.size < bound) {92 ret = true;93 }94 return ret;95}...
Using AI Code Generation
1wpt.test_fail("test failed");2wpt.test_pass("test passed");3wpt.test_status("test status");4wpt.test_message("test message");5wpt.test_done();6wpt.test_start("test start");7wpt.test_log("test log");8wpt.test_set_location("test set location");9wpt.test_set_cookie("test set cookie");10wpt.test_clear_cookies("test clear cookies");11wpt.test_exec("test exec");12wpt.test_exec_async("test exec async");13wpt.test_set_pref("test set pref");14wpt.test_clear_pref("test clear pref");15wpt.test_set_user_agent("test set user agent");16wpt.test_set_viewport("test set viewport");17wpt.test_set_auth("test set auth");18wpt.test_set_proxy("test set proxy");19wpt.test_clear_proxy("test clear proxy");20wpt.test_set_basic_auth("test set basic auth");21wpt.test_clear_basic_auth("test clear basic auth");22wpt.test_set_dns("test set dns");23wpt.test_clear_dns("
Using AI Code Generation
1wpt.test_fail("test fail message");2wpt.test_pass("test pass message");3wpt.test_status("test status message");4wpt.test_print("test print message");5wpt.test_message("test message");6wpt.test_start("test start message");7wpt.test_done("test done message");8wpt.test_timeout("test timeout message");9wpt.test_done("test done message");10wpt.test_timeout("test timeout message");11wpt.test_done("test done message");12wpt.test_timeout("test timeout message");13wpt.test_done("test done message");14wpt.test_timeout("test timeout message");15wpt.test_done("test done message");16wpt.test_timeout("test timeout message");17wpt.test_done("test done message");18wpt.test_timeout("test timeout message");19wpt.test_done("test done message");20wpt.test_timeout("test timeout message");21wpt.test_done("test done message");22wpt.test_timeout("test timeout message");23wpt.test_done("test done message");24wpt.test_timeout("test timeout message");25wpt.test_done("test done message");
Using AI Code Generation
1var wpt = require('wpt');2wpt.test_fail();3var wpt = require('wpt');4wpt.test_pass();5var wpt = require('wpt');6wpt.test_status("OK");7var wpt = require('wpt');8wpt.test_status("ERROR");9var wpt = require('wpt');10wpt.test_status("OK", "test passed");11var wpt = require('wpt');12wpt.test_status("ERROR", "test failed");13var wpt = require('wpt');14var wpt = require('wpt');15var wpt = require('wpt');16var wpt = require('wpt');17var wpt = require('wpt');18var wpt = require('wpt');19var wpt = require('wpt');
Using AI Code Generation
1var wpt = require('webpagetest');2wpt.test_fail(url, function(err, data) {3 if(err) console.log(err);4 else console.log(data);5});6var wpt = require('webpagetest');7wpt.test_fail(url, function(err, data) {8 if(err) console.log(err);9 else console.log(data);10});11var wpt = require('webpagetest');12wpt.test_fail(url, function(err, data) {13 if(err) console.log(err);14 else console.log(data);15});16var wpt = require('webpagetest');17wpt.test_fail(url, function(err, data) {18 if(err) console.log(err);19 else console.log(data);20});21var wpt = require('webpagetest');22wpt.test_fail(url, function(err, data) {23 if(err) console.log(err);24 else console.log(data);25});26var wpt = require('webpagetest');27wpt.test_fail(url, function(err, data) {28 if(err) console.log(err);29 else console.log(data);30});31var wpt = require('webpagetest');32wpt.test_fail(url, function(err, data) {33 if(err) console.log(err);34 else console.log(data);35});36var wpt = require('webpagetest');37wpt.test_fail(url, function(err, data) {38 if(err) console.log(err);39 else console.log(data);40});41var wpt = require('webpagetest
Using AI Code Generation
1var wpt = require('wpt');2wpt.test_fail('Test failed');3var wpt = require('wpt');4wpt.test_pass('Test passed');5var wpt = require('wpt');6wpt.test_status('Test status');7var wpt = require('wpt');8wpt.test_info('Test info');9var wpt = require('wpt');10wpt.test_done();11var wpt = require('wpt');12wpt.test_start('Test start');13var wpt = require('wpt');14wpt.test_done();15var wpt = require('wpt');16wpt.test_start('Test start');17var wpt = require('wpt');18wpt.test_done();19var wpt = require('wpt');20wpt.test_start('Test start');21var wpt = require('wpt');22wpt.test_done();23var wpt = require('wpt');24wpt.test_start('Test start');25var wpt = require('wpt');26wpt.test_done();27var wpt = require('wpt');28wpt.test_start('Test start');29var wpt = require('wpt');30wpt.test_done();
Using AI Code Generation
1var wpt = require('wpt');2wpt.test_fail();3var wpt = {};4wpt.test_fail = function(){5 console.log('test_fail');6};7module.exports = wpt;8var wpt = {};9wpt.test_pass = function(){10 console.log('test_pass');11};12module.exports = wpt;13 0 passing (6ms)14 at Context.<anonymous> (test.js:6:10)15 at Context.<anonymous> (test.js:12:10)16var wpt = require('wpt');17wpt.test_fail();18var wpt = {};
Using AI Code Generation
1var wpt = require('wpt');2wpt.test_fail();3exports.test_fail = function(){4 throw new Error('Test failed');5}6{ [Error: Test failed]7 path: '/home/username/phantomjs/wpt/test_fail.js' }8{ [Error: Test failed]9 path: '/home/username/phantomjs/wpt/test_fail.js' }10{ [Error: Test failed]11 path: '/home/username/phantomjs/wpt/test_fail.js' }12{ [Error: Test failed]13 path: '/home/username/phantomjs/wpt/test_fail.js' }14{ [Error: Test failed]15 path: '/home/username/phantomjs/wpt/test_fail.js' }16{ [Error: Test failed]17 path: '/home/username/phantomjs/wpt/test_fail.js' }18{ [Error: Test failed]19 path: '/home/username/phantomjs/wpt/test_fail.js' }20{ [Error: Test failed]
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!!