Skip to content

Commit

Permalink
Merge d08848b into 00c736f
Browse files Browse the repository at this point in the history
  • Loading branch information
relekang committed Apr 1, 2015
2 parents 00c736f + d08848b commit 783fdfd
Show file tree
Hide file tree
Showing 29 changed files with 210 additions and 170 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ addons:
postgresql: "9.3"
language: python
env:
- TOXENV=py27-tests
- TOXENV=py27-flake8
- TOXENV=py34-tests
- TOXENV=py34-flake8
install:
- pip install coveralls tox
before_script:
Expand Down
4 changes: 2 additions & 2 deletions accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ class Profile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=200, blank=True)

def __unicode__(self):
return self.name or unicode(self.user)
def __str__(self):
return self.name or str(self.user)
2 changes: 0 additions & 2 deletions aggregator/management/commands/update_subscriptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import logging

from datetime import timedelta
Expand Down
6 changes: 3 additions & 3 deletions aggregator/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class FeedType(models.Model):
slug = models.SlugField(max_length=250)
can_self_add = models.BooleanField(default=True)

def __unicode__(self):
def __str__(self):
return "%s" % (self.name,)

def items(self):
Expand All @@ -42,7 +42,7 @@ class Feed(models.Model):
feed_type = models.ForeignKey(FeedType)
owner = models.ForeignKey(User, blank=True, null=True, related_name='owned_feeds')

def __unicode__(self):
def __str__(self):
return self.title

def save(self, **kwargs):
Expand Down Expand Up @@ -115,7 +115,7 @@ class FeedItem(models.Model):
class Meta:
ordering = ("-date_modified",)

def __unicode__(self):
def __str__(self):
return self.title

def get_absolute_url(self):
Expand Down
4 changes: 1 addition & 3 deletions blog/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import datetime
from docutils.core import publish_parts

Expand Down Expand Up @@ -66,7 +64,7 @@ class Meta:
ordering = ('-pub_date',)
get_latest_by = 'pub_date'

def __unicode__(self):
def __str__(self):
return self.headline

def get_absolute_url(self):
Expand Down
2 changes: 1 addition & 1 deletion cla/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


class ICLAAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'user', 'date_signed']
list_display = ['__str__', 'user', 'date_signed']
raw_id_fields = ['user']
ordering = ['-date_signed']

Expand Down
12 changes: 5 additions & 7 deletions cla/models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"""
Track signed CLAs.
"""
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User

Expand Down Expand Up @@ -41,8 +39,8 @@ class Meta(object):
verbose_name = 'individual CLA'
verbose_name_plural = 'individual CLAs'

def __unicode__(self):
return unicode(self.full_name or self.user)
def __str__(self):
return self.full_name or str(self.user)


class CCLA(models.Model):
Expand Down Expand Up @@ -71,7 +69,7 @@ class Meta(object):
verbose_name = 'corporate CLA'
verbose_name_plural = 'corporate CLAs'

def __unicode__(self):
def __str__(self):
return self.company_name


Expand All @@ -95,8 +93,8 @@ class Meta(object):
verbose_name = 'CCLA designee'
verbose_name_plural = 'CCLA designees'

def __unicode__(self):
return unicode(self.full_name or self.user)
def __str__(self):
return self.full_name or str(self.user)


def find_agreements(user):
Expand Down
37 changes: 25 additions & 12 deletions contact/forms.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from __future__ import unicode_literals
import logging

import django
from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.encoding import force_bytes

from akismet import Akismet
from pykismet3 import Akismet, AkismetServerError
from contact_form.forms import ContactForm

logger = logging.getLogger(__name__)


class BaseContactForm(ContactForm):
message_subject = forms.CharField(
Expand All @@ -34,17 +37,27 @@ def clean_body(self):
Backported from django-contact-form pre-1.0; 1.0 dropped built-in
Akismet support.
"""
if 'body' in self.cleaned_data and hasattr(settings, 'AKISMET_API_KEY') and settings.AKISMET_API_KEY:
akismet_api = Akismet(key=settings.AKISMET_API_KEY,
blog_url='http://%s/' % Site.objects.get_current().domain)
if akismet_api.verify_key():
akismet_data = {'comment_type': 'comment',
'referer': self.request.META.get('HTTP_REFERER', ''),
'user_ip': self.request.META.get('REMOTE_ADDR', ''),
'user_agent': self.request.META.get('HTTP_USER_AGENT', '')}
comment = force_bytes(self.cleaned_data['body']) # workaround for #21444
if akismet_api.comment_check(comment, data=akismet_data, build_data=True):
if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY', None):
try:
akismet_api = Akismet(
api_key=settings.AKISMET_API_KEY,
blog_url='http://%s/' % Site.objects.get_current().domain,
user_agent='Django {}.{}.{}'.format(*django.VERSION)
)

akismet_data = {
'user_ip': self.request.META.get('REMOTE_ADDR', ''),
'user_agent': self.request.META.get('HTTP_USER_AGENT', ''),
'referrer': self.request.META.get('HTTP_REFERER', ''),
'comment_content': force_bytes(self.cleaned_data['body']),
'comment_author': self.cleaned_data['name']
}
if getattr(settings, 'AKISMET_TESTING', None):
akismet_data['test'] = 1
if akismet_api.check(akismet_data):
raise forms.ValidationError("Akismet thinks this message is spam")
except AkismetServerError:
logger.error('Akismet server error')
return self.cleaned_data['body']


Expand Down
52 changes: 46 additions & 6 deletions contact/tests.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,57 @@
from unittest import skipIf

import requests
from django.core import mail
from django.test import TestCase
from django.test.utils import override_settings


@override_settings(AKISMET_API_KEY='') # Disable Akismet in tests
def check_network_connection():
try:
requests.get('https://djangoproject.com')
except requests.exceptions.ConnectionError:
return False
return True


has_network_connection = check_network_connection()
print(has_network_connection)


@override_settings(AKISMET_TESTING=True)
class ContactFormTests(TestCase):
def test_foundation_contact(self):
data = {
def setUp(self):
self.url = '/contact/foundation/'

@override_settings(AKISMET_API_KEY='') # Disable Akismet in tests
def test_without_akismet(self):
response = self.client.post(self.url, {
'name': 'A. Random Hacker',
'email': 'a.random@example.com',
'message_subject': 'Hello',
'body': 'Hello, World!'
}
resp = self.client.post('/contact/foundation/', data)
self.assertRedirects(resp, '/contact/sent/')
})
self.assertRedirects(response, '/contact/sent/')
self.assertEqual(mail.outbox[-1].subject, '[Contact form] Hello')

@skipIf(not has_network_connection, 'Requires a network connection')
def test_akismet_detect_spam(self):
response = self.client.post(self.url, {
'name': 'viagra-test-123', # according to akismet this should flag as spam
'email': 'a.random@example.com',
'message_subject': 'Hello',
'body': 'Hello, World!'
})
self.assertContains(response, 'Akismet thinks this message is spam')
self.assertEqual(len(mail.outbox), 0)

@skipIf(not has_network_connection, 'Requires a network connection')
def test_akismet_not_spam(self):
response = self.client.post(self.url, {
'name': 'administrator',
'email': 'a.random@example.com',
'message_subject': 'Hello',
'body': 'Hello, World!'
})
self.assertRedirects(response, '/contact/sent/')
self.assertEqual(mail.outbox[-1].subject, '[Contact form] Hello')
13 changes: 5 additions & 8 deletions dashboard/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ast
import datetime
import xmlrpclib
import xmlrpc.client
import feedparser
import calendar
import requests
Expand All @@ -27,7 +27,7 @@ class Category(models.Model):
class Meta:
verbose_name_plural = 'categories'

def __unicode__(self):
def __str__(self):
return self.name


Expand All @@ -48,7 +48,7 @@ class Metric(models.Model):
class Meta:
abstract = True

def __unicode__(self):
def __str__(self):
return self.name

def get_absolute_url(self):
Expand Down Expand Up @@ -116,11 +116,8 @@ def _gather_data_periodic(self, since, period):
class TracTicketMetric(Metric):
query = models.TextField()

def __unicode__(self):
return self.name

def fetch(self):
s = xmlrpclib.ServerProxy(settings.TRAC_RPC_URL)
s = xmlrpc.client.ServerProxy(settings.TRAC_RPC_URL)
return len(s.ticket.query(self.query + "&max=0"))

def link(self):
Expand Down Expand Up @@ -241,5 +238,5 @@ class Meta:
get_latest_by = 'timestamp'
verbose_name_plural = 'data'

def __unicode__(self):
def __str__(self):
return "%s at %s: %s" % (self.metric, self.timestamp, self.measurement)
18 changes: 11 additions & 7 deletions dashboard/tests.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# -*- coding: utf-8 -*-
import codecs
import json
import os

from django.core import management
from django.http import Http404
from django.test import TestCase, RequestFactory
from django_hosts.resolvers import reverse
import mock
from unittest import mock
import requests_mock
from unipath import Path

from .models import TracTicketMetric, RSSFeedMetric, GithubItemCountMetric, Metric
from .views import index, metric_detail, metric_json
Expand All @@ -27,8 +28,8 @@ def test_index(self):
request = self.factory.get(reverse('dashboard-index', host='dashboard'))
response = index(request)
self.assertContains(response, 'Development dashboard')
self.assertEqual(response.content.count('<div class="metric'), 13)
self.assertEqual(response.content.count('42'), 13)
self.assertEqual(response.content.count(b'<div class="metric'), 13)
self.assertEqual(response.content.count(b'42'), 13)

def test_metric(self):
TracTicketMetric.objects.get(slug='new-tickets-week').data.create(measurement=42)
Expand All @@ -53,12 +54,15 @@ def test_metric_json(self):
request = self.factory.get(reverse('metric-json', args=['new-tickets-week'],
host='dashboard'))
response = metric_json(request, 'new-tickets-week')
self.assertEqual(json.loads(response.content)['data'][0][1], 42)
self.assertEqual(json.loads(response.content.decode())['data'][0][1], 42)
self.assertEqual(response.status_code, 200)


class MetricMixin(object):

def test_str(self):
self.assertEqual(str(self.instance), self.instance.name)

def test_get_absolute_url(self):
url_path = '/metric/%s/' % self.instance.slug
self.assertTrue(url_path in self.instance.get_absolute_url())
Expand All @@ -71,7 +75,7 @@ def setUp(self):
super(TracTicketMetricTestCase, self).setUp()
self.instance = TracTicketMetric.objects.last()

@mock.patch('xmlrpclib.ServerProxy')
@mock.patch('xmlrpc.client.ServerProxy')
def test_fetch(self, mock_server_proxy):
self.instance.fetch()
self.assertTrue(mock_server_proxy.client.query.assert_called_with)
Expand All @@ -80,7 +84,7 @@ def test_fetch(self, mock_server_proxy):
class RSSFeedMetricTestCase(TestCase, MetricMixin):
fixtures = ['dashboard_test_data']
feed_url = 'http://code.djangoproject.com/timeline?changeset=on&max=0&daysback=7&format=rss'
fixtures_path = Path(__file__).parent.child('fixtures', 'rss_feed_metric.xml')
fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'rss_feed_metric.xml')

def setUp(self):
super(RSSFeedMetricTestCase, self).setUp()
Expand Down
Loading

0 comments on commit 783fdfd

Please sign in to comment.