带有django的Pycharm抛出ImportError:无法导入名称'unittest'

问题描述 投票:7回答:4

我正在通过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类为空,也会发生这种情况。所以它一定是pycharm的问题然后(?)我正在使用Pycharm Pro 2017.2.4,Django 2.0和Python 3.6我的运行/调试配置只是pycharm所做的基本的,预设的Django设置

谢谢!!

django pycharm django-testing
4个回答
6
投票

新的PyCharm修复了这个bug。

如果更新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指向的东西。


6
投票

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

在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

因此,您在测试运行配置的解释器中使用的django版本似乎<1.7(当django.utils.unittest被弃用时。)如果您执行from django import VERSION并在解释器中打印它,会返回什么?


2
投票

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

在我的pycharm中,代码是:

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

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

我修改了我的test_runner:

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

您需要使用相同的技巧修改其他地方的同一文件。

这是工作 !


1
投票

django_test_runner.py实际上存在更多问题。有什么帮助是用这个版本替换它:https://gist.github.com/IlianIliev/6f884f237ab52d10aa0e22d53df97141

它可以在<pycharm_root>/helpers/pycharm找到

© www.soinside.com 2019 - 2024. All rights reserved.