【问题标题】:Invalid syntax error while running unit test in django在 django 中运行单元测试时出现无效的语法错误
【发布时间】:2018-07-18 16:17:08
【问题描述】:

我的示例 django 项目工作正常,我得到了结果,但问题是每当我在我的项目上运行单元测试时,我都会在 test.py 中得到如下语法错误。我尝试使用 .format() 仍然显示错误。为什么我不能使用 f'this is my text' 来格式化我的字符串? 错误日志

ERROR: blog.tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: blog.tests
Traceback (most recent call last):
File "/usr/lib/python3.5/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib/python3.5/unittest/loader.py", line 369, in
  _get_module_from_name
__import__(name)
File "/home/blog/tests.py", line 28
self.assertEqual(f'{self.post.title}', 'Content')
                                    ^
SyntaxError: invalid syntax

【问题讨论】:

  • 你能提一下你的测试吗?

标签: python django python-3.x unit-testing format-string


【解决方案1】:

f-strings 仅在 Python 3.6+ 中有效。

但是似乎没有任何理由在此处使用它们,因为您没有进行任何插值。为什么不只是self.assertEqual(self.post.title, 'Content')

【讨论】:

  • 有人可能会指出,这假设self.post.title 是一个str 开头(这似乎是一个合理的假设)。
  • 是的,没错。如果没有,str(self.post.title) 仍然是更好的选择。
猜你喜欢
  • 2014-11-09
  • 2021-03-30
  • 2017-07-21
  • 1970-01-01
  • 2013-01-01
  • 2015-11-21
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
相关资源
最近更新 更多