darrenburns / posting

The modern API client that lives in your terminal.
Apache License 2.0
4.48k stars 64 forks source link

Format request body that contains unicode as multi-line in .save_to_disk() (fix #48) #49

Closed devdanzin closed 1 month ago

devdanzin commented 1 month ago

This PR fixes #48 by passing allow_unicode=True to yaml.dump(). Since doing only that would include unicode characters in saved response content (which would necessitate special care when writing and reading files), we also encode to ascii with backslashreplace and save the resulting bytes.

A possible test would be:

from pathlib import Path

import yaml

from posting.collection import RequestModel

sample = """name: Test
method: POST
url: https://example.org/test
body:
  content: |-
    {
      "Hello": "There",
      "Hi": "Čau"
    }"""

request = yaml.load(sample, Loader=yaml.SafeLoader)
req = RequestModel(**request)
output = Path("output.yaml")
req.save_to_disk(output)
contents = Path("output.yaml").read_text()
print(contents)
contents_body = yaml.load(contents, Loader=yaml.SafeLoader)["body"]["content"].encode("ascii")
request_body = request["body"]["content"].encode("ascii", errors="backslashreplace")
assert contents_body == request_body