I have a string result
which looks like this:
>>> result
'--- \n+++ \n@@ -48,7 +48,7 @@\n "%%time\\n",\n "def hello(name: str = \\"world\\"):\\n",\n "\\n",\n- " return f\'hello {name}\'\\n",\n+ " return f\\"hello {name}\\"\\n",\n "\\n",\n "\\n",\n "hello(3)"\n'
>>> print(result)
---
+++
@@ -48,7 +48,7 @@
"%%time\n",
"def hello(name: str = \"world\"):\n",
"\n",
- " return f'hello {name}'\n",
+ " return f\"hello {name}\"\n",
"\n",
"\n",
"hello(3)"
I'd like to write a test case for this. One (not so easy to read) way to write this would be
expected = '--- \n+++ \n@@ -48,7 +48,7 @@\n "%%time\\n",\n "def hello(name: str = \\"world\\"):\\n",\n "\\n",\n- " return f\'hello {name}\'\\n",\n+ " return f\\"hello {name}\\"\\n",\n "\\n",\n "\\n",\n "hello(3)"\n'
and then
assert result == expected
would work.
Another more readable way would be
expected = (
"""
---
+++
@@ -48,7 +48,7 @@
"%%time\n",
"def hello(name: str = \"world\"):\n",
"\n",
- " return f'hello {name}'\n",
+ " return f\"hello {name}\"\n",
"\n",
"\n",
"hello(3)"
"""
)
but then
assert result == expected
no longer works.
I think that the \n
inside the strings make it hard to do something like
'\n'.join([i[8:] for i in expected.split('\n')])
Is there a way to write expected
with triple quotes (as above) in such a way that result==expected
will work?
You can use textwrap.dedent
to find and remove common leading whitespace, which is useful for getting correct indentation for triple-quoted strings. Note that I also use str.lstrip
to remove the initial newline, which IMO makes the string easier to read, instead of putting the start triple quote on the same line as the ---
. Finally, in order to avoid escaping the \
's, a r
aw string can be used.
import textwrap
result = '--- \n+++ \n@@ -48,7 +48,7 @@\n "%%time\\n",\n "def hello(name: str = \\"world\\"):\\n",\n "\\n",\n- " return f\'hello {name}\'\\n",\n+ " return f\\"hello {name}\\"\\n",\n "\\n",\n "\\n",\n "hello(3)"\n'
expected = textwrap.dedent(
r"""
---
+++
@@ -48,7 +48,7 @@
"%%time\n",
"def hello(name: str = \"world\"):\n",
"\n",
- " return f'hello {name}'\n",
+ " return f\"hello {name}\"\n",
"\n",
"\n",
"hello(3)"
"""
).lstrip()
assert expected == result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With