Skip to content

Commit

Permalink
Make print_block_string work with string proxy objects (#153)
Browse files Browse the repository at this point in the history
  • Loading branch information
fugal-dy authored Dec 27, 2021
1 parent 7c0d73a commit 02f349b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/graphql/language/block_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ def print_block_string(value: str, prefer_multiple_lines: bool = False) -> str:
For internal use only.
"""
if not isinstance(value, str):
value = str(value) # resolve lazy string proxy object

is_single_line = "\n" not in value
has_leading_space = value.startswith(" ") or value.startswith("\t")
has_trailing_quote = value.endswith('"')
Expand All @@ -95,12 +98,12 @@ def print_block_string(value: str, prefer_multiple_lines: bool = False) -> str:
)

# Format a multi-line block quote to account for leading space.
result = (
before = (
"\n"
if print_as_multiple_lines and not (is_single_line and has_leading_space)
else ""
) + value
if print_as_multiple_lines:
result += "\n"
)
after = "\n" if print_as_multiple_lines else ""
value = value.replace('"""', '\\"""')

return '"""' + result.replace('"""', '\\"""') + '"""'
return f'"""{before}{value}{after}"""'
9 changes: 9 additions & 0 deletions tests/language/test_block_string.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import cast

from graphql.language.block_string import (
dedent_block_string_value,
print_block_string,
Expand Down Expand Up @@ -144,3 +146,10 @@ def correctly_prints_string_with_a_first_line_indentation():
assert print_block_string(s) == join_lines(
'"""', " first ", " line ", "indentation", " string", '"""'
)

def correctly_prints_lazy_stings():
class LazyString:
def __str__(self):
return "lazy"

assert print_block_string(cast(str, LazyString())) == '"""lazy"""'

0 comments on commit 02f349b

Please sign in to comment.