Search code examples
djangopycharmdjango-testing

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


I am working through the Django tutorial, and am trying to get the test cases to run with PyCharm. I have encountered a problem however. When I run the command: app test

I am faced with this exception: test framework quit unexpectedly:

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

Apparently, the django_test_manage.py file does not work. How can I fix this? this happens even when the test.py class is empty. So it must be a problem with PyCharm then(?) I am using PyCharm Pro 2017.2.4, Django 2.0 and Python 3.6 My run/debug configurations are just the basic, preset Django Settings that PyCharm does.


Solution

  • The new PyCharm has this bug fixed.

    If update PyCharm is not an option, you can change the following lines on django_test_runner.py:

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

    to:

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

    Again at line 56 change to:

    if VERSION >= (1, 6):
    

    And finally at line 256 change to:

    if VERSION >= (1, 1):
    

    Why? Because the VERSION refers to the version of django, which has ticked over to 2 point something.