为包含 "\n" 的差异编写可读的测试用例

mar*_*lli 6 python string diff

我有一个result看起来像这样的字符串:

>>> 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)"

Run Code Online (Sandbox Code Playgroud)

我想为此编写一个测试用例。一种(不太容易阅读)的写法是

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'
Run Code Online (Sandbox Code Playgroud)

进而

assert result == expected
Run Code Online (Sandbox Code Playgroud)

会工作。

另一种更具可读性的方式是

    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)"

        """
    )
Run Code Online (Sandbox Code Playgroud)

但是之后

assert result == expected
Run Code Online (Sandbox Code Playgroud)

不再有效。

我认为\n琴弦内部很难做类似的事情

'\n'.join([i[8:] for i in expected.split('\n')])
Run Code Online (Sandbox Code Playgroud)
  • 更不用说这不容易阅读。

有没有办法以这样的方式expected用三重引号(如上)写result==expected

xav*_*avc 3

您可以使用textwrap.dedent查找并删除常见的前导空格,这对于获得三引号字符串的正确缩进很有用。请注意,我还使用str.lstrip删除初始换行符,IMO 使字符串更易于阅读,而不是将起始三引号放在与---. 最后,为了避免转义\'s,r可以使用 aw 字符串。

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
Run Code Online (Sandbox Code Playgroud)