Beispiel #1
0
 def setup_method(self):
     """Initialize the test instances."""
     # pylint: disable=attribute-defined-outside-init
     devices = load_yaml_config(
         get_fixture_path('public', 'config', 'devices.yaml'))
     devices_config = {
         fqdn: device.get('config', {})
         for fqdn, device in devices.items()
     }
     self.devices = Devices(devices, devices_config)
     self.devices_with_private = Devices(
         devices, devices_config,
         load_yaml_config(
             get_fixture_path('private', 'config', 'devices.yaml')))
Beispiel #2
0
def setup_tmp_path(file_name, path):
    """Initialize the temporary directory and configuration."""
    output = path / 'output'
    output.mkdir()
    config = load_yaml_config(get_fixture_path('cli', file_name))
    config['base_paths']['output'] = str(output)
    return output, config
Beispiel #3
0
def main(argv: Optional[list] = None) -> int:
    """Run the Homer CLI.

    Arguments:
        argv (list): the command line arguments to parse.

    Returns:
        int: ``0`` on success, ``1`` on failure.

    """
    args = argument_parser().parse_args(argv)
    logging.basicConfig(level=args.loglevel)
    if args.loglevel != logging.DEBUG:  # Suppress noisy loggers
        logging.getLogger("absl").setLevel(logging.WARNING)
        logging.getLogger('ncclient').setLevel(logging.WARNING)

    kwargs = {}
    if args.action == 'commit':
        kwargs['message'] = args.message
    elif args.action == 'diff':
        kwargs['omit_diff'] = args.omit_diff

    config = load_yaml_config(args.config)
    runner = Homer(config)
    return getattr(runner, args.action)(args.query, **kwargs)
Beispiel #4
0
def test_load_yaml_config_ipaddress_objects():
    """It should return the configuration with IP addresses, networks and interfaces converted into objects."""
    config = load_yaml_config(get_fixture_path('config', 'ipaddress.yaml'))
    assert isinstance(config['ipv4'], ipaddress.IPv4Address)
    assert isinstance(config['ipv6'], ipaddress.IPv6Address)
    assert isinstance(config['networkv4'], ipaddress.IPv4Network)
    assert isinstance(config['networkv6'], ipaddress.IPv6Network)
    assert isinstance(config['interfacev4'], ipaddress.IPv4Interface)
    assert isinstance(config['interfacev6'], ipaddress.IPv6Interface)
    assert isinstance(config['non_parsable_interface'], str)
    assert isinstance(config['non_parsable_ip'], str)
Beispiel #5
0
def test_main(tmp_path):
    """It should execute the whole program based on CLI arguments."""
    output = tmp_path / 'output'
    output.mkdir()
    config = load_yaml_config(get_fixture_path('cli', 'config.yaml'))
    config['base_paths']['output'] = str(output)
    config_path = tmp_path / 'config.yaml'
    with open(str(config_path), 'w') as f:
        yaml.dump(config, f)

    assert cli.main(
        ['-c', str(config_path), 'device1.example.com', 'generate']) == 0
Beispiel #6
0
def test_load_yaml_config_valid():
    """Loading a valid config should return its content."""
    config = load_yaml_config(get_fixture_path('config', 'valid.yaml'))
    assert 'key' in config
Beispiel #7
0
def test_load_yaml_config_raise():
    """Loading an invalid config should raise Exception."""
    with pytest.raises(HomerError, match='Could not load config file'):
        load_yaml_config(get_fixture_path('config', 'invalid.yaml'))
Beispiel #8
0
def test_load_yaml_config_no_content(name):
    """Loading an empty or non-existent config should return an empty dictionary."""
    assert {} == load_yaml_config(get_fixture_path('config', name))
Beispiel #9
0
    def __init__(self, main_config: Mapping):
        """Initialize the instance.

        Arguments:
            main_config (dict): the configuration dictionary.

        """
        logger.debug('Initialized with configuration: %s', main_config)
        self._main_config = main_config
        self.private_base_path = self._main_config['base_paths'].get(
            'private', '')
        self._config = HierarchicalConfig(
            self._main_config['base_paths']['public'],
            private_base_path=self.private_base_path)

        self._netbox_api = None
        self._device_plugin = None
        if self._main_config.get('netbox', {}):
            self._netbox_api = pynetbox.api(
                self._main_config['netbox']['url'],
                token=self._main_config['netbox']['token'])
            if self._main_config['netbox'].get('plugin', ''):
                self._device_plugin = import_module(  # type: ignore
                    self._main_config['netbox']
                    ['plugin']).NetboxDeviceDataPlugin

        devices_all_config = load_yaml_config(
            os.path.join(self._main_config['base_paths']['public'], 'config',
                         'devices.yaml'))
        devices_config = {
            fqdn: data.get('config', {})
            for fqdn, data in devices_all_config.items()
        }

        netbox_inventory = self._main_config.get('netbox',
                                                 {}).get('inventory', {})
        if netbox_inventory:
            devices = NetboxInventory(
                self._netbox_api, netbox_inventory['device_roles'],
                netbox_inventory['device_statuses']).get_devices()
        else:
            devices = devices_all_config.copy()
            for data in devices.values():
                data.pop('config', None)

        private_devices_config: Dict = {}
        if self.private_base_path:
            private_devices_config = load_yaml_config(
                os.path.join(self.private_base_path, 'config', 'devices.yaml'))

        self._ignore_warning = self._main_config.get('transports', {}).get(
            'junos', {}).get('ignore_warning', False)
        self._transport_username = self._main_config.get('transports', {}).get(
            'username', '')
        self._transport_ssh_config = self._main_config.get(
            'transports', {}).get('ssh_config', None)
        self._devices = Devices(devices, devices_config,
                                private_devices_config)
        self._renderer = Renderer(self._main_config['base_paths']['public'],
                                  self.private_base_path)
        self._output_base_path = pathlib.Path(
            self._main_config['base_paths']['output'])