Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a readable test-case for a diff which includes "\n"

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')])
  • not to mention that this isn't easy to read.

Is there a way to write expected with triple quotes (as above) in such a way that result==expected will work?

like image 823
ignoring_gravity Avatar asked Jul 12 '20 09:07

ignoring_gravity


Video Answer


1 Answers

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 raw 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
like image 142
xavc Avatar answered Sep 29 '22 20:09

xavc