Skip to content

Commit

Permalink
Skeleton for pytest tests, so I can at least try and verify the app s…
Browse files Browse the repository at this point in the history
…till runs under Django version X.Y

Because while I don't haystack often anymore, I'd like to keep it working for when I do.
  • Loading branch information
kezabelle committed Feb 27, 2016
1 parent 6fdeb2c commit b935ee3
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 7 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -4,3 +4,5 @@ haystackbrowser/panels.py
dist
django_haystackbrowser.egg-info
*.pickle
.eggs
db.sqlite3
14 changes: 14 additions & 0 deletions conftest.py
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import django
from django.conf import settings
import os


HERE = os.path.realpath(os.path.dirname(__file__))


def pytest_configure():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests_settings")
if settings.configured and hasattr(django, 'setup'):
django.setup()
15 changes: 15 additions & 0 deletions demo_project.py
@@ -0,0 +1,15 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import sys
sys.dont_write_bytecode = True

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests_settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
7 changes: 6 additions & 1 deletion haystackbrowser/admin.py
@@ -1,4 +1,6 @@
from django.core.paginator import Paginator, InvalidPage
from haystack.exceptions import SearchBackendError

try:
from django.utils.encoding import force_text
except ImportError: # < Django 1.5
Expand Down Expand Up @@ -385,7 +387,7 @@ def view(self, request, content_type, pk):
:return: A template rendered into an HttpReponse
"""
if not self.has_change_permission(request, None):
raise PermissionDenied
raise PermissionDenied("Not a superuser")

query = {DJANGO_ID: pk, DJANGO_CT: content_type}
try:
Expand All @@ -395,6 +397,9 @@ def view(self, request, content_type, pk):
except IndexError:
raise Search404("Search result using query {q!r} does not exist".format(
q=query))
except SearchBackendError as e:
raise Search404("{exc!r} while trying query {q!r}".format(
q=query, exc=e))

more_like_this = ()
# the model may no longer be in the database, instead being only backed
Expand Down
25 changes: 25 additions & 0 deletions haystackbrowser/test_app.py
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
from django.core.urlresolvers import reverse, resolve
from .admin import Search404


def test_app_is_mounted_accessing_changelist_but_no_models_loaded(admin_user, rf):
url = reverse('admin:haystackbrowser_haystackresults_changelist')
request = rf.get(url)
request.user = admin_user
match = resolve(url)
with pytest.raises(Search404):
match.func(request, *match.args, **match.kwargs)


def test_app_is_mounted_viewing_details_but_no_models_loaded(admin_user, rf):
url = reverse('admin:haystackbrowser_haystackresults_change',
kwargs={'content_type': 1, 'pk': 1})
request = rf.get(url)
request.user = admin_user
match = resolve(url)
with pytest.raises(Search404):
match.func(request, *match.args, **match.kwargs)
38 changes: 38 additions & 0 deletions setup.cfg
@@ -0,0 +1,38 @@
[pytest]
norecursedirs=.* *.egg .svn _build src bin lib local include
python_files=test_*.py
addopts = --cov haystackbrowser --cov-report term --cov-report html -vvv

[metadata]
license-file = LICENSE

[wheel]
universal = 1

[flake8]
max-line-length = 80

[check-manifest]
ignore-default-rules = true
ignore =
.travis.yml
.bumpversion.cfg
PKG-INFO
.eggs
.idea
.tox
__pycache__
bin
include
lib
local
share
.Python
*.egg-info
*.egg-info/*
setup.cfg
.hgtags
.hgignore
.gitignore
.bzrignore
*.mo
51 changes: 45 additions & 6 deletions setup.py
@@ -1,15 +1,42 @@
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand


class PyTest(TestCommand):
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []

def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True

def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)



def make_readme(root_path):
consider_files = ('README.rst', 'LICENSE', 'CHANGELOG', 'CONTRIBUTORS')
for filename in consider_files:
filepath = os.path.realpath(os.path.join(root_path, filename))
if os.path.isfile(filepath):
with open(filepath, mode='r') as f:
yield f.read()


HERE = os.path.abspath(os.path.dirname(__file__))
SHORT_DESC = """A reusable Django application for viewing and debugging
all the data that has been pushed into Haystack"""
LONG_DESCRIPTION = "\r\n\r\n----\r\n\r\n".join(make_readme(HERE))

REQUIREMENTS = [
'Django>=1.2.0',
'django-haystack>=1.2.0',
'django-classy-tags>=0.3.4.1',
]

TROVE_CLASSIFIERS = [
'Development Status :: 3 - Alpha',
Expand Down Expand Up @@ -38,7 +65,19 @@
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
url='https://github.com/kezabelle/django-haystackbrowser/tree/master',
packages=PACKAGES,
install_requires=REQUIREMENTS,
install_requires=[
'Django>=1.3.1',
'django-haystack>=1.2.0',
'django-classy-tags>=0.3.4.1',
],
tests_require=[
'django-haystack>=1.2.0',
'pytest>=2.6.4',
'pytest-cov>=1.8.1',
'pytest-django>=2.8.0',
'pytest-remove-stale-bytecode>=1.0',
],
cmdclass={'test': PyTest},
classifiers=TROVE_CLASSIFIERS,
platforms=['OS Independent'],
package_data={'': [
Expand Down
70 changes: 70 additions & 0 deletions tests_settings.py
@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*-
import os


DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', 'TESTTESTTESTTESTTESTTESTTESTTEST')
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,testserver').split(',')
BASE_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))


DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'django.contrib.auth',
# need sessions for Client.login() to work
'django.contrib.sessions',
'django.contrib.admin',
'haystack',
'haystackbrowser',
]

SKIP_SOUTH_TESTS = True
SOUTH_TESTS_MIGRATE = False

STATIC_URL = '/__static__/'
MEDIA_URL = '/__media__/'
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True


ROOT_URLCONF = 'tests_urls'

# Use a fast hasher to speed up tests.
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)

SITE_ID = 1

TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

STATIC_ROOT = os.path.join(BASE_DIR, 'tests_collectstatic')
MEDIA_ROOT = os.path.join(BASE_DIR, 'tests_media')

TEMPLATE_DIRS = ()
USE_TZ = True

HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
8 changes: 8 additions & 0 deletions tests_urls.py
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from django.contrib import admin


urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]

0 comments on commit b935ee3

Please sign in to comment.