Skip to content

Commit

Permalink
re-arranged utils
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobias Lorenz committed Apr 14, 2016
1 parent 046c6d9 commit 9241a0a
Show file tree
Hide file tree
Showing 24 changed files with 562 additions and 474 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
=== 1.67.X ===

- Re-arranged utils
- added fallback for BeautifulSoup import in utils
- prepared app for Django 1.9 and Python 3.5
- dropped support for Django<1.6
Expand Down
2 changes: 1 addition & 1 deletion django_libs/settings/django_settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Useful defualt settings that you might want to use in all your projects."""
"""Useful default settings that you might want to use in all your projects."""
import re


Expand Down
2 changes: 2 additions & 0 deletions django_libs/tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import os
import logging

from ..settings.django_settings import * # NOQA


logging.getLogger("factory").setLevel(logging.WARN)

Expand Down
Empty file.
66 changes: 66 additions & 0 deletions django_libs/tests/utils/converter_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Tests for the converter utils of ``django_libs``."""
import os

from django.test import TestCase

from ...utils.converter import html_to_plain_text


class HTMLToPlainTextTestCase(TestCase):
"""Tests for the ``html_to_plain_text`` function."""
longMessage = True

def test_html_to_plain_text(self):
html = (
"""
<html>
<head></head>
<body>
<ul>
<li>List element</li>
<li>List element</li>
<li>List element</li>
</ul>
</body>
</html>
"""
)
self.assertEqual(
html_to_plain_text(html),
'\n * List element\n * List element\n * List element',
msg='Should return a formatted plain text.')
path = os.path.dirname(os.path.abspath(__file__)) + (
'/../test_app/templates/html_email.html')
with open(path, 'rb') as file:
self.assertIn('[1]: *|ARCHIVE|*\n', html_to_plain_text(file), msg=(
'Should return a formatted plain text.'))

def test_replace_links(self):
html = (
"""
<span>T1<span> <a href="www.example.com">link</a> <span>T2</span>
<br />
<span>T3</span>
"""
)
expected = (
"T1 link[1] T2\nT3\n\n[1]: www.example.com\n"
)
result = html_to_plain_text(html)
self.assertEqual(result, expected, msg=(
'Should replace links nicely'))

def test_replace_br(self):
html = (
"""
<span>Text1<br>Text2</span>
<br /><br />
<span>Text3</span>
"""
)
expected = (
"Text1\nText2\n\n\nText3"
)
result = html_to_plain_text(html)
self.assertEqual(result, expected, msg=(
'Should replace links nicely'))
38 changes: 38 additions & 0 deletions django_libs/tests/utils/decorators_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Tests for the decorator utils of ``django_libs``."""
from django.test import TestCase

from ...utils.decorators import conditional_decorator


def dummy_decorator(func):
def wrapper():
return 0
return wrapper


@conditional_decorator(dummy_decorator, False)
def test_method():
"""Used to test the ``conditional_decorator``."""
return 1


@conditional_decorator(dummy_decorator, True)
def test_method_true():
"""Used to test the ``conditional_decorator``."""
return 1


class ConditionalDecoratorTestCase(TestCase):
"""Tests for the ``conditional_decorator``."""
longMessage = True

def test_decorator_with_condition_false(self):
result = test_method()
self.assertEqual(result, 1, msg=(
'The method should have been executed normally, without calling'
' the decorator'))

def test_decorator_with_condition_true(self):
result = test_method_true()
self.assertEqual(result, 0, msg=(
'The method should have been executed with the decorator'))
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
from django.test import TestCase

from mailer.models import Message
from mixer.backend.django import mixer
from mock import Mock

from .factories import SiteFactory
from ..utils_email import send_email
from ...utils.email import send_email


class SendEmailTestCase(TestCase):
"""Tests for the ``send_email`` function."""
longMessage = True

def test_send_email(self):
SiteFactory()
mixer.blend('sites.Site')
request = Mock()
request.is_secure = Mock(return_value=True)
request.get_host = Mock(return_value='example.com')
Expand Down
43 changes: 43 additions & 0 deletions django_libs/tests/utils/log_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Tests for the log utils of ``django_libs``."""
from django.test import TestCase

from mock import Mock

from ...utils.log import AddCurrentUser, FilterIgnorable404URLs


class AddCurrentUserTestCase(TestCase):
"""Tests for the ``AddCurrentUser`` filter."""
longMessage = True

def test_filter(self):
user = Mock()
user.email = 'foo@example.com'
record = Mock()
record.request.user = user
record.request.META = {}
self.assertTrue(AddCurrentUser().filter(record))


class FilterIgnorable404URLsTestCase(TestCase):
"""Tests for the ``FilterIgnorable404URLs`` filter."""
longMessage = True

def test_filter(self):
record = Mock()
record.status_code = 200
record.request.META = {
'HTTP_USER_AGENT': 'Mozilla/5.0 (compatible; bingbot/2.0;'
' +http://www.bing.com/bingbot.htm)',
}
self.assertTrue(FilterIgnorable404URLs().filter(record))
record.status_code = 404
self.assertFalse(FilterIgnorable404URLs().filter(record))
record.request.META.update({
'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows Phone 8.1; ARM;'
' Trident/7.0; Touch; rv:11.0; IEMobile/11.0;'
' NOKIA; Lumia 530) like Gecko'})
record.request.get_full_path = Mock(return_value='/foo/')
self.assertTrue(FilterIgnorable404URLs().filter(record))
record.request.get_full_path = Mock(return_value='/static/logo.png')
self.assertFalse(FilterIgnorable404URLs().filter(record))
16 changes: 16 additions & 0 deletions django_libs/tests/utils/text_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Tests for the text utils of ``django_libs``."""
from django.test import TestCase

from ...utils.text import create_random_string


class CreateRandomStringTestCase(TestCase):
"""Tests for the ``create_random_string`` function."""
longMessage = True

def test_func(self):
self.assertEqual(len(create_random_string()), 7, msg=(
'Should return a random string with 7 characters.'))
self.assertEqual(
len(create_random_string(length=3, chars='ABC', repetitions=True)),
3, msg=('Should return a random string with 3 characters.'))
119 changes: 0 additions & 119 deletions django_libs/tests/utils_tests.py

This file was deleted.

Empty file added django_libs/utils/__init__.py
Empty file.
41 changes: 2 additions & 39 deletions django_libs/utils.py → django_libs/utils/converter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Additional helpful utility functions."""
import random
import sys

from django.conf import settings
Expand All @@ -11,50 +10,14 @@

try:
from bs4 import BeautifulSoup
except ImportError:
sys.stderr.write('Warning: BeatifulSoup could not be imported! Created'
except ImportError: # pragma: nocover
sys.stderr.write('Warning: BeautifulSoup could not be imported! Created'
' fallback for tests to work.')

def BeautifulSoup(x, y):
return x


class conditional_decorator(object):
"""
Allows you to use decorators based on a condition.
Useful to require login only if a setting is set::
@conditional_decorator(method_decorator(login_required), settings.FOO)
def dispatch(self, request, *args, **kwargs):
return super(...).dispatch(...)
"""
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition

def __call__(self, func):
if not self.condition:
# Return the function unchanged, not decorated.
return func
return self.decorator(func)


def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789',
repetitions=False):
"""
Returns a random string, based on the provided arguments.
It returns capital letters and numbers by default.
Ambiguous characters are left out, repetitions will be avoided.
"""
if repetitions:
return ''.join(random.choice(chars) for _ in range(length))
return ''.join(random.sample(chars, length))


class HTML2PlainParser(HTMLParser):
"""Custom html parser to convert html code to plain text."""
def __init__(self):
Expand Down

0 comments on commit 9241a0a

Please sign in to comment.