def from_csv(data, dialect='excel', fieldnames=None, delimiter=None, skipinitialspace=None, strict=None): dialect_params = { "delimiter": delimiter, "skipinitialspace": skipinitialspace, "strict": strict, } try: dialect = initialize_dialect(dialect, **dialect_params) except (CustomDialectFailureError, DialectNotAvailableError) as e: raise AnsibleFilterError(to_native(e)) reader = read_csv(data, dialect, fieldnames) data_list = [] try: for row in reader: data_list.append(row) except CSVError as e: raise AnsibleFilterError("Unable to process file: %s" % to_native(e)) return data_list
def test_invalid_csv(data, dialect, dialect_params, fieldnames): dialect = csv.initialize_dialect(dialect, **dialect_params) reader = csv.read_csv(data, dialect, fieldnames) result = False try: for row in reader: continue except csv.CSVError: result = True assert result
def test_valid_csv(data, dialect, dialect_params, fieldnames, expected): dialect = csv.initialize_dialect(dialect, **dialect_params) reader = csv.read_csv(data, dialect, fieldnames) result = True for idx, row in enumerate(reader): for k, v in row.items(): if expected[idx][k] != v: result = False break assert result
def main(): module = AnsibleModule( argument_spec=dict( path=dict(type='path', required=True, aliases=['filename']), dialect=dict(type='str', default='excel'), key=dict(type='str', no_log=False), fieldnames=dict(type='list', elements='str'), unique=dict(type='bool', default=True), delimiter=dict(type='str'), skipinitialspace=dict(type='bool'), strict=dict(type='bool'), ), supports_check_mode=True, ) path = module.params['path'] dialect = module.params['dialect'] key = module.params['key'] fieldnames = module.params['fieldnames'] unique = module.params['unique'] dialect_params = { "delimiter": module.params['delimiter'], "skipinitialspace": module.params['skipinitialspace'], "strict": module.params['strict'], } try: dialect = initialize_dialect(dialect, **dialect_params) except (CustomDialectFailureError, DialectNotAvailableError) as e: module.fail_json(msg=to_native(e)) try: with open(path, 'rb') as f: data = f.read() except (IOError, OSError) as e: module.fail_json(msg="Unable to open file: %s" % to_native(e)) reader = read_csv(data, dialect, fieldnames) if key and key not in reader.fieldnames: module.fail_json( msg="Key '%s' was not found in the CSV header fields: %s" % (key, ', '.join(reader.fieldnames))) data_dict = dict() data_list = list() if key is None: try: for row in reader: data_list.append(row) except CSVError as e: module.fail_json(msg="Unable to process file: %s" % to_native(e)) else: try: for row in reader: if unique and row[key] in data_dict: module.fail_json( msg="Key '%s' is not unique for value '%s'" % (key, row[key])) data_dict[row[key]] = row except CSVError as e: module.fail_json(msg="Unable to process file: %s" % to_native(e)) module.exit_json(dict=data_dict, list=data_list)