Best Python code snippet using localstack_python
set_wifi.py
Source:set_wifi.py  
1#2# set_wifi.py3#4# Copyright (C) 2014 - 2018 Kano Computing Ltd.5# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv26#7import os8from gi import require_version9require_version('Gtk', '3.0')10from gi.repository import Gtk, Gdk, GObject11import threading12import kano_settings.common as common13from kano_settings.templates import Template14from kano.gtk3.buttons import OrangeButton, KanoButton15from kano_settings.components.heading import Heading16from kano.gtk3.kano_dialog import KanoDialog17from kano.network import is_internet, network_info, launch_browser18from kano_settings.system.proxy import get_all_proxies, set_all_proxies, test_proxy19class SetWifi(Template):20    wifi_connection_attempted = False21    def __init__(self, win):22        Template.__init__(self, "", _("to be set"), _("COMPLETE"))23        self.win = win24        self.win.set_main_widget(self)25        self.kano_button.connect('button-release-event', self.win.go_to_home)26        internet_img = Gtk.Image()27        # Very hacky way to centre the Proxy button - put spaces in the label28        self.proxy_button = OrangeButton(_("Proxy  "))29        self.proxy_button.connect('button-release-event', self.go_to_proxy)30        self.disable_proxy = OrangeButton(_("Disable proxy"))31        self.win.change_prev_callback(self.win.go_to_home)32        self.win.top_bar.enable_prev()33        internet_status = Gtk.Label()34        internet_status_style = internet_status.get_style_context()35        internet_status.set_alignment(xalign=1, yalign=0.5)36        internet_action = Gtk.Label()37        internet_action_style = internet_action.get_style_context()38        internet_status_style.add_class('internet_status_top')39        internet_action_style.add_class('internet_status_bottom')40        internet_action.set_alignment(xalign=1, yalign=0.5)41        status_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)42        status_box.props.valign = Gtk.Align.CENTER43        configure_container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)44        container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)45        container.pack_start(status_box, False, False, 2)46        container.pack_start(internet_img, False, False, 2)47        self.box.pack_start(container, False, False, 0)48        network_info_dict = network_info()49        common.has_internet = is_internet()50        if not common.has_internet or not network_info_dict:51            if network_info_dict:52                description = _("Use the browser to log in or configure proxy")53            else:54                description = _("Configure wireless")55            title = _("Get connected")56            self.add_connection = KanoButton(_("WIFI"))57            self.add_connection.connect('button_release_event', self.configure_wifi)58            # We removed the ability to use keyboard to click, so we also remove ability59            # to get keyboard focus60            self.add_connection.set_can_focus(False)61            # For now, this is removed as the event listener is interefering with the62            # kano-connect63            #self.add_connection.connect("key_release_event", self.configure_wifi)64            status_box.pack_start(self.add_connection, False, False, 0)65            internet_img.set_from_file(common.media + "/Graphics/Internet-noConnection.png")66            internet_status.set_text(_("No network found"))67            self.kano_button.set_label(_("BACK"))68            status_box.pack_start(configure_container, False, False, 3)69            go_to_portal_button = OrangeButton(_("Browser Login"))70            go_to_portal_button.connect('button-press-event', self.cb_launch_browser)71            configure_container.pack_start(go_to_portal_button, False, False, 0)72            divider_label = Gtk.Label("|")73            configure_container.pack_start(divider_label, False, False, 3)74            configure_container.pack_end(self.proxy_button, False, False, 0)75        else:76            self.kano_button.set_label(_("COMPLETE"))77            status_box.pack_start(internet_status, False, False, 3)78            status_box.pack_start(internet_action, False, False, 3)79            status_box.pack_start(configure_container, False, False, 3)80            network = network_info_dict.keys()[0]81            ip = network_info_dict[network]['address']82            network_text = network_info_dict[network]['nice_name']83            internet_img.set_from_file(common.media + "/Graphics/Internet-Connection.png")84            internet_status.set_text(network_text)85            internet_action.set_text(ip)86            go_to_portal_button = OrangeButton(_("Browser Login"))87            go_to_portal_button.connect('button-press-event', self.cb_launch_browser)88            configure_container.pack_start(go_to_portal_button, False, False, 0)89            if network_text == 'Ethernet':90                title = _("Connection found!")91                description = _("You're on a wired network")92                # Change to ethernet image here93                internet_img.set_from_file(common.media + "/Graphics/Internet-ethernetConnection.png")94            else:95                title = _("Connection found!")96                description = _("You're on a wireless network")97                divider_label = Gtk.Label("|")98                configure_container.pack_start(divider_label, False, False, 3)99                configure_button = OrangeButton(_("Configure"))100                configure_button.connect('button_press_event', self.configure_wifi)101                configure_container.pack_start(configure_button, False, False, 0)102            divider_label = Gtk.Label("|")103            configure_container.pack_start(divider_label, False, False, 3)104            configure_container.pack_end(self.proxy_button, False, False, 0)105        self.title.title.set_text(title)106        self.title.description.set_text(description)107        self.win.show_all()108    def cb_launch_browser(self, control, signal):109        # start the default browser to visit the default page110        launch_browser()111    def go_to_proxy(self, widget, event):112        self.win.clear_win()113        SetProxy(self.win)114    def configure_wifi(self, widget=None, event=None):115        # If is a mouse click event or key pressed is ENTER116        if not hasattr(event, 'keyval') or event.keyval == Gdk.KEY_Return:117            self.kano_button.set_sensitive(True)118            self.wifi_connection_attempted = True119            # Blur window120            self.win.blur()121            self.win.show_all()122            # Force blur to be shown123            while Gtk.events_pending():124                Gtk.main_iteration()125            # Call WiFi config126            os.system('/usr/bin/kano-wifi-gui')127            # Refresh window after WiFi Setup128            self.win.unblur()129            self.win.clear_win()130            SetWifi(self.win)131class SetProxy(Gtk.Box):132    def __init__(self, win):133        Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)134        self.kano_button = KanoButton()135        self.win = win136        self.win.set_main_widget(self)137        self.heading = Heading(138            _("Proxy"),139            _("Connect via a friend")140        )141        grid = Gtk.Grid(column_homogeneous=False, column_spacing=10, row_spacing=10)142        self.kano_button.connect('button-release-event', self.apply_changes)143        self.kano_button.connect('key-release-event', self.apply_changes)144        self.win.top_bar.enable_prev()145        self.win.change_prev_callback(self.go_to_wifi)146        self.ip_entry = Gtk.Entry()147        self.ip_entry.props.placeholder_text = _("IP address")148        self.ip_entry.connect('key-release-event', self.proxy_enabled)149        self.username_entry = Gtk.Entry()150        self.username_entry.props.placeholder_text = _("Username")151        self.username_entry.connect('key-release-event', self.proxy_enabled)152        self.port_entry = Gtk.Entry()153        self.port_entry.props.placeholder_text = _("Port")154        self.port_entry.connect('key-release-event', self.proxy_enabled)155        self.password_entry = Gtk.Entry()156        self.password_entry.props.placeholder_text = _("Password")157        self.password_entry.set_visibility(False)158        self.password_entry.connect('key-release-event', self.proxy_enabled)159        password_box = Gtk.Box()160        password_box.add(self.password_entry)161        self.checkbutton = Gtk.CheckButton(_("enable proxy"))162        self.read_config()163        self.checkbutton.connect('clicked', self.proxy_status)164        self.checkbutton.set_can_focus(False)165        bottom_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)166        bottom_row.pack_start(self.checkbutton, False, False, 0)167        bottom_row.pack_start(self.kano_button, False, False, 60)168        bottom_row.set_margin_bottom(30)169        bottom_row.set_margin_left(70)170        grid.attach(self.ip_entry, 0, 0, 2, 2)171        grid.attach(self.username_entry, 0, 2, 2, 2)172        grid.attach(self.port_entry, 2, 0, 2, 2)173        grid.attach(password_box, 2, 2, 3, 2)174        grid_alignment = Gtk.Alignment(xscale=0, xalign=0.5, yscale=0, yalign=0.2)175        grid_alignment.add(grid)176        self.pack_start(self.heading.container, False, False, 0)177        self.pack_start(grid_alignment, True, True, 0)178        self.pack_end(bottom_row, False, False, 0)179        self.proxy_status(self.checkbutton)180        self.kano_button.set_sensitive(False)181        # Change text of kano button depending on if proxy is enabled182        if self.checkbutton.get_active():183            self.kano_button.set_label(_("ENABLE PROXY"))184        else:185            self.kano_button.set_label(_("DISABLE PROXY"))186        self.win.show_all()187    def clear_entries(self):188        self.ip_entry.set_text("")189        self.username_entry.set_text("")190        self.port_entry.set_text("")191        self.password_entry.set_text("")192    def go_to_wifi(self, widget=None, event=None):193        self.win.clear_win()194        SetWifi(self.win)195    # Update for proxy196    def read_config(self):197        self.enable_proxy, data, _ = get_all_proxies()198        self.enabled_init = self.enable_proxy199        if self.enable_proxy:200            try:201                self.ip_entry.set_text(data['host'])202                self.port_entry.set_text(data['port'])203                if data['username']:204                    self.username_entry.set_text(data['username'])205                if data['password']:206                    self.password_entry.set_text(data['password'])207            except:208                # Something went wrong > disable proxy209                set_all_proxies(False)210                common.proxy_enabled = False211                self.enable_proxy = False212                self.enabled_init = False213                self.clear_entries()214        self.checkbutton.set_active(self.enable_proxy)215    def apply_changes(self, button, event):216        # If enter key is pressed or mouse button is clicked217        if not hasattr(event, 'keyval') or event.keyval == 65293:218            # This is a callback called by the main loop, so it's safe to219            # manipulate GTK objects:220            watch_cursor = Gdk.Cursor(Gdk.CursorType.WATCH)221            self.win.get_window().set_cursor(watch_cursor)222            self.kano_button.start_spinner()223            self.kano_button.set_sensitive(False)224            def lengthy_process():225                if self.enable_proxy:226                    host = self.ip_entry.get_text()227                    port = self.port_entry.get_text()228                    username = self.username_entry.get_text()229                    password = self.password_entry.get_text()230                    set_all_proxies(enable=True, host=host, port=port, username=username, password=password)231                    common.proxy_enabled = True232                    success, text = test_proxy()233                    if not success:234                        title = _("Error with proxy")235                        description = text236                        return_value = 1237                        # disable proxy if we couldn't successfully enable it238                        set_all_proxies(False)239                        common.proxy_enabled = False240                    else:241                        title = _("Successfully enabled proxy")242                        description = ""243                        return_value = 0244                else:245                    set_all_proxies(False)246                    common.proxy_enabled = False247                    title = _("Successfully disabled proxy")248                    description = ""249                    return_value = 0250                def done(title, description, return_value):251                    kdialog = KanoDialog(252                        title,253                        description,254                        [255                            {256                                'label': _("OK"),257                                'color': 'green',258                                'return_value': return_value259                            }260                        ],261                        parent_window=self.win262                    )263                    response = kdialog.run()264                    self.win.get_window().set_cursor(None)265                    self.kano_button.stop_spinner()266                    if response == 0:267                        self.go_to_wifi()268                    elif response == 1:269                        self.checkbutton.set_active(False)270                        self.kano_button.set_sensitive(False)271                GObject.idle_add(done, title, description, return_value)272            thread = threading.Thread(target=lengthy_process)273            thread.start()274    # Validation functions275    # If the "enable proxy" checkbox is checked/uncheckout, this function is activated276    # Disables the text entries if enable proxy is not checked277    def proxy_status(self, widget):278        self.enable_proxy = widget.get_active()279        if self.enable_proxy:280            self.ip_entry.set_sensitive(True)281            self.port_entry.set_sensitive(True)282            self.password_entry.set_sensitive(True)283            self.username_entry.set_sensitive(True)284            # Run to see if it need enabling285            self.proxy_enabled()286            self.kano_button.set_label(_("ENABLE PROXY"))287        else:288            self.ip_entry.set_sensitive(False)289            self.port_entry.set_sensitive(False)290            self.password_entry.set_sensitive(False)291            self.username_entry.set_sensitive(False)292            self.kano_button.set_label(_("DISABLE PROXY"))293            self.kano_button.set_sensitive(True)294    # if proxy enabled: ip address, port are mandatory295    def proxy_enabled(self, widget=None, event=None):296        # Get IP address297        # Get port298        # Get299        # If these entries are non empty, good - else, disable the next button300        ip_text = self.ip_entry.get_text()301        port_text = self.port_entry.get_text()302        if ip_text == "" or port_text == "":303            self.kano_button.set_sensitive(False)304            return False305        else:306            self.kano_button.set_sensitive(True)307            return True...test_container.py
Source:test_container.py  
...30        container = ServiceContainer({31            'command_name': "the_test",32            'log_level': 'INFO'33        })34        configure_container(container)35        assert_true(container.get('logger'))36    @staticmethod37    def test_get_logger_raises_on_missing_params():38        """StreamQuery - ServiceContainer - get - logger - raises"""39        container = ServiceContainer({})40        configure_container(container)41        assert_raises(ValueError, container.get, 'logger')42    @staticmethod43    def test_get_everything_else():44        """StreamQuery - ServiceContainer - get - other"""45        container = ServiceContainer({46            'command_name': "the_test",47            'log_level': 'INFO',48            'aws_region': 'us-nowhere-1',49            'kinesis_auth_mode': 'iam_role',50            'kinesis_stream': 'aaaa',51            'athena_auth_mode': 'iam_role',52            'athena_database': 'test',53            'athena_results_bucket': 'test',54        })55        configure_container(container)56        assert_true(container.get('streamalert_forwarder'))57        assert_true(container.get('athena'))58        assert_true(container.get('query_parameter_generator'))59        assert_true(container.get('query_pack_repository'))60        assert_true(container.get('query_pack_manager_factory'))61        assert_true(container.get('boto3_kinesis_client'))62        assert_true(container.get('boto3_athena_client'))63    @staticmethod64    def test_get_raises_on_missing():65        """StreamQuery - ServiceContainer - get - other"""66        container = ServiceContainer({})67        configure_container(container)...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!!
