Best Python code snippet using keyboard
test_collection.py
Source:test_collection.py  
1from random import randint, choice2import pytest3from spaceway.collection import *4from spaceway.mixins import BoostMixin, SceneButtonMixin, SettingsButtonMixin5from spaceway.hitbox import Rect6from utils import *7@pytest.mark.parametrize('boosts_params', [8    [(7, 'a'), (3, 'b'), (5, 'c'), (7, 'a')],9    [(2, 'x'), (2, 'y'), (2, 'z')],10    [(9, 'q'), (3, 'f'), (5, 'r'), (4, 't')]11])12def test_boosts_group(pygame_env, boosts_params):13    screen, base_dir, config, clock = pygame_env14    class TestBoost(BoostMixin):15        def __init__(self, life, name):16            pygame.sprite.Sprite.__init__(self)17            self.img_idle = pygame_surface((30, 30))18            self.img_small = pygame_surface((18, 18), 1)19            BoostMixin.__init__(self, screen, base_dir, config, name, life)20    def create_boosts():21        return [TestBoost(life, name) for life, name in boosts_params]22    def uniq_len(a):23        return len(set(a))24    # Test `add` and `remove` methods of group simply25    test_boosts = create_boosts()26    test_boost = test_boosts[0]27    test_group = BoostsGroup()28    assert len(test_group) == 029    test_group.add(test_boost)30    assert len(test_group) == 131    test_group.remove(test_boost)32    assert len(test_group) == 033    # Test `remove` method for activated boosts34    test_boosts = create_boosts()35    test_group = BoostsGroup(*test_boosts)36    for test_boost in test_boosts:37        test_group.activate(test_boost)38    test_boost = min(test_boosts, key=lambda x: x.number_in_queue)39    assert len(test_group) == uniq_len(boosts_params)40    test_group.remove(test_boost)41    assert len(test_group) == uniq_len(boosts_params) - 142    # Test `empty` method43    test_boosts = create_boosts()44    test_group = BoostsGroup(*test_boosts)45    test_group.empty()46    assert len(test_group) == len(test_group.active) == len(test_group.passive) == 047    assert test_group.next_spawn == 348    # Test `get` method without activated boosts49    test_boosts = create_boosts()50    test_boost = test_boosts[0]51    test_group = BoostsGroup(*test_boosts)52    assert test_group.get(test_boost.name) is None53    # Test `get` method with activated boosts54    test_boosts = create_boosts()55    test_group = BoostsGroup(*test_boosts)56    for test_boost in test_boosts:57        test_group.activate(test_boost)58    test_boost = test_boosts[0]59    assert test_group.get(test_boost.name)60    # Test `__contains__` method61    test_boosts = create_boosts()62    test_group = BoostsGroup(*test_boosts)63    test_boost1, test_boost2 = test_boosts[:2]64    test_group.activate(test_boost1)65    assert test_boost1.name in test_group66    assert test_boost1 in test_group67    assert test_boost2.name not in test_group68    assert test_boost2 in test_group69@pytest.mark.parametrize('buttons_sizes', [70    [(30, 45), (60, 60), (40, 60), (82, 48)],71    [(120, 38), (80, 27), (30, 32), (10, 78)],72    [(74, 52), (33, 48), (20, 12)]73])74def test_centered_buttons_group(pygame_env, buttons_sizes):75    screen, base_dir, config, clock = pygame_env76    class TestSceneButton(SceneButtonMixin):77        def __init__(self, size):78            self.screen = screen79            self.img = pygame_surface(size)80            self.rect = Rect(self.img.get_rect())81            self.rect.topleft = (randint(0, 550), randint(0, 250))82            SceneButtonMixin.__init__(self, base_dir, config, '', '', '', '')83    class TestSettingsButton(SettingsButtonMixin):84        def __init__(self, size):85            self.imgs = {True: pygame_surface(size),86                         False: pygame_surface(size, 1)}87            config_index = rstring(15)88            config['user'][config_index] = True89            SettingsButtonMixin.__init__(self, screen, config, config_index)90            self.rect = Rect(self.img.get_rect())91            self.rect.topleft = (randint(0, 550), randint(0, 250))92    def create_buttons():93        buttons = []94        rects = []95        for button_size in buttons_sizes:96            buttons.append(choice([TestSceneButton, TestSettingsButton])(button_size))97            rects.append(buttons[-1].rect)98        return buttons, rects99    # Test `add` and `remove` methods of group100    test_buttons, buttons_rects = create_buttons()101    test_button = test_buttons[0]102    test_group = CenteredButtonsGroup(config['mode'])103    assert len(test_group) == 0104    test_group.add(test_button)105    assert len(test_group) == 1106    test_group.remove(test_button)107    assert len(test_group) == 0108    # Test centering of buttons which passed to constructor109    test_group = CenteredButtonsGroup(config['mode'], *test_buttons)110    unionall_rect = buttons_rects[0].unionall(buttons_rects[1:])111    assert tuple(map(round, unionall_rect.trunc().center)) == screen.get_rect().center112    # Test centering of buttons which added after group initialization113    test_buttons, buttons_rects = create_buttons()114    test_group = CenteredButtonsGroup(config['mode'])115    test_group.add(test_buttons)116    unionall_rect = buttons_rects[0].unionall(buttons_rects[1:])117    assert tuple(map(round, unionall_rect.trunc().center)) == screen.get_rect().center118    # Remove random button and check if other buttons centered again119    remove_button = choice(test_buttons)120    buttons_rects.remove(remove_button.rect)121    test_group.remove(remove_button)122    unionall_rect = buttons_rects[0].unionall(buttons_rects[1:])123    assert tuple(map(round, unionall_rect.trunc().center)) == screen.get_rect().center124    # Test `draw` method of group125    test_buttons, buttons_rects = create_buttons()126    test_group = CenteredButtonsGroup(config['mode'], *test_buttons)127    @pygame_loop(pygame_env, 1)128    def loop1():129        test_group.draw()130    # Test `perform_point_collides` method of group131    assert test_group.perform_point_collides(test_group.sprites()[0].rect.center)132    assert not test_group.perform_point_collides((-1, -1))133@pytest.mark.parametrize('buttons_scenes', [134    [(1, 1, 2, 2), (3, 3, 1, 1), (2, 2, 1, 1)],135    [('a', 'a', 'b', 'b'), ('b', 'b', 'c', 'c'), ('a', 'a', 'b', 'b')],136    [('abc', 'def', 'asd', 'test'), ('abc', 'def', 'req', 'obr')]137])138def test_scene_buttons_group(pygame_env, buttons_scenes):139    screen, base_dir, config, clock = pygame_env140    class TestSceneButton(SceneButtonMixin):141        def __init__(self, scenes, color):142            self.screen = screen143            self.img = pygame_surface((randint(20, 80), randint(20, 80)), color)144            self.rect = Rect(self.img.get_rect())145            self.rect.topleft = (randint(20, 120), randint(20, 120))146            SceneButtonMixin.__init__(self, base_dir, config, *scenes)147    class UniqueTestInstance:148        pass149    def create_buttons():150        unique_color_scene = buttons_scenes[0][:2]151        buttons = []152        for scenes in buttons_scenes:153            if scenes[:2] == unique_color_scene:154                buttons.append(TestSceneButton(scenes, 0))155            else:156                buttons.append(TestSceneButton(scenes, 1))157        return buttons158    config['scene'], config['sub_scene'] = buttons_scenes[0][:2]159    # Test `draw` method160    test_buttons = create_buttons()161    test_group = SceneButtonsGroup(config, *test_buttons)162    @pygame_loop(pygame_env, 1)163    def loop1():164        test_group.draw()165        assert (166            most_popular_colors(screen, exclude=[(0, 0, 0)])[0] == (0, 57, 255) or167            most_popular_colors(screen, exclude=[(0, 0, 0)])[0] == (255, 46, 222)168        )169    # Test `perform_point_collides` method of group170    assert test_group.perform_point_collides(test_group.sprites()[0].rect.center)171    assert not test_group.perform_point_collides((-1, -1))172    # Test `add` and `remove` methods of group173    test_button = test_buttons[0]174    test_group = SceneButtonsGroup(config)175    assert len(test_group) == 0176    test_group.add(test_button)177    assert len(test_group) == 1178    test_group.remove(test_button)179    assert len(test_group) == 0180    # Test if group with butttons which passed in constructor181    # equals to group with buttons added after initialization182    test_group1 = SceneButtonsGroup(config, *test_buttons)183    test_group2 = SceneButtonsGroup(config)184    test_group2.add(*test_buttons)185    assert len(test_group1) == len(test_group2)186    # Test `get_by_scene` method without parameters187    config['scene'] = buttons_scenes[0][0]188    config['sub_scene'] = buttons_scenes[0][1]189    for test_button in test_group.get_by_scene():190        assert test_button.scene == config['scene']191        assert test_button.sub_scene == config['sub_scene']192    # Test `get_by_scene` method with parameters193    test_group = SceneButtonsGroup(config, *test_buttons)194    scene = buttons_scenes[1][0]195    sub_scene = buttons_scenes[1][1]196    for test_button in test_group.get_by_scene(scene, sub_scene):197        assert test_button.scene == scene198        assert test_button.sub_scene == sub_scene199    # Test `get_by_instance`200    test_group = SceneButtonsGroup(config, *test_buttons)201    assert test_group.get_by_instance(TestSceneButton) == test_buttons[0]202    assert test_group.get_by_instance(UniqueTestInstance) is None203    # Test `enter_buttons` method without parameters204    test_buttons = create_buttons()205    test_group = SceneButtonsGroup(config, *test_buttons)206    config['scene'] = buttons_scenes[0][0]207    config['sub_scene'] = buttons_scenes[0][1]208    test_group.enter_buttons()209    for test_button in test_group:210        if test_button.scene == config['scene'] and test_button.sub_scene == config['sub_scene']:211            assert test_button.action == 'enter'212        else:213            assert test_button.action == 'stop'214    # Test `enter_buttons` method with parameters215    test_buttons = create_buttons()216    test_group = SceneButtonsGroup(config, *test_buttons)217    scene = buttons_scenes[1][0]218    sub_scene = buttons_scenes[1][1]219    test_group.enter_buttons(scene, sub_scene)220    for test_button in test_group:221        if test_button.scene == scene and test_button.sub_scene == sub_scene:222            assert test_button.action == 'enter'223        else:224            assert test_button.action == 'stop'225    # Test `leave_buttons` method without parameters226    test_buttons = create_buttons()227    test_group = SceneButtonsGroup(config, *test_buttons)228    config['scene'] = buttons_scenes[0][0]229    config['sub_scene'] = buttons_scenes[0][1]230    test_group.leave_buttons()231    for test_button in test_group:232        if test_button.scene == config['scene'] and test_button.sub_scene == config['sub_scene']:233            assert test_button.action == 'leave'234        else:235            assert test_button.action == 'stop'236    # Test `leave_buttons` method with parameters237    test_buttons = create_buttons()238    test_group = SceneButtonsGroup(config, *test_buttons)239    scene = buttons_scenes[1][0]240    sub_scene = buttons_scenes[1][1]241    test_group.leave_buttons(scene, sub_scene)242    for test_button in test_group:243        if test_button.scene == scene and test_button.sub_scene == sub_scene:244            assert test_button.action == 'leave'245        else:...test_button_bar.py
Source:test_button_bar.py  
1from tkinter import ttk, messagebox, NORMAL, DISABLED, X, BOTH, Button2from comms.comms import stop_all, open_connection3from threading import Thread4from motor_tests.dir_test import DirectionTest5from motor_tests.encoder_test import EncoderTest6from motor_tests.rep_test import RepeatabilityTest7from motor_tests.back_lash_test import BacklashTest8class TestButtonBar(ttk.Frame):9    button_idx = 010    test_buttons = []11    connection_open = True12    def __init__(self, axis, settings_panel, parent):13        ttk.Frame.__init__(self, parent)14        self.axis = axis15        self.parent = parent16        self.events = parent.events17        self.log = parent.log18        self.g = parent.g19        self.test_settings = settings_panel20        self.create_widgets()21    def change_axis(self, new_axis):22        self.axis = new_axis23        self.enable_buttons()24    def enable_buttons(self):25        if self.axis.limits_found.get():26            [t.configure(state=NORMAL) for t in self.test_buttons]27        else:28            [t.configure(state=DISABLED) for t in self.test_buttons]29            self.test_buttons[0].configure(state=NORMAL)30    def _create_test_button(self, test_type, starting_state=DISABLED):31        test = test_type(self.events, self.log, self.axis, self.g)32        test_button = ttk.Button(self, text=test.name, state=starting_state)33        test_button.configure(command=lambda: self.run_test(test))34        self._place_button(test_button)35        self.test_buttons.append(test_button)36        if getattr(test, "get_settings_ui", False):37            group = ttk.LabelFrame(self.test_settings, text=test.name, padding=5)38            test.get_settings_ui(group)39            group.pack(fill=X, pady=5, padx=5)40    def _place_button(self, button):41        button.pack(fill=BOTH, expand=1, pady="5")42        self.rowconfigure(self.button_idx, weight=1)43    def manual_stop(self):44        stop_all(self.g)45        self.axis.safe_to_move = False46        self.enable_buttons()47    def run_test(self, test):48        if not self.axis.safe_to_move:49            msg = "The last motion was manually stopped. Is it now safe to proceed?"50            if messagebox.askyesno("Motor State", msg):51                self.axis.safe_to_move = True52            else:53                return54        thread = Thread(target=test.run_test, args=(self.axis,))55        thread.daemon = True56        thread.start()57        for t in self.test_buttons:58            t.configure(state=DISABLED)59        test.running.trace("w", lambda *args: self.events.put(self.enable_buttons))60    def toggle_connection(self):61        if self.connection_open:62            self.log("Closing connection")63            for t in self.test_buttons:64                t.configure(state=DISABLED)65            self.stop_button.configure(state=DISABLED)66            new_text = "Reconnect"67            self.g.GClose()68        else:69            self.log("Opening new connection")70            self.stop_button.configure(state=NORMAL)71            self.test_buttons[0].configure(state=NORMAL)72            new_text = "Disconnect"73            open_connection(self.g)74        self.disconnect_button.configure(text=new_text)75        self.connection_open = not self.connection_open76    def create_widgets(self):77        self._create_test_button(DirectionTest, NORMAL)78        self._create_test_button(EncoderTest)79        self._create_test_button(BacklashTest)80        self._create_test_button(RepeatabilityTest)81        self.axis.limits_found.trace("w", lambda *args: self.events.put(self.enable_buttons))82        self.stop_button = Button(self, text="STOP MOTORS", command=self.manual_stop, bg='#FF0000')83        self._place_button(self.stop_button)84        self.disconnect_button = ttk.Button(self, text="Disconnect", command=self.toggle_connection)85        self._place_button(self.disconnect_button)86        self._place_button(ttk.Button(self, text="Save All Axes Setup", command=self.parent.save_setup))87        self._place_button(ttk.Button(self, text="Load All Axes Setup", command=self.parent.load_setup))...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!!
