Подтвердить что ты не робот

Нос не находит тесты Django

Я пытаюсь использовать Django-нос в моем текущем проекте, но я не могу понять, как получить нос для запуска моих тестов. Поэтому я начал простой проект Django 1.4.1, чтобы узнать нос. Но даже в этом простом тестовом проекте я мог бы запустить его.

Прежде чем продолжить: я знаю, что в Stackoverflow есть много похожих вопросов, например, например:

Как сообщить Django-носу, где мои тесты?

Но после Googling вокруг, читая сообщения в блогах и ответы StackOverflow, я все равно не смог его запустить.

Как я установил свой тестовый проект

  • Создание виртуальной среды.
  • pip install django django-nose nose.
  • Создайте проект с помощью django-admin.py startproject djangonosetest.
  • Создать приложение manage.py startapp testapp
  • Измените settings.py:

    • Установите ENGINE в django.db.backends.sqlite3
    • Добавлен django_nose, testapp в INSTALLED_APPS
    • Добавлено TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'.
  • Запустите manage.py test

Но все, что я получил, это результат:

nosetests --verbosity 1
Creating test database for alias 'default'...

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
Destroying test database for alias 'default'...

Но, по крайней мере, должен быть запущен тестовый пример по умолчанию.

Когда я запустил python manage.py test djangonosetest.testapp.tests:SimpleTest, он запустит тест. Но это кажется немного излишним, если я должен был сделать это для каждого тестового файла, который у меня есть. Но это доказывает, что тесты могут выполняться.

Когда я запустил manage.py test -v 3 (высокий уровень детализации), это показало:

nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/settings.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/settings.pyc is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/urls.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/wsgi.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/testapp/models.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/testapp/models.pyc is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/testapp/views.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/testapp/tests.py is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/djangonosetest/testapp/tests.pyc is executable; skipped
nose.selector: INFO: /Users/Jens/Projects/Django/djangonosetest/manage.py is executable; skipped

Нос определенно находит мои test.py, но по какой-то причине пропускает его.

Структура папки

djangonosetest/
    djangonosetest/
        __init__.py
        settings.py
        testapp/
            __init__.py
            models.py
            tests.py
            views.py
        urls.py
        wsgi.py
    manage.py

settings.py

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', '[email protected]'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected too.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique and don't share it with anybody.
SECRET_KEY = 'ikh^t)[email protected](o)go_129zdr87*im00m^[email protected]_n!w4ec'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'djangonosetest.urls'

# Python dotted path to the WSGI application used by Django runserver.
WSGI_APPLICATION = 'djangonosetest.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django_nose',
    'djangonosetest.testapp',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

Код проверки

Тестовый код является стандартным TestCase, созданным Django.

"""
This file demonstrates writing tests using the unit test module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from Django.test import TestCase


class SimpleTest(TestCase):
    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)

Итак, как мне сказать Django-нос/нос, где мои тесты?

UPDATE

Если вы нашли интересный ответ Google Groups и ответ Stackoverflow на тему:

Оба сводятся к тому, что нос пропускает исполняемые файлы. Вот почему я получаю tests.py is executable; skipped. Проблема в том, что файл не является исполняемым:

----------+ 1 Jens  staff  383 13 Okt 00:01 tests.py

Я также пробовал его с u-x, g-x и o-x, но нос пропускал в любом случае. У меня такое чувство, что это ошибка. Файл находится в носе, не является исполняемым, но все же пропускается.

Обходным решением является использование -exe-переключателя. Выполняется тест manage.py test --exe. Хотя это лучше, чем другие обходные пути, я не совсем доволен этим решением.

4b9b3361

Ответ 1

У меня была такая же проблема сегодня, и я ее исправил.

Try:

chmod a-x djangonosetest/djangonosetest/testapp/*.py

Ответ 2

Я думаю, возможно, что в Django 1.4 вам нужно указать проект в установленных приложениях, если вы не укажете корень проекта. Вместо 'testapp' попробуйте 'djangonosetest.testapp'

https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-INSTALLED_APPS см. их пример.