Pycharm with Django throws ImportError: cannot import name 'unittest'

Pycharm with Django throws ImportError: cannot import name 'unittest'

我正在学习 Django 教程,并试图通过 PyCharm 使测试用例达到 运行。但是我遇到了一个问题。当我 运行 命令时:app test

我遇到了这个异常:测试框架意外退出:

F:\programming\Python\python.exe "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py" test a F:\programming\Projects\pycharm\untitled
Testing started at 4:54 PM ...
Traceback (most recent call last):
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 157, in <module>
    utility.execute()
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_manage.py", line 110, in execute
    from django_test_runner import is_nosetest
  File "F:\programming\JetBrains\PyCharm 2017.2.4\helpers\pycharm\django_test_runner.py", line 42, in <module>
    from django.utils import unittest
ImportError: cannot import name 'unittest'

Process finished with exit code 1

显然,django_test_manage.py 文件不起作用。我怎样才能解决这个问题? 即使 test.py class 为空,也会发生这种情况。所以一定是 PyCharm then(?) 的问题 我正在使用 PyCharm Pro 2017.2.4、Django 2.0 和 Python 3.6 我的 run/debug 配置只是 PyCharm 所做的基本预设 Django 设置。

django.utils.unittest 在 Django 1.9 中被删除所以我怀疑你可能使用的是旧版本的教程。

在 pycharm 中,您使用的是 django.tests.testcases 运行 配置吗?最好使用 Python unittest.TestCase 详细 here

编辑:所以在 django_test_runner.py 中你有以下内容:

from django.test.testcases import TestCase
from django import VERSION

# See: https://docs.djangoproject.com/en/1.8/releases/1.7/#django-utils-unittest
# django.utils.unittest provided uniform access to the unittest2 library on all Python versions.
# Since unittest2 became the standard library's unittest module in Python 2.7,
# and Django 1.7 drops support for older Python versions, this module isn't useful anymore.
# It has been deprecated. Use unittest instead.
if VERSION >= (1,7):
  import unittest
else:
  from django.utils import unittest

所以您在测试 运行config 的解释器中使用的 django 版本似乎是 < 1.7(当 django.utils.unittest 被弃用时。)如果您这样做会返回什么 from django import VERSION 并在你的解释器中打印出来?

我认为这是 Pycharm 的 django_test_runner.py 中的错误。

在我的 pycharm 中,代码是:

  if VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest

但是你(和我)使用 Django 2.0,所以 pycharm import 'from django.utils import unittest' ...

我已经这样修改了我的 test_runner :

  if VERSION[0] > 1 or VERSION[1] >= 7:
    import unittest
  else:
    from django.utils import unittest

你需要在其他地方用同样的技巧修改同一个文件。

工作顺利!

新的 PyCharm 修复了这个错误。

如果更新 PyCharm 不是一个选项,您可以在 django_test_runner.py 上更改以下行:

 if VERSION[1] >= 7:
   import unittest
 else:
   from django.utils import unittest

至:

 if VERSION >= (1, 7):
   import unittest
 else:
   from django.utils import unittest

再次在第 56 行更改为:

if VERSION >= (1, 6):

最后在第 256 行更改为:

if VERSION >= (1, 1):

为什么?因为VERSION指的是django的版本,已经勾选到2点了。

django_test_runner.py其实问题更多。有用的是用这个版本替换它:https://gist.github.com/IlianIliev/6f884f237ab52d10aa0e22d53df97141

可以在<pycharm_root>/helpers/pycharm

中找到