Esempio n. 1
0
    def test_left_key_returns_none(self):
        num_elements = 3
        contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)]
        cb = Checkbox(contents,
                      get_mock_input(),
                      get_mock_output(),
                      name=cb_name,
                      config={})
        cb.refresh = lambda *args, **kwargs: None

        # Checking at the start of the list
        def scenario():
            cb.deactivate()  # KEY_LEFT
            assert not cb.in_foreground

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            return_value = cb.activate()
        assert return_value is None

        # Checking at the end of the list
        def scenario():
            for i in range(num_elements):
                cb.move_down()  # KEY_DOWN x3
            cb.deactivate()  # KEY_LEFT
            assert not cb.in_foreground

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            return_value = cb.activate()
        assert return_value is None
Esempio n. 2
0
    def test_enter_on_last_returns_right(self):
        num_elements = 3
        contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)]
        cb = Checkbox(contents,
                      get_mock_input(),
                      get_mock_output(),
                      name=cb_name,
                      config={})
        cb.refresh = lambda *args, **kwargs: None

        # Checking at other elements - shouldn't return
        def scenario():
            cb.select_entry()  # KEY_ENTER
            assert cb.in_foreground  # Should still be active
            cb.deactivate(
            )  # because is not deactivated yet and would idle loop otherwise

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            return_value = cb.activate()
        assert return_value is None

        # Scrolling to the end of the list and pressing Enter - should return a correct dict
        def scenario():
            for i in range(num_elements):
                cb.move_down()  # KEY_DOWN x3
            cb.select_entry()  # KEY_ENTER
            assert not cb.in_foreground

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            return_value = cb.activate()
        assert isinstance(return_value, dict)
        assert all(
            [isinstance(key, basestring) for key in return_value.keys()])
        assert all(
            [isinstance(value, bool) for value in return_value.values()])
Esempio n. 3
0
def send_files():
    if not config.get("uuid", None):
        generate_uuid()
    uuid = config["uuid"]
    cb_contents = deepcopy(log_options)
    if config.get("last_choices", None):
        last_choices = config.get("last_choices")
        for e in cb_contents:
            if e[1] in last_choices:
                v = last_choices[e[1]]
                if len(e) > 2:
                   e[2] = v
                elif len(e) == 2:
                   e.append(v)
                else:
                   e.append(e[0])
                   e.append(v)
    choices = Checkbox(cb_contents, i, o, name="Checkbox for selecting logs to be sent").activate()
    if not choices:
        return
    config["last_choices"] = choices
    save_config(config)
    ##### DATE_STR!~
    date_str = "ololo"
    with LoadingIndicator(i, o, message="Processing files", name="Bugreport log sending loading bar") as li:
        try:
            filename = "ZPUI_logs-{}-{}.zip".format(uuid, date_str)
            bugreport = BugReport(filename)
            selected_choices = [key for key, value in choices.items() if value]
            bugreport.add_text(json.dumps(selected_choices), "bugreport_choices.json")
            for choice in selected_choices:
                 try:
                     process_choice(choice, bugreport, li)
                 except:
                     logger.exception("Failed to process {} choice".format(choice))
                     bugreport.add_text(json.dumps(traceback.format_exc()), "choice_{}_failed.json".format(choice))
        except:
            logger.exception("Failed to collect files!")
            li.stop()
            PrettyPrinter("Failed while collecting files!", i, o, 3)
            return
        try:
            li.message = "Sending files"
            bugreport.send()
        except:
            logger.exception("Failed to send files!")
            bugreport.add_text(json.dumps(traceback.format_exc()), "bugreport_sending_failed.json")
            li.stop()
            PrettyPrinter("Failed while sending files!", i, o, 3)
            try:
                location = bugreport.store_in("/boot/")
                PrettyPrinter("Stored in {}".format(location), i, o, 3)
            except:
                PrettyPrinter("Failed to store files!", i, o, 3)
            return
        else:
            li.stop()
            PrettyPrinter("Sent files successfully!", i, o, 3)
Esempio n. 4
0
    def graphical_display_redraw_runner(self, contents):
        o = get_mock_graphical_output()
        cb = Checkbox(contents, get_mock_input(), o, name=cb_name, config={})
        Canvas.fonts_dir = fonts_dir

        # Exiting immediately, but we should get at least one redraw
        def scenario():
            cb.deactivate()  # KEY_LEFT
            assert not cb.in_foreground

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            return_value = cb.activate()
        assert o.display_image.called
        assert o.display_image.call_count == 1  #One in to_foreground
Esempio n. 5
0
    def read_checklist(self):
        """
        Asks about types of memory that you'd like to read -
        for now, hardcoded to ["flash", "hfuse", "lfuse", "efuse"].
        Doesn't yet check if the MCU actually has the type of memory requested.

        This version only supports reading fuses using the 'i' mode - for now.
        """
        types = ["flash"] + self.fuse_types
        choices = [[c.capitalize(), c] for c in types]
        choices = Checkbox(
            choices,
            self.i,
            self.o,
            default_state=True,
            name="Avrdude read memory selection checkbox").activate()
        base_filename = self.read_filename
        if not choices:
            return False
        for choice in choices:
            if choices[choice]:  # Flash is read by default
                extension = "hex" if choice == "flash" else choice
                format = self.flash_format if choice == "flash" else self.fuse_format
                file_path = os.path.join(
                    self.read_dir, "{}.{}".format(base_filename, extension))
                self.p.setup_read(file_path, memtype=choice, format=format)
        return True
Esempio n. 6
0
    def shows_data_on_screen_runner(self, contents):
        i = get_mock_input()
        o = get_mock_output()
        cb = Checkbox(contents, i, o, name=cb_name, config={})

        def scenario():
            cb.deactivate()

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            cb.activate()
            #The scenario should only be called once
            assert cb.idle_loop.called
            assert cb.idle_loop.call_count == 1

        assert o.display_data.called
        assert o.display_data.call_count == 1  #One in to_foreground
        assert o.display_data.call_args[0] == (' A0', ' A1', ' A2', ' Accept')
Esempio n. 7
0
 def test_constructor(self):
     """tests constructor"""
     checkbox = Checkbox([["Option", "option"]],
                         get_mock_input(),
                         get_mock_output(),
                         name=cb_name,
                         config={})
     self.assertIsNotNone(checkbox)
Esempio n. 8
0
 def test_keymap(self):
     """tests keymap"""
     checkbox = Checkbox([["Option", "option"]],
                         get_mock_input(),
                         get_mock_output(),
                         name=cb_name,
                         config={})
     self.assertIsNotNone(checkbox.keymap)
     for key_name, callback in checkbox.keymap.iteritems():
         self.assertIsNotNone(callback)
Esempio n. 9
0
 def test_exit_label_leakage(self):
     """tests whether the exit label of one Checkbox leaks into another"""
     i = get_mock_input()
     o = get_mock_output()
     c1 = Checkbox([["a", "1"]],
                   i,
                   o,
                   name=cb_name + "1",
                   final_button_name="Name1",
                   config={})
     c2 = Checkbox([["b", "2"]],
                   i,
                   o,
                   name=cb_name + "2",
                   final_button_name="Name2",
                   config={})
     c3 = Checkbox([["c", "3"]], i, o, name=cb_name + "3", config={})
     assert (c1.exit_entry != c2.exit_entry)
     assert (c2.exit_entry != c3.exit_entry)
     assert (c1.exit_entry != c3.exit_entry)
Esempio n. 10
0
    def test_shows_data_on_screen(self):
        """Tests whether the Checkbox outputs data on screen when it's ran"""
        num_elements = 3
        contents = [["A" + str(i), "a" + str(i)] for i in range(num_elements)]
        i = get_mock_input()
        o = get_mock_output()
        cb = Checkbox(contents, i, o, name=cb_name, config={})

        def scenario():
            cb.deactivate()

        with patch.object(cb, 'idle_loop', side_effect=scenario) as p:
            cb.activate()
            #The scenario should only be called once
            assert cb.idle_loop.called
            assert cb.idle_loop.call_count == 1

        assert o.display_data.called
        assert o.display_data.call_count == 1  #One in to_foreground
        assert o.display_data.call_args[0] == (' A0', ' A1', ' A2', ' Accept')
Esempio n. 11
0
 def write_checklist(self):
     """
     Asks about types of memory that you'd like to write. When writing a bootloader,
     it adds the fuses to avrdude CLI parameters as text. When writing a .hex file or
     a backup created by read_checklist(), checks if there are additional fuse files
     present and adds them to avrdude CLI parameters.
     """
     if self.write_fuse_params:
         # Text fuse parameters detected, formatting them properly
         memory_params = [["flash", self.write_file, self.flash_format]]
         memory_params += copy(self.write_fuse_params)
     else:
         # No text fuse parameters found, looking for files
         memory_params = self.autodetect_memory_files(self.write_file)
     if memory_params:
         # If there are additional fuse files/settings present,
         # we give the user a chance to opt-out
         choices = [[type.capitalize(), type]
                    for type, _, _ in memory_params]
         # Adding the "Flash" choice in front, as we certainly have that
         # but the user might want to only flash fuses
         #choices = [["Flash", "flash"]] + choices
         choices = Checkbox(
             choices,
             self.i,
             self.o,
             default_state=True,
             name="Avrdude write memory selection checkbox").activate()
         if not choices:  # user exited the listbox
             return False  # they likely don't want to continue
         for type, value, format in memory_params:
             if choices.get(type, False):  # type selected
                 self.p.setup_write(value, memtype=type, format=format)
     else:  # No fuse files/settings found
         # Add the flash file and proceed without a checkbox, no fuses
         self.p.setup_write(self.write_file,
                            memtype="flash",
                            format=self.flash_format)
     return True
Esempio n. 12
0
def smart_scan():
    #First, getting all available interfaces
    networks = []
    interface_data = get_ip_addr()
    for interface_name in interface_data.keys():
        #Autofiltering unsuitable interfaces
        interface_info = interface_data[interface_name]
        state = interface_info["state"]
        ip = interface_info["addr"] if interface_info["addr"] else None
        if state == "up" and ip is not None:
            #Only using interface if it's up and has an IP
            #Automatically filters out localhost
            networks.append(["{}:{}".format(interface_name, ip), ip])
    if not networks:
        #No suitable interfaces found after filtering
        Printer(ffs("No suitable network interfaces found!", o.cols), i, o, 3)
        return None
    if len(networks) == 1:
        #Only one good interface, using it automatically
        network_ip = networks[0][1]
    else:
        #Allowing user to pick an interface
        network_ip = Listbox(networks, i, o).activate()
        if network_ip is None:  #Listbox exited without making a choice
            return None
    network_ip = get_network_from_ip(network_ip)
    chosen_ports = Checkbox(heuristic_ports,
                            i,
                            o,
                            name="NMap: select port types",
                            final_button_name="Run scan").activate()
    if chosen_ports is None: return None
    chosen_port_list = [
        port_choice for port_choice in chosen_ports
        if chosen_ports[port_choice] == True
    ]
    port_string = ",".join(chosen_port_list)
    #So the library I'm using is silently failing. I launch the scan from command-line and see:
    #
    #WARNING: Duplicate port number(s) specified.  Are you alert enough to be using Nmap?  Have some coffee or Jolt(tm).
    #
    #Well, thank you, but it's a script and f**k off.
    port_string = ",".join(list(set(port_string.split(","))))
    #De-duplicated and ready to go.
    print(port_string)
    Printer(ffs("Scanning {}".format(network_ip), o.cols), i, o, 0)
    nm = nmap.PortScanner()
    nm.scan(network_ip, arguments="-n -p {}".format(port_string))
    print(nm)
    show_quick_scan_results_for_network(network_ip, nm)
Esempio n. 13
0
def change_filters():
    global config
    all_types = [["Slices", 'slice'], ["Sockets", 'socket'],
                 ["Services", 'service'], ["Automounts", 'automount'],
                 ["Mounts", 'mount'], ["Timers", 'timer'], ["Paths", 'path'],
                 ["Devices", 'device'], ["Scopes", 'scope'],
                 ["Targets", 'target']]
    checkbox_contents = []
    for type in all_types:
        checkbox_contents.append(
            [type[0], type[1], type[1] in config["allowed_types"]])
    states = Checkbox(checkbox_contents, i, o).activate()
    config["allowed_types"] = [state for state in states if states[state]]
    write_config(config, config_path)
Esempio n. 14
0
def manage_contents():
    global config
    cc = []
    for action in context.get_actions():
        menu_name_or_cb = action.menu_name
        menu_name = menu_name_or_cb() if callable(
            menu_name_or_cb) else menu_name_or_cb
        name = action.full_name
        is_excluded = action.full_name not in config["excluded_actions"]
        cc.append([menu_name, name, is_excluded])
    choice = Checkbox(cc,
                      i,
                      o,
                      default_state=False,
                      name="ZeroMenu contents checkbox").activate()
    if choice:
        for action in choice:
            state = choice[action]
            if state == False and action not in config["excluded_actions"]:
                config["excluded_actions"].append(action)
            elif state == True and action in config["excluded_actions"]:
                config["excluded_actions"].remove(action)
        save_config(config)
Esempio n. 15
0
def options_menu():
    settings = settings_manager.load_settings()

    title_text = Text(display_dimensions, (0, -370), "Options", 40, black)
    about_text = Text(display_dimensions, (0, 350), "", 14, black)

    back_button = Button(display_dimensions, "Back", (10, 25), (75, 25), red, centered=False, text_color=white, text_size=14, action="back")
    buttons = [back_button]

    draw_three_checkbox = Checkbox(display_dimensions, (10, 100), centered=False, checked=settings['draw_three'])
    draw_three_label = Text(display_dimensions, (40, 100), "Draw three cards from deck", 14, black, centered=False)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit_game()
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if event.button == 1:
                    for button in buttons:
                        if button.check_if_clicked(mouse_pos):
                            if button.action == "back":
                                settings_manager.save_settings({'draw_three': draw_three_checkbox.checked})
                                start_menu()
                            else:
                                print("Button action: {} does not exist".format(button.action))

                    draw_three_checkbox.check_if_clicked(mouse_pos)

        game_display.fill(white)

        title_text.display(game_display)
        about_text.display(game_display)

        draw_three_label.display(game_display)
        draw_three_checkbox.display(game_display)

        for button in buttons:
            button.display(game_display, pygame.mouse.get_pos())

        pygame.display.update()
        clock.tick(FPS)
Esempio n. 16
0
File: main.py Progetto: joha2/pyLCI
def callback():
    result = Checkbox(checkbox_contents, i, o, "Shutdown menu").activate()
    Printer(str(result), i, o, 1)
Esempio n. 17
0
 def callback():
     print(Checkbox(checkbox_contents, i, o, "Shutdown menu").activate())