Add tests for canonicalizing device name and removed unused function.

This commit is contained in:
Sebastian Lenzlinger 2024-06-28 17:51:01 +02:00
parent 0d16d5b6a2
commit 29ca5562c6
3 changed files with 20 additions and 72 deletions

View File

@ -17,6 +17,7 @@ def add_device_guided(ctx, cn, db):
logger.info('Adding device interactively')
#logger.debug(f'Parameters: {params}. value: {value}')
@click.command('add-device', help='Add a device to a database')
@click.option('--dev', '--device-name', type=str, required=True,
help='The name of the device to be added. If this string contains spaces or other special characters \
@ -85,68 +86,3 @@ def add_device(dev, db, guided):
logger.info(f'Metadata for {dev} {device_metadata.print_attributes()}')
# @click.command('add-device', help='Add a device to a database')
# @click.option('-d', '--dev', '--device-name', type=str, required=True,
# help='The name of the device to be added. If this string contains spaces or other special characters \
# normalization is performed to derive a canonical name')
# @click.option('--db', '--database', type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
# envvar='IOTTB_DB', show_envvar=True,
# help='Name of in which to add this device. If not specified use default from config.')
# @click.option('--guided', is_flag=True, default=False, show_default=True, envvar='IOTTB_GUIDED_ADD', show_envvar=True,
# help='Add device interactively')
# # @click.option('-m', '--model', default="", help='Model of the device')
# # @click.option('--manufacturer', default="", help='Manufacturer of the device')
# # @click.option('--firmware-version', default="", help='Current firmware version of the device')
# # @click.option('--device-type', default="", help='Type of the device')
# # @click.option('-i', '--interfaces', default="", help='Supported interfaces of the device')
# # @click.option('--apps', '--companion-applications', default="", help='Companion applications of the device')
# # @click.option('--desc', '--description', default="", help='Description of the device')
# @click.pass_context
# def add_device_inactive(ctx, dev, db, guided):
# """Add a new device to a database
#
# Device name must be supplied unless in an interactive setup. Database is taken from config by default.
# """
# logger.info('add-device invoked')
# config = ctx.obj['CONFIG']
# logger.debug(f'{str(config)}')
# database = None
# # Setep1: Determine the current db
# if db:
# db_path = str(config.get_database_path)
# database = str(config.get_full_default_path())
# logger.debug(f'database: {database}. variable type: {type(database)}')
# click.echo(f'No db specified, using default database')
# if not Path(database).is_dir():
# logger.warning(f'No database at {database}')
# click.echo(f'Could not find a database.')
# click.echo(f'You need to initialize the testbed before before you add devices!')
# click.echo(f'To initialize the testbed in the default location run "iottb init-db"')
# exit()
#
# # Step 2: Check if device already exists
# if guided:
# add_device_guided(ctx, dev, database)
# else:
# device_metadata = DeviceMetadata(device_name=dev)
# device_metadata.print_attributes()
# click.echo('TODO: Unguided device add path')
#
# logger.info(f'Device {dev} added.')
def normalize_device_name(name):
"""Normalizes the device name to get a shorter representation which is easier to use at the command line.
This function derives a device name which can be more easily specified at the command line.
The first two occurrences of white space are turned into a dash, the rest of the name is dropped.
Name should be an ASCII string.
"""
logger.info(f'Normalizing name {name}')
chars_to_replace = definitions.REPLACEMENT_SET_CANONICAL_DEVICE_NAMES
pattern = re.compile('|'.join(re.escape(char) for char in chars_to_replace))
norm_name = pattern.sub('-', name, count=2)
logger.debug(f'Name after first subst: {norm_name}')
norm_name = pattern.sub('', norm_name)
logger.debug(f'Fully normalized name: {norm_name}')
return norm_name

View File

@ -184,14 +184,23 @@ def make_canonical_name(name):
"""
aliases = [name]
logger.info(f'Normalizing name {name}')
# We first normalize
chars_to_replace = definitions.REPLACEMENT_SET_CANONICAL_DEVICE_NAMES
pattern = re.compile('|'.join(re.escape(char) for char in chars_to_replace))
norm_name = pattern.sub('-', name, count=2)
norm_name = pattern.sub('-', name)
norm_name = re.sub(r'[^\x00-\x7F]+', '', norm_name) # removes non ascii chars
aliases.append(norm_name)
logger.debug(f'Name after first subst: {norm_name}')
norm_name = pattern.sub('', norm_name)
aliases.append(norm_name)
logger.debug(f'Fully normalized name: {norm_name}')
# Lower case
norm_name = norm_name.lower()
aliases.append(norm_name)
return norm_name, list(set(aliases))
# canonical name is only first two parts of resulting string
parts = norm_name.split('-')
canonical_name = canonical_name = '-'.join(parts[:2])
aliases.append(canonical_name)
logger.debug(f'Canonical name: {canonical_name}')
logger.debug(f'Aliases: {aliases}')
return canonical_name, list(set(aliases))

View File

@ -24,7 +24,10 @@ LOGLEVEL = logging.DEBUG
LOGDIR = Path.cwd() / 'logs'
# Characters to just replace
REPLACEMENT_SET_CANONICAL_DEVICE_NAMES = {' ', '_', }
REPLACEMENT_SET_CANONICAL_DEVICE_NAMES = {' ', '_', ',', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=',
'{', '}', '[', ']',
'|',
'\\', ':', ';', '"', "'", '<', '>', '?', '/', '`', '~'}
# Characters to possibly error on
ERROR_SET_CANONICAL_DEVICE_NAMES = {',', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '{', '}', '[', ']',
'|',