示例#1
0
 def __init__(self):
     load_dotenv()
     self.__branch_nbr = STARTER
     self.__page_nbr = INITIAL_PAGE
     self.__next_page_nbr = 0
     self.__beverages_subcategories = set()
     self.__food_subcategories = set()
     self.__list_of_prods = None
     self.__subcategory = None
     self.__product = None
     self.__router = Router()
     self.__view = View()
     self.__starter_controller = StarterController()
     self.__substitute_controller = SubstituteController()
     self.__favorites_controller = FavoritesController()
     self.__trunk_controller = TrunkController()
     self.__root_controller = RootController()
     self.memory = {
         "best_products": None,
         "chosen_pair": None,
         "fav_prod": None,
         "list_of_pairs__original_v_substitutes": None,
         "list_of_products": None,
         "product": None,
         "subcategory_name": None,
         "substitute_product": None
     }
示例#2
0
    def _test_get_single_firmware(self):
        """
        Downloads a single firmware-image.
        """
        print("Test FirmwareHandler: get_single_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Imports the Firmware if already existing or downlaods it
        firmware = firmware_handler.get_firmware(router.model, release_model,
                                                 download_all)
        assert isinstance(firmware, Firmware)
        assert firmware.name == "gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin"
        assert firmware.version == "0.7.3"
        assert firmware.freifunk_verein == "ffda"
        assert firmware.release_model == "stable"
        assert firmware.file == (
            FIRMWARE_PATH +
            '/stable/sysupgrade/gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin'
        )
示例#3
0
    def _test_import_firmware(self):
        """
        Try's to get the firmware-image two times. At least the second try the firmware should be stored on the device
        and imported.
        """
        print("Test FirmwareHandler: import_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Downloads the firmware-image
        firmware_handler.download_firmware(router.model, release_model)

        # Imports the firmware-image from the local storage
        firmware = firmware_handler.get_firmware(router.model, release_model,
                                                 download_all)
        assert isinstance(firmware, Firmware)
        assert firmware.name == "gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin"
        assert firmware.version == "0.7.3"
        assert firmware.freifunk_verein == "ffda"
        assert firmware.release_model == "stable"
        assert firmware.file == (
            FIRMWARE_PATH +
            '/stable/sysupgrade/gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin'
        )
示例#4
0
    def test_create_Router(self):
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.mode = Mode.normal
        assert isinstance(router, Router)

        assert router.ip == "10.223.254.254"
        assert router.ip_mask == 16
示例#5
0
    def _test_check_hash_firmware(self):
        """
        Downloads a single firmware-image.
        """
        print("Test FirmwareHandler: check_hash_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Imports the Firmware if already existing or downloads it
        firmware = firmware_handler.get_firmware(router.model, release_model,
                                                 download_all)
        assert isinstance(firmware, Firmware)

        incorrect_hash = "2b83a03e961f2e0a7fe1817e86e9caf248fbe440d12acda5a5c78de8a7d4f25ec48282cb8562d4b3b5e3c0"
        assert not firmware.check_hash(incorrect_hash)

        assert firmware.check_hash(firmware.hash)
    def test_import_firmware(self):
        """
        Try's to get the firmware-image two times. At least the second try the firmware should be stored on the device
        and imported.
        """
        Logger().debug("Test FirmwareHandler: import_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Downlaods the firmware-image
        firmware_handler.download_firmware(router.model, release_model)

        # Imports the firmware-image from the local storage
        firmware = firmware_handler.get_firmware(router.model, release_model, download_all)
        assert isinstance(firmware, Firmware)
        assert firmware.name == "gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin"
        assert firmware.version == "0.7.3"
        assert firmware.freifunk_verein == "ffda"
        assert firmware.release_model == "stable"
        assert firmware.file == (firmware_handler.FIRMWARE_PATH +
                                 '/stable/sysupgrade/gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin')
示例#7
0
 def test_router_wget(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                     24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     self.assertRaises(Exception, network_ctrl.connect_with_remote_system())
     # Create test file 'test_wget.txt'
     path = os.path.dirname(__file__)
     file = open(path + '/test_wget.txt', 'w+')
     # The Router downloads this file via wget from the raspberryPi
     network_ctrl.remote_system_wget(path + '/test_wget.txt', '/tmp/')
     # Tests if the file has successful downloaded
     output = network_ctrl.send_command(
         "test -f '/tmp/test_wget.txt' && echo True")
     self.assertEqual(output, "['True\\n']")
     # Test
     output = network_ctrl.send_command(
         "rm '/tmp/test_wget.txt' && echo True")
     self.assertEqual(output, "['True\\n']")
     file.close()
     network_ctrl.exit()
    def test_get_single_firmware(self):
        """
        Downloads a single firmware-image.
        """
        Logger().debug("Test FirmwareHandler: get_single_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Imports the Firmware if already existing or downlaods it
        firmware = firmware_handler.get_firmware(router.model, release_model, download_all)
        assert isinstance(firmware, Firmware)
        assert firmware.name == "gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin"
        assert firmware.version == "0.7.3"
        assert firmware.freifunk_verein == "ffda"
        assert firmware.release_model == "stable"
        assert firmware.file == (firmware_handler.FIRMWARE_PATH +
                                 '/stable/sysupgrade/gluon-ffda-0.7.3-tp-link-tl-wr841n-nd-v9-sysupgrade.bin')
    def test_check_hash_firmware(self):
        """
        Downloads a single firmware-image.
        """
        Logger().debug("Test FirmwareHandler: check_hash_firmware ...")
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        assert isinstance(router, Router)

        # Create firmware_handler
        release_model = "stable"
        url = "https://firmware.darmstadt.freifunk.net"
        download_all = False
        firmware_handler = FirmwareHandler(url)
        assert isinstance(firmware_handler, FirmwareHandler)

        # Imports the Firmware if already existing or downloads it
        firmware = firmware_handler.get_firmware(router.model, release_model, download_all)
        assert isinstance(firmware, Firmware)

        incorrect_hash = "2b83a03e961f2e0a7fe1817e86e9caf248fbe440d12acda5a5c78de8a7d4f25ec48282cb8562d4b3b5e3c0"
        assert not firmware.check_hash(incorrect_hash)

        assert firmware.check_hash(firmware.hash)
示例#10
0
    def test_setup_expert(self):
        """
        This UnitTest executes the wca_setup_expert-function with the given config-file.
        It sets the values of all the  from WebInterface of the Router.
        """
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        router.mode = Mode.configuration
        assert isinstance(router, Router)
        # Config
        config = ConfigManager().get_web_interface_dict()[0]
        self.assertEqual(len(config), 30, "Wrong size of the Config-Directory")
        # Create NetworkCrtl
        network_ctrl = NetworkCtrl(router, 'eth0')
        assert isinstance(network_ctrl, NetworkCtrl)

        try:
            web_config_assist = RouterWebConfiguration(router,
                                                       config,
                                                       wizard=True)
            web_config_assist.start()
            web_config_assist.join()
        except Exception as e:
            Logger().error(str(e))
        finally:
            assert router.mode == Mode.normal
            network_ctrl.exit()
示例#11
0
    def test_create_Router(self):
        router = Router(0, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.mode = Mode.normal
        assert isinstance(router, Router)

        assert router.ip == "10.223.254.254"
        assert router.ip_mask == 16
示例#12
0
 def test_router_wget(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     self.assertRaises(Exception, network_ctrl.connect_with_remote_system())
     # Create test file 'test_wget.txt'
     path = os.path.dirname(__file__)
     file = open(path + '/test_wget.txt', 'w+')
     # The Router downloads this file via wget from the raspberryPi
     network_ctrl.remote_system_wget(path + '/test_wget.txt', '/tmp/')
     # Tests if the file has successful downloaded
     output = network_ctrl.send_command("test -f '/tmp/test_wget.txt' && echo True")
     self.assertEqual(output, "['True\\n']")
     # Test
     output = network_ctrl.send_command("rm '/tmp/test_wget.txt' && echo True")
     self.assertEqual(output, "['True\\n']")
     file.close()
     network_ctrl.exit()
    def test_setup_expert(self):
        """
        This UnitTest executes the wca_setup_expert-function with the given config-file.
        It sets the values of all the  from WebInterface of the Router.
        """
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        router.mode = Mode.configuration
        assert isinstance(router, Router)
        # Config
        config = ConfigManager().get_web_interface_dict()[0]
        self.assertEqual(len(config), 30, "Wrong size of the Config-Directory")
        # Create NetworkCrtl
        network_ctrl = NetworkCtrl(router, 'eth0')
        assert isinstance(network_ctrl, NetworkCtrl)

        try:
            web_config_assist = RouterWebConfiguration(router, config, wizard=True)
            web_config_assist.start()
            web_config_assist.join()
        except Exception as e:
            Logger().error(str(e))
        finally:
            assert router.mode == Mode.normal
            network_ctrl.exit()
示例#14
0
 def _create_router(self):
     # Create router
     router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1",
                     24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     assert isinstance(router, Router)
     return router
示例#15
0
    def test_add_information(self):
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)

        router.ssid = "lol funk"
        router.wlan_mode = WlanMode.master

        assert router.ssid == "lol funk"
        assert router.wlan_mode == WlanMode.master
示例#16
0
 def _create_router(self):
     # Create router
     router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.normal
     assert isinstance(router, Router)
     return router
示例#17
0
 def _create_router(self):
     # Create router
     router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     return router
示例#18
0
    def test_add_information(self):
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)

        router.ssid = "lol funk"
        router.wlan_mode = WlanMode.master

        assert router.ssid == "lol funk"
        assert router.wlan_mode == WlanMode.master
示例#19
0
    def test_router_info(self):
        # Create router
        router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        router.mode = Mode.normal

        router_info = RouterInfo(router)
        router_info.start()
        router_info.join()
 def test_reboot_into_config(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                     24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     router.mode = Mode.normal
     assert isinstance(router, Router)
     RouterReboot().configmode(router)
     assert router.mode == Mode.configuration
示例#21
0
def main():
    bootstrap()
    display_introduction()
    factory = Router()

    command = None
    while not is_command_exit(command):
        clear_screen()
        command = get_command()
        try:
            factory.execute_command(command)
        except Exception as e:
            print(e)
示例#22
0
 def test_connection(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     # network_ctrl.connect_with_router()
     network_ctrl.exit()
示例#23
0
 def test_connection(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                     24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     # network_ctrl.connect_with_router()
     network_ctrl.exit()
示例#24
0
    def test_optional_getter_setter(self):
        router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)

        assert isinstance(router, Router)

        router.mode = Mode.configuration
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        router.node_name = "64293-testframework1"
        router.public_key = "1234567890abcdef16171819"

        network_interface = NetworkInterface(0, "eth0")
        assert isinstance(network_interface, NetworkInterface)
        router.network_interfaces[network_interface.name] = network_interface

        cpu_process = CPUProcess(11, "root", 1.1, 11.2, "echo")
        assert isinstance(cpu_process, CPUProcess)
        router.cpu_processes.append(cpu_process)

        socket = InternetSocket()
        assert isinstance(socket, InternetSocket)
        router.sockets.append(socket)

        ram = RAM(8000, 4000, 4000, 0, 0)
        assert isinstance(ram, RAM)
        router.ram = ram

        flash_driver = Flashdriver(8000, 2000, 6000)
        assert isinstance(flash_driver, Flashdriver)
        router.flashdriver = flash_driver

        router.uci["autoupdater.settings.enabled"] = "1"

        bat_originator = BatOriginator(
            "00:00:00:00:00:00", 12.2, "01:00:01:00:01:00", "mesh0",
            ["01:00:01:00:01:00", "21:00:21:00:21:00", "03:00:03:00:03:00"])
        assert isinstance(bat_originator, BatOriginator)
        router.bat_originators.append(bat_originator)

        self.assertEqual(Mode.configuration, router.mode)
        self.assertEqual("TP-LINK TL-WR841N/ND v9", router.model)
        self.assertEqual("e8:de:27:b7:7c:e2", router.mac)
        self.assertEqual("64293-testframework1", router.node_name)
        self.assertEqual("1234567890abcdef16171819", router.public_key)
        self.assertEqual(network_interface,
                         router.network_interfaces[network_interface.name])
        self.assertEqual(cpu_process, router.cpu_processes.pop())
        self.assertEqual(socket, router.sockets.pop())
        self.assertEqual(ram, router.ram)
        self.assertEqual(flash_driver, router.flashdriver)
        self.assertEqual('Firmware not known', router.firmware.name)
        self.assertEqual("1", router.uci["autoupdater.settings.enabled"])
        self.assertEqual(bat_originator, router.bat_originators.pop())
示例#25
0
    def get_router_manual_list() -> []:
        """
        Read the Router Manual Config file

        :return: List with any Router objects from the file
        """
        output = ConfigManager.get_router_manual_config()

        router_list = []

        for i in range(0, len(output)):
            router_info = output[i]

            if not len(router_info) == 9:
                Logger().error(
                    "List must be length of 9 but has a length of {0}".format(
                        len(output)))
                return

            try:
                v = Router(i, router_info['Name'], router_info['Id'],
                           router_info['IP'], router_info['IP_Mask'],
                           router_info['CONFIG_IP'],
                           router_info['CONFIG_IP_MASK'],
                           router_info['Username'], router_info['Password'],
                           router_info['PowerSocket'])
                router_list.append(v)

            except Exception as ex:
                Logger().error(
                    "Error at building the list of Router's\nError: {0}".
                    format(ex))

        return router_list
示例#26
0
 def test_send_command(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     # Test if the command 'uname' could be send via ssh
     self.assertRaises(Exception, network_ctrl.connect_with_remote_system())
     output = network_ctrl.send_command("uname")
     self.assertEqual(output, "['Linux\\n']")
     network_ctrl.exit()
示例#27
0
 def test_send_command(self):
     # Create router
     router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1",
                     24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     # Has to be matched with the current mode (normal, configuration)
     router.mode = Mode.configuration
     assert isinstance(router, Router)
     # Create NetworkCrtl
     network_ctrl = NetworkCtrl(router, 'eth0')
     assert isinstance(network_ctrl, NetworkCtrl)
     # Test if the command 'uname' could be send via ssh
     self.assertRaises(Exception, network_ctrl.connect_with_remote_system())
     output = network_ctrl.send_command("uname")
     self.assertEqual(output, "['Linux\\n']")
     network_ctrl.exit()
    def test_optional_getter_setter(self):
        router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)

        assert isinstance(router, Router)

        router.mode = Mode.configuration
        router.model = "TP-LINK TL-WR841N/ND v9"
        router.mac = "e8:de:27:b7:7c:e2"
        router.node_name = "64293-testframework1"
        router.public_key = "1234567890abcdef16171819"

        network_interface = NetworkInterface(0, "eth0")
        assert isinstance(network_interface, NetworkInterface)
        router.network_interfaces[network_interface.name] = network_interface

        cpu_process = CPUProcess(11, "root", 1.1, 11.2, "echo")
        assert isinstance(cpu_process, CPUProcess)
        router.cpu_processes.append(cpu_process)

        socket = InternetSocket()
        assert isinstance(socket, InternetSocket)
        router.sockets.append(socket)

        ram = RAM(8000, 4000, 4000, 0, 0)
        assert isinstance(ram, RAM)
        router.ram = ram

        flash_driver = Flashdriver(8000, 2000, 6000)
        assert isinstance(flash_driver, Flashdriver)
        router.flashdriver = flash_driver

        router.uci["autoupdater.settings.enabled"] = "1"

        bat_originator = BatOriginator("00:00:00:00:00:00", 12.2, "01:00:01:00:01:00", "mesh0",
                                       ["01:00:01:00:01:00", "21:00:21:00:21:00", "03:00:03:00:03:00"])
        assert isinstance(bat_originator, BatOriginator)
        router.bat_originators.append(bat_originator)

        self.assertEqual(Mode.configuration, router.mode)
        self.assertEqual("TP-LINK TL-WR841N/ND v9", router.model)
        self.assertEqual("e8:de:27:b7:7c:e2", router.mac)
        self.assertEqual("64293-testframework1", router.node_name)
        self.assertEqual("1234567890abcdef16171819", router.public_key)
        self.assertEqual(network_interface, router.network_interfaces[network_interface.name])
        self.assertEqual(cpu_process, router.cpu_processes.pop())
        self.assertEqual(socket, router.sockets.pop())
        self.assertEqual(ram, router.ram)
        self.assertEqual(flash_driver, router.flashdriver)
        self.assertEqual('Firmware not known', router.firmware.name)
        self.assertEqual("1", router.uci["autoupdater.settings.enabled"])
        self.assertEqual(bat_originator, router.bat_originators.pop())
示例#29
0
    def get_router_auto_list(count: int = 0) -> []:
        """
        Read the Router Manual Config file

        :param count: Count of the Router
        :return: List with any Router objects from the file
        """
        output = ConfigManager.get_router_auto_config()

        if not len(output) == 10:
            Logger().error(
                "List must be length of 10 but has a length of {0}".format(
                    len(output)))
            return

        try:
            router_count = output[0]
            name = output[1]
            identifier = output[2]
            ip = output[3]
            ip_mask = output[4]
            config_ip = output[5]
            config_ip_mask = output[6]
            username = output[7]
            password = output[8]
            power_socket = output[9]

            i = identifier['default_Start_Id']
            socket_id = power_socket['powerSocket_Start_Id']
            router_list = []

            if count <= 0:
                count = router_count['router_Count']
            else:
                count = count

            for x in range(0, count):
                v = Router(x, name['default_Name'] + "{0}".format(i), i,
                           ip['default_IP'], ip_mask['default_IP_Mask'],
                           config_ip['default_CONFIG_IP'],
                           config_ip_mask['default_CONFIG_IP_MASK'],
                           username['default_Username'],
                           password['default_Password'], socket_id)
                router_list.append(v)
                i += 1
                socket_id += 1

            return router_list

        except Exception as ex:
            Logger().error(
                "Error at building the list of Router's\nError: {0}".format(
                    ex))
示例#30
0
    def get_routers_list() -> []:
        """
        Read the routers from the config

        :return: List with any router objects from the file
        """
        output = ConfigManager.get_routers_dict()

        routers = []

        # i must defined before 'for', because 'default' increase i and then the router.id has wrong count
        i = 0
        for data in output.items():

            name, router_info = data

            if 'default' in name:
                continue

            if len(router_info) != 9:  # FixMe ist eher eine schlechte idee
                logging.error(
                    "List must be length of 9 but has a length of {0}".format(
                        len(output)))
                return None

            # TODO:
            # wenn die keys im "router_info" dict mit den argument namen von `Router` passt kann man das so machen:
            # router = Router(i, **router_info)

            try:
                router = Router(i, router_info['Name'], router_info['Id'],
                                router_info['IP'], router_info['IP_Mask'],
                                router_info['CONFIG_IP'],
                                router_info['CONFIG_IP_MASK'],
                                router_info['Username'],
                                router_info['Password'],
                                router_info['PowerSocket'])
                routers.append(router)
                i += 1

            except KeyError as ex:
                logging.error(
                    "Error at building the list of Router's\nError: {0}".
                    format(ex))
                return None

        if len(routers) > 0:
            routers = sorted(routers, key=lambda e: e.id)

        return routers
示例#31
0
 def _create_router(self):
     # Create router
     router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
     router.model = "TP-LINK TL-WR841N/ND v9"
     router.mac = "e8:de:27:b7:7c:e2"
     router.node_name = "64293-testframework1"
     router.public_key = "483938492329bc12aa1212d1b"
     assert isinstance(router, Router)
     return router
示例#32
0
    def get_routers_list() -> []:
        """
        Read the Routers from the config.

        :return: List with any Router-Obj from the file
        """
        output = ConfigManager.get_routers_dict()

        if not output[0]:
            return []

        routers = []

        for data in output[1].items():

            name, router_info = data

            if 'default' in name:
                continue

            # TODO:
            # wenn die keys im "router_info" dict mit den argument namen von `Router` passt kann man das so machen:
            # router = Router(i, **router_info)

            try:
                router = Router(0, router_info['Name'], router_info['Id'],
                                router_info['IP'], router_info['IP_Mask'],
                                router_info['CONFIG_IP'],
                                router_info['CONFIG_IP_MASK'],
                                router_info['Username'],
                                router_info['Password'],
                                router_info['PowerSocket'])
                routers.append(router)

            except KeyError as ex:
                logging.error(
                    "Error at building the list of Router's\nError: {0}".
                    format(ex))
                return None

        if routers:
            routers = sorted(routers, key=lambda e: e.vlan_iface_id)

        for i, r in enumerate(routers):
            r.set_id(i)

        return routers
示例#33
0
    def test_create_Router(self):
        router = Router(0, "vlan21", 21, "10.223.254.254", 16, "192.168.1.1",
                        24, "root", "root", 1)

        assert isinstance(router, Router)

        self.assertEqual(0, router.id)
        self.assertEqual("vlan21", router.vlan_iface_name)
        self.assertEqual(21, router.vlan_iface_id)
        self.assertEqual("nsp21", router.namespace_name)
        self.assertEqual("10.223.254.254", router._ip)
        self.assertEqual(16, router._ip_mask)
        self.assertEqual("192.168.1.1", router._config_ip)
        self.assertEqual(24, router._config_ip_mask)
        self.assertEqual("root", router.usr_name)
        self.assertEqual("root", router.usr_password)
        self.assertEqual(1, router.power_socket)
from util.router_flash_firmware import RouterFlashFirmware
from router.router import Router, Mode
from config.configmanager import ConfigManager

# Create router
router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24,
                "root", "root", 1)
router.model = "TP-LINK TL-WR841N/ND v9"
router.mac = "e8:de:27:b7:7c:e2"
router.mode = Mode.configuration
# Create firware configuration
firmware_config = ConfigManager.get_firmware_dict()[0]

RouterFlashFirmware.sysupdate(router, firmware_config)
RouterFlashFirmware.sysupgrade(router, n=True)
 def __init__(self):
     self.file_lines = [EMPTY_LINE]
     self.current_line_index = FIRST_LINE_INDEX
     self.router = Router(self)
     self.end = False
示例#36
0
    def test_add_information(self):
        router = Router(0, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)

        router.ssid = "lol funk"
        assert router.ssid == "lol funk"
示例#37
0
import logging
from flask import Flask, request
from router.router import Router, CommandExecutor
from router.interface_finder import InterfaceFinder
from config.flask_config import get_config

app = Flask('Router')
config = get_config()
debug_mode = config.getboolean('router', 'debug')
logging.basicConfig(level=logging.DEBUG)

router = Router(CommandExecutor, InterfaceFinder)


@app.route('/create/network', methods=['POST'])
def create_network():
    data = request.get_json()
    router.add_network(name=data['id'])
    return 'Success\n'


@app.route('/create/logical_port', methods=['POST'])
def create_logical_port():
    data = request.get_json()
    router.add_logical_port(net=data['net_id'], ip=data['ip'])
    return 'Success\n'


app.run(config.get('router', 'listen_address'),
        config.getint('router', 'listen_port'), debug_mode)
class TextEditor:
    def __init__(self):
        self.file_lines = [EMPTY_LINE]
        self.current_line_index = FIRST_LINE_INDEX
        self.router = Router(self)
        self.end = False

    def start(self):
        print(WELCOME_TEXT_MESSAGE)
        while not self.end:
            command = input()
            self.router.get_route(command)

    @staticmethod
    def help():
        for command in ALL_POSSIBLE_COMMANDS:
            print(command)

    def new_file(self):
        self.file_lines = [EMPTY_LINE]

    def load_file(self):
        file_name = input()
        try:
            file = open(
                os.path.dirname(__file__) + PATH_TO_FILE % file_name,
                READ_FILE)
            self.file_lines = file.read().split(NEW_LINE)
            file.close()
        except FileNotFoundError:
            print(FILE_ERROR_MESSAGE)

    def save_file(self):
        file_name = input()
        file = open(
            os.path.dirname(__file__) + PATH_TO_FILE % file_name, WRITE_FILE)
        file.write(NEW_LINE.join(self.file_lines))
        file.close()

    def move_up(self):
        if not self.is_first_line():
            self.decrement_line_index()
            self.print_current_line()

    def move_down(self):
        if not self.is_last_line():
            self.increment_line_index()
            self.print_current_line()

    def page_up(self):
        start_index = self.current_line_index - PAGE_UP_DOWN_RANGE if self.current_line_index > PAGE_UP_DOWN_RANGE else 0
        for i in range(start_index, self.current_line_index):
            self.current_line_index = i
            self.print_current_line()

    def page_down(self):
        end_index = self.current_line_index + PAGE_UP_DOWN_RANGE \
            if self.get_count_lines_before_end() > PAGE_UP_DOWN_RANGE else len(self.file_lines)
        while self.current_line_index != end_index:
            self.move_down()

    def head(self):
        self.current_line_index = FIRST_LINE_INDEX
        self.print_current_line()

    def tail(self):
        self.current_line_index = self.get_last_line_index()
        self.print_current_line()

    def insert_before(self):
        self.decrement_line_index() if not self.is_first_line() else None
        self.insert_empty_line()
        self.print_current_line()

    def insert_after(self):
        self.increment_line_index()
        self.insert_empty_line()
        self.print_current_line()

    def delete(self):
        self.remove_current_line(
        ) if not self.is_first_line() else self.set_current_line(EMPTY_LINE)

    def replace(self):
        self.set_current_line(input())

    def show(self):
        start_index = self.current_line_index - SHOW_UP_DOWN_RANGE \
            if self.current_line_index > SHOW_UP_DOWN_RANGE else FIRST_LINE_INDEX
        end_index = self.current_line_index + SHOW_UP_DOWN_RANGE + 1 \
            if self.get_count_lines_before_end() > SHOW_UP_DOWN_RANGE else len(self.file_lines)
        [
            self.print_line(i)
            for i in range(start_index, self.current_line_index)
        ]
        self.print_current_line()
        [
            self.print_line(i)
            for i in range(self.current_line_index + 1, end_index)
        ]

    def exit(self):
        print(EXIT_TEXT_MESSAGE)
        self.end = True

    def get_count_lines_before_end(self):
        return self.get_last_line_index() - self.current_line_index

    def is_first_line(self):
        return self.current_line_index == FIRST_LINE_INDEX

    def is_last_line(self):
        return self.current_line_index == self.get_last_line_index()

    def insert_empty_line(self):
        self.file_lines.insert(self.current_line_index, EMPTY_LINE)

    def get_last_line_index(self):
        return len(self.file_lines) - 1

    def increment_line_index(self):
        self.current_line_index += 1

    def decrement_line_index(self):
        self.current_line_index -= 1

    def print_current_line(self):
        print(PRINT_LINE_FORMAT % (self.current_line_index + 1,
                                   self.file_lines[self.current_line_index]))

    def print_line(self, index):
        print(PRINT_LINE_FORMAT % (index + 1, self.file_lines[index]))

    def set_current_line(self, value):
        self.file_lines[self.current_line_index] = value

    def remove_current_line(self):
        if self.is_last_line():
            self.current_line_index -= 1
        self.file_lines.pop(self.current_line_index + 1)
from util.router_flash_firmware import RouterFlashFirmware
from router.router import Router, Mode
from config.configmanager import ConfigManager

# Create router
router = Router(1, "vlan1", 21, "10.223.254.254", 16, "192.168.1.1", 24, "root", "root", 1)
router.model = "TP-LINK TL-WR841N/ND v9"
router.mac = "e8:de:27:b7:7c:e2"
router.mode = Mode.configuration
# Create firware configuration
firmware_config = ConfigManager.get_firmware_dict()[0]

RouterFlashFirmware.sysupdate(router, firmware_config)
RouterFlashFirmware.sysupgrade(router, n=True)
示例#40
0
#!/usr/bin/env python

import os
import sys

root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(root)

from rpc_client import Jagare
from router.router import Router


# router
router = Router()
ip = router.lookup('lh/testproj')

# set node (host:port)
Jagare.host = ip
Jagare.port = 7303

Jagare.init('/home/vagrant/data/lh/testproj', None, True)
print Jagare.get('/home/vagrant/data/lh/testproj')
# print Jagare.list_branches('/home/vagrant/github/code-distribute/node/tmp/testproj-2')

print Jagare.host, Jagare.port
示例#41
0
def route(fin, fout):
    r = Router(grid_size=.5, maxflow_enforcement_level=3)
    r.route(fin, fout)
示例#42
0
class Controller:
    def __init__(self):
        load_dotenv()
        self.__branch_nbr = STARTER
        self.__page_nbr = INITIAL_PAGE
        self.__next_page_nbr = 0
        self.__beverages_subcategories = set()
        self.__food_subcategories = set()
        self.__list_of_prods = None
        self.__subcategory = None
        self.__product = None
        self.__router = Router()
        self.__view = View()
        self.__starter_controller = StarterController()
        self.__substitute_controller = SubstituteController()
        self.__favorites_controller = FavoritesController()
        self.__trunk_controller = TrunkController()
        self.__root_controller = RootController()
        self.memory = {
            "best_products": None,
            "chosen_pair": None,
            "fav_prod": None,
            "list_of_pairs__original_v_substitutes": None,
            "list_of_products": None,
            "product": None,
            "subcategory_name": None,
            "substitute_product": None
        }

    def get_next_page(self):
        """Returns the number of the next page to be displayed.

        Returns:
            integer: Number of the next page to be displayed
        """
        return self.__next_page_nbr

    def set_next_page_nbr(self, next_page):
        """Set the number of the next page to be displayed.

        Args:
            next_page (integer): Number of the next page to be displayed.
        """
        self.__next_page_nbr = next_page

    def get_beverage_subcategories(self):
        """Returns a list of names of the subcategories that belong to the
        Beverages category.

        Returns:
            List of strings: Names of the subcategories that belong to the
            Beverages category.
        """
        return self.__beverages_subcategories

    def set_beverages_subcategories(self, beverage_subcategories):
        """Set a list of names of the subcategories that belong to the
        Beverages category.

        Args:
            beverage_subcategories (list of strings): list of subcategories
            that belong to the Beverages category.
        """
        self.__beverages_subcategories = beverage_subcategories

    def get_food_subcategories(self):
        """Returns a list of names of the subcategories that belong to the
        Food category.

        Returns:
            List of strings: Names of the subcategories that belong to the
            Food category.
        """
        return self.__food_subcategories

    def set_food_subcategories(self, food_subcategories):
        """Set a list of names of the subcategories that belong to the
        Food category.

        Args:
            food_subcategories (list of strings): list of subcategories
            that belong to the Food category.
        """
        self.__food_subcategories = food_subcategories

    def remove_accent(self, string):
        """Take Unicode data and try to represent it in ASCII characters
        (US keyboard)

        Args:
            string (string): Text to get modified.

        Returns:
            string: Modified text.
        """
        return unidecode(string)

    def run(self):
        """Run the application by calling the very first page.
        """
        self.__view.initial_page(self.event_handler)

    def event_handler(self, branch_name, page_nbr, choice, *args):
        """Analyzes the choice made by the user.

        Args:
            branch_name (integer): The number of the branch where the user
            is located.
            page_nbr (integer): The number of the page where the user is
            located.
            choice (integer): The choice made by the user.
        """
        if branch_name == FAVORITES:
            self.__favorites_controller.analyze(self, page_nbr, choice, *args)
        elif branch_name == ROOT_BRANCH:
            self.__root_controller.analyze(self, page_nbr, choice, *args)
        elif branch_name == STARTER:
            self.__starter_controller.analyze(self, page_nbr, choice, *args)
        elif branch_name == SUBSTITUTE:
            self.__substitute_controller.analyze(self, page_nbr, choice, *args)

        elif branch_name == TRUNK_BRANCH:
            self.__trunk_controller.analyze(self, page_nbr, choice, *args)
        else:
            self.home_page()

        self.__router.go_to(self)

    def go_to_previous_page(self):
        """Go to the previous page via the router."""
        self.__next_page_nbr = self.__next_page_nbr - 1
        self.__router.go_to(self)

    def is_empty(self, items_list):
        """Check if a list is empty.

        Args:
            items_list (list): List to get verified

        Returns:
            Boolean: True if the list is empty or else False.
        """
        return not items_list

    def manage_menu_header(self, choice):
        """Analyze the choice made by the user.
        This part checks if the user wants to go to the main menu,
        to the previous page or if he wants to leave the application.

        Args:
            choice (integer): Choice of the user.
        """
        if choice == 1:
            self.set_next_page_nbr(HOME_PAGE)
        elif choice == 2:
            self.go_to_previous_page()
        elif choice == 3:
            logger.info(F"""
            {PROGRAM_QUIT_BY_USER}
            """)
            sys.exit()

    def create_db_page(self):
        """Call the view in order to display the create database page.
        """
        self.__view.create_db_page(self.event_handler)

    def db_created_page(self):
        """Call the view in order to display the page that indicate the
        database has been created.
        """
        self.__view.db_created_page(self.event_handler)

    def home_page(self):
        """Update the food and beverage list, then call the view, which
        in turn will call the main menu page.
        """
        try:
            if self.is_empty(self.__beverages_subcategories):
                self.set_beverages_subcategories(Category.get_beverages_list())

            if self.is_empty(self.__food_subcategories):
                self.set_food_subcategories(Category.get_food_list())

            self.__view.home_page(self.event_handler)
        except InterfaceError:  # Unable to connect to the database
            e_traceback = traceback.format_exc()
            logger.error(f"""
            {ERROR_COLOR}
            ******************************************
            {e_traceback}
            ******************************************
            Error!
            Unable to access the database.
            Maybe the database server did not start
            or the connection elements are not correct.
            ******************************************
            {ic()} {NORMAL_COLOR}""")
            sys.exit(ic())

        except DBAPIError:  # <= any database error
            e_traceback = traceback.format_exc()
            logger.error(f"""
            {ERROR_COLOR}
            ******************************************
            {e_traceback}
            ******************************************
            Error!
            Unable to drop nor create the database
            Something went wrong with the database.
            ******************************************
            {ic()} {NORMAL_COLOR}""")
            sys.exit(ic())
        except Exception as e:
            e_traceback = traceback.format_exc()
            logger.error(f"""
            {ERROR_COLOR}
            ******************************************
            {e_traceback}
            ******************************************
            Unable to drop nor create the database
            {str(e)}
            ******************************************
            {ic()} {NORMAL_COLOR}""")
            sys.exit(ic())

    def substitute_a_food(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to substitute a food.
        """
        self.__view.substitute_a_food_page(self.memory,
                                           self.__food_subcategories,
                                           self.event_handler)

    def substitute_a_beverage(self, **kwargs):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to substitute a beverage.
        """
        self.__view.substitute_a_beverage_page(self.memory,
                                               self.__beverages_subcategories,
                                               self.event_handler)

    def get_prod_from_a_food(self):
        """Store in memory a list of products in order to be used if the user
        go back to a previous page.
        Then call the view which in turn will call the view that will display
        the page when the user wants to get a product which is a food.
        """
        self.memory["list_of_products"] = list(
            Product.get_products_from_subcategory(
                FOOD, self.memory["subcategory_name"]))

        self.__view.get_prod_from_a_food_page(self.memory, self.event_handler)

    def get_prod_from_a_beverage(self):
        """Store in memory a list of products in order to be used if the user
        go back to a previous page.
        Then call the main view which in turn will call the view that will
        display the page when the user wants to get a product which is a
        beverage.
        """
        self.memory["list_of_products"] = list(
            Product.get_products_from_subcategory(
                BEVERAGES, self.memory["subcategory_name"]))

        self.__view.get_prod_from_a_beverage_page(self.memory,
                                                  self.event_handler)

    def details_of_a_food_prod(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to see the details of a product which is a
        food.
        """
        self.__view.details_of_a_food_prod_page(self.memory,
                                                self.event_handler)

    def details_of_a_beverage_prod(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to see the details of a product which is a
        beverage.
        """
        self.__view.details_of_a_beverage_prod_page(self.memory,
                                                    self.event_handler)

    def get_a_better_food(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to see a list of better food.
        """
        self.__view.get_a_better_food(self.memory, self.event_handler)

    def get_a_better_beverage(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to see a list of better beverages.
        """
        self.__view.get_a_better_beverage(self.memory, self.event_handler)

    def added_to_fav_food(self):
        """Call the main view which in turn will call the view that will display
        the page when a food has been add to the favorite substitutes.
        """
        self.__view.added_to_fav_food(self.event_handler)

    def added_to_fav(self):
        """Call the main view which in turn will call the view that will display
        the page when a beverage has been add to the favorite substitutes.
        """
        self.__view.added_to_fav(self.event_handler)

    def favorites_page(self, **kwargs):
        """Store the favorite products in memory then call the main view which
        in turn will call the view that will display the page when the user
        wants to see his favorite products.
        """
        try:
            self.memory["list_of_pairs__original_v_substitutes"] = (
                Product.get_favorites())

            self.__view.favorites_page(self.memory, self.event_handler)
        except Exception as e:
            e_traceback = traceback.format_exc()
            logger.error(f"""
            {ERROR_COLOR}
            ******************************************
            {e_traceback}
            ******************************************
            {str(e)}""")
            sys.exit(ic())

    def list_of_favs(self):
        """Call the main view which in turn will call the view that will display
        the page when the user wants to see the favorite substitutes of one
        product.
        """
        self.__view.list_of_favs(self.memory, self.event_handler)

    def one_fav_deleted(self):
        """Call the main view which in turn will call the view that will display
        the page that indicates a substitute has been deleted.
        """
        self.__view.one_fav_deleted(self.event_handler)