Best Python code snippet using Airtest
trinkeypass.py
Source:trinkeypass.py  
1#!/usr/bin/env python32"""This code, designed to run on an Adafruit Neo Trinkey, sends a password3to the connected system as if it was a keyboard."""4__version__ = '0.0.16'5__author__ = 'William Stearns'6__copyright__ = 'Copyright 2021, William Stearns'7__credits__ = ['William Stearns']8__email__ = 'william.l.stearns@gmail.com'9__license__ = 'GPL 3.0'10__maintainer__ = 'William Stearns'11__status__ = 'Development'				#Prototype, Development or Production12import os13import sys14import time15#import gc16import board														# pylint: disable=import-error17import touchio														# pylint: disable=import-error18import usb_hid														# pylint: disable=import-error19import neopixel														# pylint: disable=import-error20import storage														# pylint: disable=import-error21from adafruit_hid.keyboard import Keyboard										# pylint: disable=import-error22from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS								# pylint: disable=import-error23#from adafruit_hid.keycode import Keycode										# pylint: disable=import-error,unused-import24#def debug(debug_str):25#	"""Returns debugging information."""26#27#	print(debug_str)28def isdir(possible_dir):29	"""Returns whether possible_dir is a directory or not, as30	os.path.* is not currently available in micropython."""31	try:32		_ = os.listdir(possible_dir)33		return True34	except OSError:35		return False36def obj_exists(possible_object):37	"""Returns whether possible_object exists in the filesystem or38	not, as os.path.* is not currently available in micropython.39	Does not distinguish between directories and files. """40	try:41		os.stat(possible_object)42		return True43	except OSError:44		return False45def get_keypress(k1, k2):46	"""Waits for a key to be pressed, then returns which one(s) were47	pressed and the total time from first press to last release (in48	10ths of a second)."""49	t1press = False50	t2press = False51	timecycles = 052	while (not t1press) and (not t2press):							#Keep going through the loop as loong as we've not yet seen a press53		while (k1.value ^ key_invert) or (k2.value ^ key_invert):			#While either button is pressed54			oldt1 = t1press55			oldt2 = t2press56			t1press = t1press or (k1.value ^ key_invert)57			t2press = t2press or (k2.value ^ key_invert)58			if oldt1 != t1press or oldt2 != t2press:				#If we've added a key since the last loop...59				if t1press and t2press:60					set_neo(pixels, [1, 2], color_keypress, False)		#Turn on the neopixels next to the pads.61				elif t1press:62					set_neo(pixels, [2], color_keypress, False)		#Pixel closest to pad 163				elif t2press:64					set_neo(pixels, [1], color_keypress, False)		#Pixel closest to pad 265			time.sleep(0.1)66			timecycles += 167	set_neo(pixels, default_pixels, default_color, True)68	return t1press, t2press, timecycles69def load_file_into_string(filename):70	"""Reads the entire contents of a file into the returned string.  First returned object is string form, second is raw bytes."""71	file_string = None72	raw_bytes = None73	if obj_exists(filename) and not isdir(filename):				#Can't use python's "os.path.exists"74		#print("Reading " +str(filename))75		#try:76		with open(filename, 'rb') as read_h:77			raw_bytes = read_h.read()78			#file_string = raw_bytes.decode('utf-8', "replace")79			file_string = str(raw_bytes, 'ascii')80		#except PermissionError:81		#except:82		#	pass83	return file_string, raw_bytes84def load_raw_keyfile(passfile_dir, key_filename):85	"""Load the contents of the requested key."""86	content = None87	filename = passfile_dir + key_filename88	if obj_exists(filename) and not isdir(filename):89		content, _ = load_file_into_string(filename)90	else:91		print("Unable to locate " + filename)92	return content93#def transform_raw(raw_string, xform_key):94#	"""Converts a raw string into a transformed string."""95#	#If xform_key empty or false, just return the string as is.96#	#If xform_key non-empty, swap the case of all keys lining up with Trues in xform_key (we can think of xform_key being repeated over and over enough to cover the entire raw_string.97#98#	if xform_key:99#		output_text = ''100#		for s_index, orig_char in enumerate(raw_string):101#			#Loop through the xform key values, wrapping around to the 0th element when we get to the end.102#			if xform_key[s_index % len(xform_key)]:						#Pull out the True/False value from xform_key103#				if orig_char.isupper():104#					output_text = output_text + orig_char.lower()105#				elif orig_char.isdigit():106#					output_text = output_text + str(9 - int(orig_char))	#Replace each digit with 9-thatdigit107#				else:108#					output_text = output_text + orig_char.upper()109#			else:110#				output_text = output_text + orig_char111#	else:112#		output_text = raw_string113#114#	return output_text115def flash_neo(pixel_h, which_ones, color, how_long):116	"""Flash all neopixels in the which_ones list to a given color for the given time."""117	for pix in which_ones:118		pixel_h[pix] = color119		pixel_h.brightness = neo_brightness120		pixel_h.show()121	time.sleep(how_long)122	set_neo(pixel_h, default_pixels, default_color, True)123def set_neo(pixel_h, which_ones, color, clean_slate):124	"""Set all neopixels in the which_ones list to a given color."""125	for pix in range(0, 4):126		if pix in which_ones:127			pixel_h[pix] = color128		elif clean_slate:129			pixel_h[pix] = color_blank130	pixel_h.brightness = neo_brightness131	pixel_h.show()132#Constants133num_to_neo = [ [], [0], [1], [0,1], [2], [0,2], [1,2], [0,1,2], [3], [0,3], [1,3], [0,1,3], [2,3], [0,2,3], [1,2,3], [0,1,2,3] ]	#For a number 0-15, which neopixels do we light to show it?134red = (32, 0, 0)135green = (0, 32, 0)136blue = (0, 0, 32)137cyan = (0, 32, 32)138purple = (32, 0, 32)139yellow = (32, 32, 0)140white = (32, 32, 32)141black = (0, 0, 0)142zero_pads = '0000'143#User-editable values144seconds_to_erase = 7145max_unlock_failures = 7146neo_brightness = 0.2147color_keynum = green148color_wakeup = blue149color_keypress = purple150color_blank = black151#color_xform_mode = cyan152color_unlock_mode = yellow153color_error = red154#Setup155if os.uname().machine == 'Adafruit NeoPixel Trinkey M0 with samd21e18':156	key_invert = False157	pixels = neopixel.NeoPixel(board.NEOPIXEL, 4, brightness=neo_brightness, auto_write=False)158	keyboard = Keyboard(usb_hid.devices)159	keyboard_layout = KeyboardLayoutUS(keyboard)160	touch1 = touchio.TouchIn(board.TOUCH1)161	touch2 = touchio.TouchIn(board.TOUCH2)162else:163	print("I don't know how to run on this platform: " + os.uname().machine)164	print("Here are its hardware features: " + str(dir(board)))165	sys.exit(1)166selected_keynum = 0167#xform_entry_mode = False168unlock_entry_mode = False169#xform_list = []170unlock_code = ""171unlock_failures = 0172default_color = color_keynum173#try:174#	from secrets import secrets175#except ImportError:176#	secrets = {}177#178#if 'unlock' not in secrets:179#	secrets['unlock'] = ''180if obj_exists('/sd/') and isdir('/sd/'):					#Where will the password files be?181	data_dir = '/sd/'							#If this circuitpython board has a microsd slot, the contents of this will show up under /sd/182else:183	data_dir = '/'								#Otherwise, the contents will be immediately at the top of the filesystem.184pw_subdir = ''									#This dir is under data_dir, equal to unlock_code (unless the directory does not exist, then empty so we use the password files in data_dir)185default_pixels = []186for led in [0, 1, 2, 3]:187	flash_neo(pixels, [led], color_wakeup, 1)188while True:189	#print(str(gc.mem_free()) + " bytes free")				# pylint: disable=no-member190	(t1, t2, cycles) = get_keypress(touch1, touch2)191	#print(str(t1) + ' ' + str(t2) + ' ' + str(cycles))192	if t1 and t2:193		#Both Touch1 and Touch2 pressed.  This switches back and forth between normal (select/send keys) mode and enter xform mode.194		if cycles >= (seconds_to_erase * 10):195			#Erasing the entire storage because the user held both keys for more than 7 seconds196			storage.erase_filesystem()197		#if xform_entry_mode:198		#	#Switching back to normal operation199		#	default_color = color_keynum200		#	default_pixels = num_to_neo[selected_keynum % 16]201		#	set_neo(pixels, default_pixels, default_color, True)202		elif unlock_entry_mode:203			#Switching back to normal operation204			default_color = color_keynum205			default_pixels = num_to_neo[selected_keynum % 16]206			if not obj_exists(data_dir + unlock_code) or not isdir(data_dir + unlock_code):207				#Supplied unlock_code does not correspond to a dir in the filesystem; track how many fails and erase_filesystem if too many208				unlock_failures += 1209				if unlock_failures > max_unlock_failures:210					#Erasing the entire storage because there were more than 7 unlock failures211					storage.erase_filesystem()212			elif obj_exists(data_dir + unlock_code) and isdir(data_dir + unlock_code):		# and obj_exists(data_dir + unlock_code + '/0000.txt'):213				pw_subdir = unlock_code + '/'214				selected_keynum = 0215				default_pixels = num_to_neo[selected_keynum % 16]216				if unlock_code:217					#You only reset the failure count if you actually guess a correct one, not by going back to the top level directory with an empty unlock code.218					unlock_failures = 0219		else:220			#Switching into unlock entry mode221			default_color = color_unlock_mode222			default_pixels = [0,3]223			unlock_code = ""224		set_neo(pixels, default_pixels, default_color, True)225		unlock_entry_mode = unlock_entry_mode ^ True			#xor with true to switch to opposite value (True->False, False->True)226	elif t1:227		#Only T1 pressed.  In normal mode, this moves us to the next password.  In "enter xform" mode, add a "False/nocasechange" to the xform list.228		#if xform_entry_mode:229		#	xform_list.append(False)230		#	print(str(xform_list))231		if unlock_entry_mode:232			unlock_code = unlock_code + '1'233		#elif unlock_code != secrets['unlock']:234		#	flash_neo(pixels, [0, 3], color_unlock_mode, 0.5)235		else:236			if selected_keynum == 9999:237				selected_keynum = 0238			elif obj_exists(data_dir + pw_subdir + (zero_pads + str(selected_keynum + 1))[-4:] + '.txt'):239				selected_keynum += 1240			else:241				selected_keynum = 0242			default_pixels = num_to_neo[selected_keynum % 16]243			set_neo(pixels, default_pixels, color_keynum, True)244	elif t2:245		#Only T2 pressed.  In normal mode, send the currently selected password like a keyboard.  In "enter xform" mode, add a "True/casechange" to the xform list.246		#if xform_entry_mode:247		#	xform_list.append(True)248		#	print(str(xform_list))249		if unlock_entry_mode:250			unlock_code = unlock_code + '2'251		#elif unlock_code != secrets['unlock']:252		#	flash_neo(pixels, [0, 3], color_unlock_mode, 0.5)253		else:254			#target_string = transform_raw(load_raw_keyfile(data_dir + pw_subdir, (zero_pads + str(selected_keynum))[-4:] + '.txt'), xform_list)255			target_string = load_raw_keyfile(data_dir + pw_subdir, (zero_pads + str(selected_keynum))[-4:] + '.txt')256			if target_string:...test_lock_unlock_host.py
Source:test_lock_unlock_host.py  
1###2# test_467_lock_unlock_compute_node sanity_juno_unified_R3.xls3###4import time5from pytest import mark, skip, param6from utils.clients.ssh import ControllerClient7from utils.tis_log import LOG8from utils.kpi import kpi_log_parser9from consts.stx import HostOperState, HostAvailState10from consts.kpi_vars import HostLock, HostUnlock, KPI_DATE_FORMAT11from testfixtures.recover_hosts import HostsToRecover12from keywords import host_helper, system_helper, common, container_helper13@mark.platform_sanity14def test_lock_active_controller_reject(no_simplex):15    """16    Verify lock unlock active controller. Expected it to fail17    Test Steps:18        - Get active controller19        - Attempt to lock active controller and ensure it's rejected20    """21    LOG.tc_step('Retrieve the active controller from the lab')22    active_controller = system_helper.get_active_controller_name()23    assert active_controller, "No active controller available"24    # lock standby controller node and verify it is successfully locked25    LOG.tc_step("Lock active controller and ensure it fail to lock")26    exit_code, cmd_output = host_helper.lock_host(active_controller, fail_ok=True, swact=False,27                                                  check_first=False)28    assert exit_code == 1, 'Expect locking active controller to be rejected. ' \29                           'Actual: {}'.format(cmd_output)30    status = system_helper.get_host_values(active_controller, 'administrative')[0]31    assert status == 'unlocked', "Fail: The active controller was locked."32@mark.parametrize('host_type', [33    param('controller', marks=mark.priorities('platform_sanity', 'kpi')),34    param('compute', marks=mark.priorities('platform_sanity', 'kpi')),35    param('storage', marks=mark.priorities('platform_sanity', 'kpi')),36])37def test_lock_unlock_host(host_type, collect_kpi):38    """39    Verify lock unlock host40    Test Steps:41        - Select a host per given type. If type is controller, select standby controller.42        - Lock selected host and ensure it is successfully locked43        - Unlock selected host and ensure it is successfully unlocked44    """45    init_time = None46    if collect_kpi:47        init_time = common.get_date_in_format(date_format=KPI_DATE_FORMAT)48    LOG.tc_step("Select a {} node from system if any".format(host_type))49    if host_type == 'controller':50        if system_helper.is_aio_simplex():51            host = 'controller-0'52        else:53            host = system_helper.get_standby_controller_name()54            assert host, "No standby controller available"55    else:56        if host_type == 'compute' and (system_helper.is_aio_duplex() or57                                       system_helper.is_aio_simplex()):58            skip("No compute host on AIO system")59        elif host_type == 'storage' and not system_helper.is_storage_system():60            skip("System does not have storage nodes")61        hosts = system_helper.get_hosts(personality=host_type,62                                        availability=HostAvailState.AVAILABLE,63                                        operational=HostOperState.ENABLED)64        assert hosts, "No good {} host on system".format(host_type)65        host = hosts[0]66    LOG.tc_step("Lock {} host - {} and ensure it is successfully locked".format(host_type, host))67    HostsToRecover.add(host)68    host_helper.lock_host(host, swact=False)69    # wait for services to stabilize before unlocking70    time.sleep(20)71    # unlock standby controller node and verify controller node is successfully unlocked72    LOG.tc_step("Unlock {} host - {} and ensure it is successfully unlocked".format(host_type,73                                                                                    host))74    host_helper.unlock_host(host)75    LOG.tc_step("Check helm list after host unlocked")76    con_ssh = ControllerClient.get_active_controller()77    con_ssh.exec_cmd('helm list', fail_ok=False)78    if collect_kpi:79        lock_kpi_name = HostLock.NAME.format(host_type)80        unlock_kpi_name = HostUnlock.NAME.format(host_type)81        unlock_host_type = host_type82        if container_helper.is_stx_openstack_deployed():83            if system_helper.is_aio_system():84                unlock_host_type = 'compute'85        else:86            lock_kpi_name += '_platform'87            unlock_kpi_name += '_platform'88            if unlock_host_type == 'compute':89                unlock_host_type = 'compute_platform'90        LOG.info("Collect kpi for lock/unlock {}".format(host_type))91        code_lock, out_lock = kpi_log_parser.record_kpi(92            local_kpi_file=collect_kpi,93            kpi_name=lock_kpi_name,94            host=None, log_path=HostLock.LOG_PATH,95            end_pattern=HostLock.END.format(host),96            start_pattern=HostLock.START.format(host),97            start_path=HostLock.START_PATH,98            init_time=init_time)99        time.sleep(30)      # delay in sysinv log vs nova hypervisor list100        code_unlock, out_unlock = kpi_log_parser.record_kpi(101            local_kpi_file=collect_kpi,102            kpi_name=unlock_kpi_name, host=None,103            log_path=HostUnlock.LOG_PATH,104            end_pattern=HostUnlock.END[unlock_host_type].format(host),105            init_time=init_time,106            start_pattern=HostUnlock.START.format(host),107            start_path=HostUnlock.START_PATH)108        assert code_lock == 0, 'Failed to collect kpi for host-lock {}. ' \109                               'Error: \n'.format(host, out_lock)110        assert code_unlock == 0, 'Failed to collect kpi for host-unlock {}. ' \...unlock.py
Source:unlock.py  
...95        self.unlockIdx = unlockIdx96        return97    def _request(self, callback):98        RequestState.sent('unlock')99        BigWorld.player().stats.unlock(self.vehTypeCD, self.unlockIdx, lambda code: self._response(code, callback))100    def _response(self, code, callback, errStr='', ctx=None):101        LOG_DEBUG('Server response', code, errStr, ctx)102        RequestState.received('unlock')...test_lockboxes.py
Source:test_lockboxes.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3import doctest4import unittest5canUnlockAll = __import__('0-lockboxes').canUnlockAll6class TestLockBoxes(unittest.TestCase):7    """Unittest."""8    def test_empty(self):9        boxes = [[]]10        self.assertEqual(canUnlockAll(boxes), True)11    def test_sequence(self):12        boxes = [[1], [2], [3], [4], []]13        self.assertEqual(canUnlockAll(boxes), True)14    def test_multiple(self):15        boxes = [[1, 4], [2], [0, 4, 1], [3], [], [4, 1], [5, 6]]16        self.assertEqual(canUnlockAll(boxes), False)17    def test_fake(self):18        boxes = [[1], [0], [3], []]19        self.assertEqual(canUnlockAll(boxes), False)20    def test_multiplepath(self):21        boxes = [[1, 2, 3], [0], [3], []]22        self.assertEqual(canUnlockAll(boxes), True)23    def test_multiplepath_false(self):24        boxes = [[1], [1, 2, 0], [0], []]25        self.assertEqual(canUnlockAll(boxes), False)26    def test_multiplepath_true(self):27        boxes = [[1], [1, 2, 0], [3], []]28        self.assertEqual(canUnlockAll(boxes), True)29    def test_oneforall(self):30        boxes = [[1, 3], [], [], [2]]31        self.assertEqual(canUnlockAll(boxes), True)32    def test_lastopenall(self):33        boxes = [[3], [], [], [1, 2]]34        self.assertEqual(canUnlockAll(boxes), True)35    def test_nopen(self):36        boxes = [[3], [], [], []]37        self.assertEqual(canUnlockAll(boxes), False)38    def test_nopen2(self):39        boxes = [[], [], [], []]40        self.assertEqual(canUnlockAll(boxes), False)41    def test_nopen2(self):42        boxes = [[1], [2], [], []]43        self.assertEqual(canUnlockAll(boxes), False)44    def test_loops(self):45        boxes = [[0, 1, 2], [0, 1, 2], [0, 1, 2, 3], [0]]46        self.assertEqual(canUnlockAll(boxes), True)47    def test_loops2(self):48        boxes = [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3], [0], []]49        self.assertEqual(canUnlockAll(boxes), False)50    def test_weirdkey(self):51        boxes = [[0, 1, 2], [0, 1, 2, 3, 8], [0, 1, 2, 3, 4], [0], []]52        self.assertEqual(canUnlockAll(boxes), True)53    def test_weirdkey1(self):54        boxes = [[0, 0, 0, 1], [1, 1, 2, 1, 8], [2, 2, 2, 3, 20], [0, 0, 0, 0, 4], []]55        self.assertEqual(canUnlockAll(boxes), True)56    def test_weirdkey2(self):57        boxes = [[4, 0, 0, 5], [8, 1, 3, 1, 8], [2, 2, 2, 3, 20], [0, 0, 0, 0, 4], [1, 8, 9, 7]]58        self.assertEqual(canUnlockAll(boxes), False)59    def test_weirdkey3(self):60        boxes = [[4, 0, 0, 5], [8, 1, 3, 1, 8], [2, 2, 2, 3, 20], [0, 0, 2, 0, 4], [1, 8, 9, 7]]61        self.assertEqual(canUnlockAll(boxes), True)62    def test_nullboxes(self):63        boxes = [[4, 0, 0, 5], [], [], [0, 0, 2, 0, 4], [1, 8, 9, 7]]64        self.assertEqual(canUnlockAll(boxes), False)65    def test_big(self):66        boxes = [[1000, 5, 2], [3, 293], [5000, 1], [0, 0, 2, 0, 4], [1, 8, 9, 7]]67        self.assertEqual(canUnlockAll(boxes), True)68    def test_repeated(self):69        boxes = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4]]70        self.assertEqual(canUnlockAll(boxes), True)71    def test_bigend(self):72        boxes = [[4], [],[],[],[0, 1, 2, 3, 4]]73        self.assertEqual(canUnlockAll(boxes), True)74    def test_nproblem(self):75        boxes = [[1000000, 90000000, 0, 0, 1], []]76        self.assertEqual(canUnlockAll(boxes), True)77    def test_ylockboxes(self):78        boxes = [[1, 3], [2, 2, 2, 2, 2, 2, 2, 2], [0], [4]]79        self.assertEqual(canUnlockAll(boxes), True)80    def test_butone(self):81        boxes = [[1], [2, 3], [], [4], [4]]82        self.assertEqual(canUnlockAll(boxes), True)83    def test_almost(self):84        boxes = [[1], [2], [4], [4], [1, 2, 4, 5, 7, 3, 8, 9]]85        self.assertEqual(canUnlockAll(boxes), True)86    def test_almostbad(self):87        boxes = [[1], [2], [4], [4], [1, 2, 4, 5, 7, 0, 8, 9]]...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!!
