def test_file_output(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') handle, filename = tempfile.mkstemp() os.close(handle) try: stream = StringIO() yaml.dump(data, stream, allow_unicode=True) data1 = stream.getvalue() if PY3: stream = BytesIO() yaml.dump(data, stream, encoding='utf-16-le', allow_unicode=True) data2 = stream.getvalue().decode('utf-16-le')[1:] with open(filename, 'w', encoding='utf-16-le') as stream: yaml.dump(data, stream, allow_unicode=True) with open(filename, 'r', encoding='utf-16-le') as fp0: data3 = fp0.read() with open(filename, 'wb') as stream: yaml.dump(data, stream, encoding='utf-8', allow_unicode=True) with open(filename, 'r', encoding='utf-8') as fp0: data4 = fp0.read() else: with open(filename, 'wb') as stream: yaml.dump(data, stream, allow_unicode=True) with open(filename, 'rb') as fp0: data2 = fp0.read() with open(filename, 'wb') as stream: yaml.dump(data, stream, encoding='utf-16-le', allow_unicode=True) with open(filename, 'rb') as fp0: data3 = fp0.read().decode('utf-16-le')[1:].encode('utf-8') stream = _unicode_open(open(filename, 'wb'), 'utf-8') yaml.dump(data, stream, allow_unicode=True) stream.close() with open(filename, 'rb') as fp0: data4 = fp0.read() assert data1 == data2, (data1, data2) assert data1 == data3, (data1, data3) assert data1 == data4, (data1, data4) finally: if os.path.exists(filename): os.unlink(filename)
def dump_str(self, data: any, **kwargs) -> str: """ Return the YAML object as a string. Properties: data<any>: The YAML object. **kwargs: Options for the YAML dump. Returns: The YAML object as a string. """ stream = StringIO() super().dump(data, stream, **kwargs) output_str = stream.getvalue() stream.close() return output_str