def test_format_header(): r"""Test formatting header.""" kws_all = dict(field_names=['name', 'number', 'value', 'complex'], field_units=['n/a', 'g', 'cm', 'n/a']) res_all = dict(names="# name\tnumber\tvalue\tcomplex\n", units="# n/a\tg\tcm\tn/a\n") if platform._is_win: # pragma: windows kws_all['format_str'] = "%5s\t%l64d\t%g\t%g%+gj\n" res_all['format'] = "# " + kws_all['format_str'] else: kws_all['format_str'] = "%5s\t%ld\t%g\t%g%+gj\n" res_all['format'] = "# " + kws_all['format_str'] kws_all['dtype'] = serialize.cformat2nptype(kws_all['format_str'], names=kws_all['field_names']) for x in [kws_all, res_all]: for k, v in x.items(): if isinstance(v, str): x[k] = v.encode("utf-8") elif isinstance(v, list): x[k] = [iv.encode("utf-8") for iv in v] test_list = [(['format_str', 'field_names', 'field_units'], ['names', 'units', 'format']), (['field_names', 'field_units', 'dtype'], ['names', 'units', 'format']), (['field_units', 'dtype'], ['names', 'units', 'format']), (['field_names'], ['names']), (['field_units'], ['units'])] for kws_keys, res_keys in test_list: kws = {k: kws_all[k] for k in kws_keys} res = b''.join([res_all[k] for k in res_keys]) assert (serialize.format_header(**kws) == res) with pytest.raises(ValueError): serialize.format_header()
def write_header(self): r"""Write header lines to the file based on the serializer info.""" if self.header_was_written: return header_msg = serialize.format_header( format_str=self.serializer.format_str, field_names=self.serializer.get_field_names(as_bytes=True), field_units=self.serializer.get_field_units(as_bytes=True), comment=self.comment, newline=self.newline, delimiter=self.delimiter) self.fd.write(header_msg) self.header_was_written = True
def serialize_file_header(self): r"""Return the serialized header information that should be prepended to files serialized using this class. Returns: bytes: Header string that should be written to the file. """ out = serialize.format_header( format_str=self.format_str, field_names=self.get_field_names(as_bytes=True), field_units=self.get_field_units(as_bytes=True), comment=self.comment, newline=self.newline, delimiter=self.delimiter) return out