Best Python code snippet using Airtest
base.py
Source:base.py  
1# -*- coding: utf-8 -*-2from __future__ import absolute_import, print_function, unicode_literals3import warnings4from django.contrib.sites.models import Site5class AutoCMSAppMixin(object):6    auto_setup = {7        'enabled': True,8        'home title': None,9        'page title': None,10        'namespace': None,11        'config_fields': {},12        'config_translated_fields': {},13        'sites': True14    }15    @classmethod16    def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None,17                     site=None, set_home=False):18        """19        Create a single page or titles20        :param page: Page instance21        :param lang: language code22        :param auto_title: title text for the newly created title23        :param cms_app: Apphook Class to be attached to the page24        :param parent: parent page (None when creating the home page)25        :param namespace: application instance name (as provided to the ApphookConfig)26        :param set_home: mark as home page (on django CMS 3.5 only)27        :return: draft copy of the created page28        """29        from cms.api import create_page, create_title30        from cms.utils.conf import get_templates31        default_template = get_templates()[0][0]32        if page is None:33            page = create_page(34                auto_title, language=lang, parent=parent, site=site,35                template=default_template, in_navigation=True, published=True36            )37            page.application_urls = cms_app38            page.application_namespace = namespace39            page.save()40            page.publish(lang)41        elif lang not in page.get_languages():42            create_title(43                language=lang, title=auto_title, page=page44            )45            page.publish(lang)46        if set_home:47            page.set_as_homepage()48        return page.get_draft_object()49    @classmethod50    def _create_config(cls):51        """52        Creates an ApphookConfig instance53        ``AutoCMSAppMixin.auto_setup['config_fields']`` is used to fill in the data54        of the instance.55        :return: ApphookConfig instance56        """57        return cls.app_config.objects.create(58            namespace=cls.auto_setup['namespace'], **cls.auto_setup['config_fields']59        )60    @classmethod61    def _create_config_translation(cls, config, lang):62        """63        Creates a translation for the given ApphookConfig64        Only django-parler kind of models are currently supported.65        ``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data66        of the instance for all the languages.67        :param config: ApphookConfig instance68        :param lang: language code for the language to create69        """70        config.set_current_language(lang, initialize=True)71        for field, data in cls.auto_setup['config_translated_fields'].items():72            setattr(config, field, data)73        config.save_translations()74    @classmethod75    def _setup_pages(cls, config):76        """77        Create the page structure.78        It created a home page (if not exists) and a sub-page, and attach the Apphook to the79        sub-page.80        Pages titles are provided by ``AutoCMSAppMixin.auto_setup``81        :param setup_config: boolean to control whether creating the ApphookConfig instance82        """83        from cms.exceptions import NoHomeFound84        from cms.models import Page85        from cms.utils import get_language_list86        from django.conf import settings87        from django.utils.translation import override88        app_page = None89        get_url = False90        if getattr(settings, 'ALDRYN_SEARCH_CMS_PAGE', False):91            from aldryn_search.search_indexes import TitleIndex92            def fake_url(self, obj):93                return ''94            get_url = TitleIndex.get_url95            TitleIndex.get_url = fake_url96        site = Site.objects.get_current()97        auto_sites = cls.auto_setup.get('sites', True)98        if auto_sites is True or site.pk in auto_sites:99            if getattr(cls, 'app_config', False):100                configs = cls.app_config.objects.all()101                if not configs.exists():102                    config = cls._create_config()103                else:104                    config = configs.first()105            langs = get_language_list(site.pk)106            if not Page.objects.on_site(site.pk).filter(application_urls=cls.__name__).exists():107                for lang in langs:108                    with override(lang):109                        if config:110                            if cls.auto_setup['config_translated_fields']:111                                cls._create_config_translation(config, lang)112                            namespace = config.namespace113                        elif cls.app_name:114                            namespace = cls.app_name115                        else:116                            namespace = None117                        try:118                            home = Page.objects.get_home(site.pk).get_draft_object()119                        except NoHomeFound:120                            home = None121                        set_home = hasattr(Page, 'set_as_homepage')122                        home = cls._create_page(123                            home, lang, cls.auto_setup['home title'], site=site, set_home=set_home124                        )125                        app_page = cls._create_page(126                            app_page, lang, cls.auto_setup['page title'], cls.__name__, home,127                            namespace, site=site128                        )129                if get_url:130                    TitleIndex.get_url = get_url131    @classmethod132    def setup(cls):133        """134        Main method to auto setup Apphook135        It must be called after the Apphook registration::136            apphook_pool.register(MyApp)137            MyApp.setup()138        """139        try:140            if cls.auto_setup and cls.auto_setup.get('enabled', False):141                if not cls.auto_setup.get('home title', False):142                    warnings.warn(143                        '"home title" is not set in {0}.auto_setup attribute'.format(cls)144                    )145                    return146                if not cls.auto_setup.get('page title', False):147                    warnings.warn(148                        '"page title" is not set in {0}.auto_setup attribute'.format(cls)149                    )150                    return151                if cls.app_name and not cls.auto_setup.get('namespace', False):152                    warnings.warn(153                        '"page title" is not set in {0}.auto_setup attribute'.format(cls)154                    )155                    return156                config = None157                cls._setup_pages(config)158        except Exception:159            # Ignore any error during setup. Worst case: pages are not created, but the instance160            # won't break...windows.py
Source:windows.py  
1import  glfw # pip install glfw2from    OpenGL.GL import (3    glClear,4    glClearColor,5    glViewport,6    GL_COLOR_BUFFER_BIT,7)8from numpy import number # pip install PyOpenGL9from xengine.types import UNDEFINED, NONE10def resize_window(window, width, height):11    window.width = width12    window.height = height13    glViewport(0, 0, width, height)14class Window:15    def __init__(16        self,17        width: int = 720,18        heigth: int = 480,19        title: str = "XEngine Window",20        monitor: glfw._GLFWmonitor = None,21        share: glfw._GLFWwindow = None,22        setup_function = NONE,23        loop_function = NONE,24        auto_setup: bool = True,25        auto_resize: bool = True,26        limit_time: number = 10 ** 5,27        FPS: int = 6028    ):29                30        self.width =   width31        self.height =  heigth32        self.title =   title33        self.monitor = monitor34        self.share =   share35        self.setup_function = setup_function36        self.loop_function =  loop_function37        self.auto_setup =     auto_setup38        self.auto_resize =    auto_resize39        self.limit_time = limit_time40        self.FPS =        FPS41        self.internal_vars = {}42        self.GL_WINDOW = self.setup()43        self.loop()44    def setup(self):45        window = UNDEFINED46        if self.auto_setup:47            if not glfw.init(): # Initialize the window48                return49            window = glfw.create_window(self.width, self.height, self.title, self.monitor, self.share)50            if not window:51                glfw.terminate()52                return53            54            glfw.make_context_current(window) # Make the window the current window55        self.setup_function(self)56        if self.auto_setup:57            glClearColor(1, 1, 1, 1)58        if window is UNDEFINED:59            error = "UNDEFINED_ERROR: "60            error_message = "Window not created in setup function while auto_setup is set to False"61            raise Exception(error + error_message)62        if self.auto_resize:63            self.enable_resize(window)64        return window65    def loop(self):66        t = 067        while not glfw.window_should_close(self.GL_WINDOW) and t < self.limit_time:68            glfw.poll_events() # Verify events are correct69            glClear(GL_COLOR_BUFFER_BIT)70            self.loop_function(self) # Drawing code71            72            glfw.swap_buffers(self.GL_WINDOW) # Swap the Drawing buffer with the Display buffer73            t += 174        glfw.terminate() # Close75    def enable_resize(self, GL_WINDOW):...test_connect.py
Source:test_connect.py  
1from airtest.core.api import auto_setup, connect_device, set_current, init_device2class Test_connect:3    #auto_setup æ¯ä¸ä¸ªç¨æ¥ åå§åç¯å¢ çæ¥å£ï¼å®æ¥å5ä¸ªåæ°:4    #æä»¬å¯ä»¥è®¾ç½®å½åèæ¬æå¨çè·¯å¾ã æå®è¿è¡èæ¬çè®¾å¤ ã设置é»è®¤çlogè·¯å¾ãè®¾ç½®èæ¬ç¶è·¯å¾åæå®æªå¾ç²¾åº¦ï¼5    def test_auto_setup(self):6        # è¿æ¥æ¬æºé»è®¤ç«¯å£è¿çä¸å°è®¾å¤å·ä¸ºSJE5T17B17çææº7        auto_setup(__file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"])8        ## è¿æ¥æ¬æºé»è®¤ç«¯å£è¿ç设å¤å·ä¸º123å456ç䏤尿æº9        auto_setup(__file__, devices=["Android://127.0.0.1:5037/123", "Android://127.0.0.1:5037/456"])10    def test_connect_device(self):11        # è¿ä¸ç¬¬ä¸å°ææº12        dev1 = connect_device("Android://127.0.0.1:5037/serialno1")13        # è¿ä¸ç¬¬äºå°ææº14        dev2 = connect_device("Android://127.0.0.1:5037/serialno2")15        # 忢å½åæä½çææºå°åºåå·ä¸ºserialno1çææº16        set_current("serialno1")17    def test_init_device(self):18        #init_device æ¥å£åªéè¦ä¼ å
¥ 设å¤å¹³å°å设å¤çuuid å³å¯ï¼åæ°è¯¦æ
å¯ä»¥æ¥çä¸å¾ï¼19        init_device(platform="Android", uuid="SJE5T17B17")20    def test_setcurrent(self):...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!!
