1. Marc Condon
  2. Simply Rocking The Future

Commits

Marc Condon  committed 692109b

added tests and templates for s3songs

  • Participants
  • Parent commits 9540988
  • Branches default

Comments (0)

Files changed (13)

File sfgeek/apps/helpers/test/__init__.py

View file
  • Ignore whitespace
+

File sfgeek/apps/helpers/test/base.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+"""
+helpers.test.base
+
+Test classes based on Django TestCase
+
+* created: 2013-07-21 Kevin Chan <kefin@makedostudio.com>
+* updated: 2013-10-27 kchan
+"""
+
+from django.utils import unittest
+from django.test import TestCase
+from django.test.client import Client
+from django.test.client import RequestFactory
+
+from garage import get_setting as _s
+from helpers.test.utils import (
+    msg,
+    create_test_users,
+    get_field_error,
+)
+
+
+VERBOSITY = _s('TEST_VERBOSITY', 0)
+
+
+class SimpleTestCase(unittest.TestCase):
+    """
+    Test case based on Python unittest TestCase.
+    """
+    # verbose output
+    verbosity = VERBOSITY
+
+    def _msg(self, *args, **kwargs):
+        """
+        Utility method to print out verbose test and debug messages.
+        * print output only if verbosity level is above 2.
+        """
+        if self.verbosity > 2:
+            msg(*args, **kwargs)
+
+
+# number of users to create for tests
+NUM_TEST_USERS = 1
+
+class ProfileUserTestCase(TestCase):
+    """
+    Test case with utility methods for logging in users and testing
+    content for authenticated users.
+    """
+    # verbose output
+    verbosity = VERBOSITY
+
+    def _msg(self, *args, **kwargs):
+        """
+        Utility method to print out verbose test and debug messages.
+        * print output only if verbosity level is above 2.
+        """
+        if self.verbosity > 2:
+            msg(*args, **kwargs)
+
+    def setUp(self, num_test_users=NUM_TEST_USERS):
+        """
+        Do setup for tests.
+        """
+        if hasattr(self, 'client') and self.client:
+            self.c = self.client
+        else:
+            self.c = Client()
+        self.users = create_test_users(num_test_users)
+        self.base_user = self.users[0]
+        self.factory = RequestFactory()
+
+    def _login(self, username=None, password=None):
+        """
+        Log in test user using Django auth login().
+        """
+        if not username:
+            username = self.base_user.username
+        if not password:
+            password = self.base_user.password
+        return self.c.login(username=username, password=password)
+
+    def _logout(self):
+        """
+        Log out user.
+        """
+        self.c.logout()
+
+    def _verify_form_errors(self, form, fields, error=True, print_msg=False):
+        """
+        Utility method to verify form field errors.
+
+        :param form: form instance
+        :param fields: list of fields to verify
+        :param error: assert error if True, assert no error if False
+        :param print_msg: print form error message if assertion fails
+        """
+        started = False
+        for field in fields:
+            e = get_field_error(form, field)
+            if error:
+                if not e and print_msg:
+                    if not started:
+                        print u''
+                        started = True
+                    self._msg('%s error' % field, e)
+                self.assertTrue(e is not None)
+            else:
+                if e and print_msg:
+                    if not started:
+                        print u''
+                        started = True
+                    self._msg('%s error' % field, e)
+                self.assertTrue(e is None)

File sfgeek/apps/helpers/test/settings.py

View file
  • Ignore whitespace
+#-*- coding: utf-8 -*-
+"""
+helpers.test.settings
+
+Settings for test utils.
+
+* created: 2013-07-20 Kevin Chan <kefin@makedostudio.com>
+* updated: 2013-10-27 kchan
+"""
+
+from garage import get_setting as _s
+
+
+# template to define test users
+# * each part contains a '%s' for appending a suffix to the base
+# ('username_base', 'password_base', 'email_base',)
+DEFAULT_TEST_USER_TEMPLATE = (
+    'testuser_%s',
+    'aVCYboFx3x_%s',
+    'testuser_%s@example.com',
+)
+TEST_USER_TEMPLATE = _s('TEST_USER_TEMPLATE', DEFAULT_TEST_USER_TEMPLATE)
+
+# divider for test diagnostic printouts (used by msg())
+DIVIDER = '# ----------------------------------------------------------------------'

File sfgeek/apps/helpers/test/utils.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+"""
+helpers.test.utils
+
+Utility functions for tests (using Django test runner).
+
+* created: 2013-07-20 kevin chan <kefin@makedostudio.com>
+* updated: 2013-11-21 kchan
+"""
+
+from django.contrib.auth.models import User
+
+from garage.utils import safe_unicode
+from garage import get_setting as _s
+from helpers.test.settings import TEST_USER_TEMPLATE, DIVIDER
+from helpers.txt.utils import uprint
+
+
+# helper functions
+
+def msg(label, txt, first=False, linebreak=False, divider=DIVIDER):
+    """
+    Print out debug message.
+    """
+    if first:
+        uprint(u'\n%s' % safe_unicode(divider))
+    label = safe_unicode(label)
+    txt = safe_unicode(txt)
+    if not linebreak:
+        uprint(u'# %-16s : %s' % (label, txt))
+    else:
+        uprint(u'# %-16s :\n%s' % (label, txt))
+
+
+def module_exists(module_name):
+    """
+    Check if module is importable.
+
+    :param module_name: name of module to import (basestring)
+    :returns: True if importable else False
+    """
+    try:
+        __import__(module_name)
+    except ImportError:
+        return False
+    else:
+        return True
+
+
+class DummyObject(object):
+    """
+    Generic object for testing.
+    """
+    def __init__(self, *args, **kwargs):
+        for k, v in kwargs.items():
+            if not k.startswith('_'):
+                setattr(self, k, v)
+
+
+class UserInfo(object):
+    """
+    Simple object to store info for test user.
+    """
+    # verbose output
+    verbosity = _s('TEST_VERBOSITY', 0)
+
+    def __init__(self, username, password, email):
+        self.username = username
+        self.password = password
+        self.email = email
+        self.user = self.create_user()
+
+    def _msg(self, *args, **kwargs):
+        """
+        Utility method to print out verbose test and debug messages.
+        * print output only if verbosity level is above 2.
+        """
+        if self.verbosity > 2:
+            msg(*args, **kwargs)
+
+    def create_user(self):
+        """
+        Utility method to create user.
+        """
+        if self.username and self.password and self.email:
+            user = User.objects.create_user(
+                    self.username,
+                    password=self.password,
+                    email=self.email)
+        else:
+            user = None
+        return user
+
+    def set_staff_status(self, is_staff):
+        """
+        Change user ``is_staff`` status.
+
+        :param is_staff: True or False
+        :returns: user instance or None if user not found/some kind of error.
+        """
+        try:
+            assert self.user and hasattr(self.user, 'is_staff')
+        except AssertionError:
+            pass
+        else:
+            self.user.is_staff = is_staff
+            self.user.save()
+        return self.user
+
+    def print_user_info(self):
+        """
+        Utility method to print out user info.
+        """
+        if self.user:
+            self._msg('username', self.username, first=True)
+            self._msg('user id', str(self.user.id))
+            self._msg('email', self.email)
+        else:
+            self._msg('user', 'None', first=True)
+
+
+def create_test_users(num, start_num=1, user_template=None):
+    """
+    Create x number of test users.
+
+    :param num: number of test users to create.
+    :param start_num: starting num suffix for user
+    :param user_template: tuple of (username_base, password_base, email_base)
+    :returns: list of UserInfo objects.
+    """
+    start_num = int(start_num)
+    username, password, email = user_template or TEST_USER_TEMPLATE
+    return [
+        UserInfo(username % str(n), password % str(n), email % str(n))
+        for n in range(start_num, start_num + num)
+    ]
+
+
+### helper functions to verify and print form errors
+
+def get_form_errors(form):
+    """
+    Return form.errors as a long string.
+
+    :param form: form instance
+    :returns: errors in a big string
+    """
+    return u'\n'.join([u'%s: %s' % (k, v) for k, v in form.errors.items()])
+
+
+def get_field_error(form, field):
+    """
+    Utility function to retrieve the error message from form.errors.
+
+    :param form: form instance
+    :param field: field name
+    :returns: error string or None
+    """
+    if field in form.errors:
+        return form.errors[field]
+    else:
+        return None

File sfgeek/apps/helpers/txt/__init__.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+"""
+helpers
+
+Utility functions for Django project and apps.
+
+"""

File sfgeek/apps/helpers/txt/utils.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+"""
+helpers.txt.utils
+
+Utility functions for helpers.txt module.
+
+* created: 2013-10-27 kevin chan <kefin@makedostudio.com>
+* updated: 2013-10-27 kchan
+"""
+
+import re
+
+from django.utils.html import strip_tags
+
+
+default_encoding = "utf-8"
+
+def uprint(data, encoding=default_encoding):
+    """
+    Print unicode output to stdout.
+
+    :param data: data to print.
+    :param encoding: data encoding (default is `utf-8`).
+    """
+    print data.encode(encoding)
+
+
+def tidy_msg(msg):
+    """
+    Utility function to tidy up text message by compressing multiple
+    blank lines.
+    * multiple (>2) blank lines are reduced to 2.
+
+    :param msg: text message
+    :returns: tidied up message with multiple blank lines removed.
+    """
+    if isinstance(msg, (basestring, unicode)):
+        lines = unicode(msg).split(u'\n')
+        s = []
+        run = 0
+        for line in lines:
+            txt = line.strip()
+            if len(txt) == 0:
+                if run < 1:
+                    s.append(u'')
+                run += 1
+            else:
+                run = 0
+                s.append(txt)
+        msg = u'\n'.join(s)
+    return msg
+
+
+def html_to_text(html):
+    """
+    Simple function to convert html content to text.
+    * uses Django strip_tags function to convert html to text;
+    * multiple blank lines are reduced to 2;
+    * strips beginning and ending white space.
+
+    :param html: html content
+    :returns: plain text content after conversion
+    """
+    txt = tidy_msg(strip_tags(html))
+    lines = []
+    for line in txt.splitlines():
+        s = line.strip()
+        if len(s) > 0:
+            lines.append(s)
+    txt = u'\n\n'.join(lines)
+    txt = u'%s\n' % txt
+    return txt

File sfgeek/apps/s3songs/tests/__init__.py

  • Ignore whitespace
Empty file added.

File sfgeek/apps/s3songs/tests/tests_page_loading.py

View file
  • Ignore whitespace
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+import re
+import os
+import pytz
+from datetime import datetime
+from bs4 import BeautifulSoup as bs
+
+from django.test import TestCase
+
+from django.test.client import RequestFactory
+from django.conf import settings
+
+from django.contrib.auth.models import User
+
+from django.core.urlresolvers import reverse
+
+from django_webtest import WebTest
+
+from garage.logger import logger
+
+class WebTest(WebTest):
+
+    def setUp(self):
+        #setup_hi_medium_low()
+        pass
+    def tearDown(self):
+        #tearDown_hi_medium_low()
+        pass
+
+
+    def test_renders(self):
+        """
+        S3Songs App - see if test harness pages are RESTFully served
+        """
+        url = reverse('search-s3-music')
+        resp = self.app.get(url).maybe_follow()
+        self.assertEqual(resp.status_int, 200)
+

File sfgeek/apps/s3songs/tests/tests_reverse_urls.py

View file
  • Ignore whitespace
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+import re
+import pytz
+import json
+from datetime import datetime
+from django.test import TestCase
+
+from django.contrib.auth.models import User
+
+from bs4 import BeautifulSoup as bs
+
+from django_webtest import WebTest
+from django.test.client import RequestFactory
+
+from django.core.urlresolvers import reverse
+
+from garage.logger import logger
+class DailySimpleTest(TestCase):
+
+    def setUp(self):
+        pass
+    def tearDown(self):
+        pass
+
+    def test_reverse_urls(self):
+        """
+        S3songs App - test the reverse urls for the exposed display pages
+        """
+        url = reverse('search-s3-music')
+        print url
+        pattern = '^/music/$'
+        matched = re.search(pattern, url)
+        self.assertTrue(matched)
+

File sfgeek/apps/s3songs/urls.py

View file
  • Ignore whitespace
+__author__ = 'marc'
+from django.conf.urls import patterns, url
+
+
+from s3songs import views
+
+urlpatterns = patterns('',
+    url(r'', views.index, name='search-s3-music'),
+)

File sfgeek/apps/s3songs/views.py

View file
  • Ignore whitespace
 # Create your views here.
+
+
+
+from django.shortcuts import  render_to_response
+
+
+from django.template import RequestContext
+
+
+
+from garage.logger import logger
+
+def index(request):
+    """
+    s3 search page
+    """
+
+    return render_to_response('s3songs/search.html',
+                              {
+
+                               },
+                context_instance=RequestContext(request)
+    )

File sfgeek/settings.py

View file
  • Ignore whitespace
 )
 
 MANAGERS = ADMINS
-AUTH_USER_MODEL='auth.user'
+AUTH_USER_MODEL = 'auth.user'
 
 DATABASES = {
     'default': {
 
 # Hosts/domain names that are valid for this site; required if DEBUG is False
 # See https://docs.djangoproject.com/en//ref/settings/#allowed-hosts
-ALLOWED_HOSTS = ['dj.sfgeek.net']
+ALLOWED_HOSTS = ['dj.sfgeek.net', 'djdev.sfgeek.net']
 
 # Local time zone for this installation. Choices can be found here:
 # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
     # Uncomment the next line to enable admin documentation:
     'django.contrib.admindocs',
     'django.contrib.flatpages',
+    'django_extensions',
     'categories',
     'categories.editor',
     'profiles',
     'kyndedgrams',
     'django_nose',
 	'testharness',
+	's3songs',
     #'staticpages'
 )
 

File sfgeek/urls.py

View file
  • Ignore whitespace
     # Uncomment the next line to enable the admin:
     url(r'^admin/', include(admin.site.urls)),
 )
-
+"""
+"""
+urlpatterns += patterns('',
+	(r'^music/$', include('s3songs.urls')),
+)
 urlpatterns += patterns('',
     url(r'^youtube/$', 'youtube.views.home', name='home'),
 	(r'^youtube/', include('django_youtube.urls')),
 
+
 	# Django youtube requires authentication
 	(r'^accounts/', include('registration.backends.default.urls')),