Move tests.py to tests/test_base.py so pytest will find and run them

Seems we've been ignoring these tests for quite a while.
Also move tests in l10n_utils/tests/__init__.py so pytest can find them.
This commit is contained in:
Paul McLanahan 2018-04-13 11:22:48 -04:00 коммит произвёл Paul McLanahan
Родитель 673438808c
Коммит 1370d2e106
12 изменённых файлов: 139 добавлений и 223 удалений

Просмотреть файл

@ -1,120 +0,0 @@
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from datetime import datetime
from django.conf import settings
from django.utils import timezone
from mock import Mock, patch, PropertyMock
from pytz import utc
from bedrock import externalfiles
from bedrock.externalfiles.models import ExternalFile as EFModel
from bedrock.mozorg.tests import TestCase
import requests
class TestExternalFile(TestCase):
@classmethod
def setUpClass(cls):
super(TestExternalFile, cls).setUpClass()
timezone.activate(utc)
def setUp(self):
settings.EXTERNAL_FILES['test'] = {
'url': 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul',
}
def tearDown(self):
externalfiles.ExternalFile('test').clear_cache()
del settings.EXTERNAL_FILES['test']
def test_file_name(self):
"""Should be based on URL if not provided."""
self.assertEqual(externalfiles.ExternalFile('test').name, 'there.is.only.xul')
def test_file_name_provided(self):
"""Should be based on URL if not provided."""
filename = 'there.is.no.data.xul'
settings.EXTERNAL_FILES['test']['name'] = filename
self.assertEqual(externalfiles.ExternalFile('test').name, filename)
def test_last_modified(self):
"""Should return the modified timestamp."""
EFModel.objects.create(name='test', content='test')
efo = EFModel.objects.get(name='test')
self.assertEqual(externalfiles.ExternalFile('test').last_modified, efo.last_modified)
def test_last_modified_read_error(self):
"""Should return None if object not in DB."""
self.assertIsNone(externalfiles.ExternalFile('test').last_modified)
@patch.object(externalfiles.ExternalFile, 'last_modified', new_callable=PropertyMock)
def test_last_modified_http(self, elm_mock):
"""should properly convert stored datetime to HTTP value."""
good_value = 'Tue, 08 Jul 2014 12:00:00 GMT'
good_datetime = datetime(year=2014, month=7, day=8, hour=4)
good_datetime = timezone.make_aware(good_datetime, utc)
elm_mock.return_value = good_datetime
efo = externalfiles.ExternalFile('test')
self.assertEqual(efo.last_modified_http, good_value)
@patch.object(externalfiles.ExternalFile, 'last_modified_http', new_callable=PropertyMock)
@patch.object(externalfiles, 'requests')
def test_update_adds_headers(self, requests_mock, elmh_mock):
"""Should add proper modified headers when possible."""
requests_mock.get.side_effect = requests.RequestException
ef = externalfiles.ExternalFile('test')
modified_str = 'Willlllmaaaaaaa!!'
elmh_mock.return_value = modified_str
try:
ef.update()
except requests.RequestException:
pass
requests_mock.get.called_once_with(settings.EXTERNAL_FILES['test']['url'],
headers={'if-modified-since': modified_str},
verify=True)
@patch.object(externalfiles.ExternalFile, 'last_modified_http', new_callable=PropertyMock)
@patch.object(externalfiles, 'requests')
def test_update_force_not_add_headers(self, requests_mock, elmh_mock):
"""Should not add proper modified headers when force is True."""
requests_mock.get.side_effect = requests.RequestException
ef = externalfiles.ExternalFile('test')
elmh_mock.return_value = 'YabbaDabbaDooo!!'
try:
ef.update(force=True)
except requests.RequestException:
pass
requests_mock.get.called_once_with(settings.EXTERNAL_FILES['test']['url'], headers={},
verify=True)
def test_validate_resp_200(self):
"""Should return the content for a successful request."""
response = Mock(status_code=200, text='Huge Success')
ef = externalfiles.ExternalFile('test')
self.assertEqual(ef.validate_resp(response), 'Huge Success')
def test_validate_resp_304(self):
"""Should return None if the URL is up-to-date."""
response = Mock(status_code=304)
ef = externalfiles.ExternalFile('test')
self.assertIsNone(ef.validate_resp(response))
def test_validate_resp_404(self):
"""Should raise an exception for a missing file."""
response = Mock(status_code=404)
ef = externalfiles.ExternalFile('test')
with self.assertRaisesMessage(ValueError, 'File not found (404): ' + ef.name):
ef.validate_resp(response)
def test_validate_resp_500(self):
"""Should raise an exception for all other codes."""
response = Mock(status_code=500)
ef = externalfiles.ExternalFile('test')
with self.assertRaises(ValueError) as e:
ef.validate_resp(response)
self.assertTrue(str(e.exception).startswith('Unknown error'))

Просмотреть файл

Просмотреть файл

@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.utils import timezone
from pytz import utc
from bedrock import externalfiles
from bedrock.externalfiles.models import ExternalFile as EFModel
from bedrock.mozorg.tests import TestCase
class TestExternalFile(TestCase):
@classmethod
def setUpClass(cls):
super(TestExternalFile, cls).setUpClass()
timezone.activate(utc)
def setUp(self):
settings.EXTERNAL_FILES['test'] = {
'url': 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul',
'name': 'there.is.no.data.xul'
}
def tearDown(self):
externalfiles.ExternalFile('test').clear_cache()
del settings.EXTERNAL_FILES['test']
def test_last_modified(self):
"""Should return the modified timestamp."""
EFModel.objects.create(name='test', content='test')
efo = EFModel.objects.get(name='test')
self.assertEqual(externalfiles.ExternalFile('test').last_modified, efo.last_modified)

Просмотреть файл

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -12,7 +12,7 @@ from nose.tools import eq_
from bedrock.mozorg.tests import TestCase
from . import views
from bedrock.legal_docs import views
class TestLoadLegalDoc(TestCase):

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -1,35 +1,9 @@
import os
import sys
from contextlib import contextmanager
from cStringIO import StringIO
from tempfile import TemporaryFile
from textwrap import dedent
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django_jinja.backend import Jinja2
from mock import patch
from lib import l10n_utils
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files')
TEMPLATE_DIRS = (os.path.join(ROOT, 'templates'),)
jinja_env = Jinja2.get_default()
@contextmanager
def capture_stdio():
oldout, olderr = sys.stdout, sys.stderr
newio = [StringIO(), StringIO()]
sys.stdout, sys.stderr = newio
yield newio
sys.stdout, sys.stderr = oldout, olderr
newio[0] = newio[0].getvalue().rstrip()
newio[1] = newio[1].getvalue().rstrip()
class TempFileMixin(object):
"""Provide a method for getting a temp file that is removed when closed."""
@ -41,78 +15,12 @@ class TempFileMixin(object):
return tempf
@patch.object(jinja_env.env.loader, 'searchpath', TEMPLATE_DIRS)
@override_settings(ROOT=ROOT)
@override_settings(DEV=False)
class TestRender(TestCase):
urls = 'lib.l10n_utils.tests.test_files.urls'
def _test(self, path, template, locale, accept_lang, status, destination=None):
request = RequestFactory().get(path)
request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang
request.locale = locale
response = l10n_utils.render(request, template)
if status == 302:
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], destination)
self.assertEqual(response['Vary'], 'Accept-Language')
else:
self.assertEqual(response.status_code, 200)
def test_firefox(self):
path = '/firefox/new/'
template = 'firefox/new.html'
# Nothing to do with a valid locale
self._test(path, template, 'en-US', 'en-us,en;q=0.5',
200)
# en-GB is activated on /firefox/new/
with patch.object(l10n_utils, 'template_is_active') as active_mock:
active_mock.return_value = True
self._test(path, template, 'en-GB', 'en-gb,en;q=0.5',
200)
active_mock.reset_mock()
active_mock.side_effect = [False, True]
# fr-FR should be treated as fr
self._test(path, template, 'fr-FR', 'fr-fr',
302, '/fr/firefox/new/')
active_mock.reset_mock()
active_mock.side_effect = [False, False, True]
# Should fallback to the user's second preferred language
self._test(path, template, 'zu', 'zu,fr;q=0.7,en;q=0.3',
302, '/fr/firefox/new/')
active_mock.reset_mock()
active_mock.side_effect = [False, False, False, False, True]
# Should fallback to one of the site's fallback languages
self._test(path, template, 'es-CL', 'es-CL,es;q=0.7,en;q=0.3',
302, '/es-ES/firefox/new/')
class TestGetAcceptLanguages(TestCase):
def _test(self, accept_lang, list):
request = RequestFactory().get('/')
request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang
self.assertEqual(l10n_utils.get_accept_languages(request), list)
def test_valid_lang_codes(self):
"""
Should return a list of valid lang codes
"""
self._test('fr-FR', ['fr'])
self._test('en-us,en;q=0.5', ['en-US', 'en'])
self._test('pt-pt,fr;q=0.8,it-it;q=0.5,de;q=0.3',
['pt-PT', 'fr', 'it', 'de'])
self._test('ja-JP-mac,ja-JP;q=0.7,ja;q=0.3', ['ja'])
self._test('foo,bar;q=0.5', ['foo', 'bar'])
def test_invalid_lang_codes(self):
"""
Should return a list of valid lang codes or an empty list
"""
self._test('', [])
self._test('en_us,en*;q=0.5', [])
self._test('Chinese,zh-cn;q=0.5', ['zh-CN'])
@contextmanager
def capture_stdio():
oldout, olderr = sys.stdout, sys.stderr
newio = [StringIO(), StringIO()]
sys.stdout, sys.stderr = newio
yield newio
sys.stdout, sys.stderr = oldout, olderr
newio[0] = newio[0].getvalue().rstrip()
newio[1] = newio[1].getvalue().rstrip()

Просмотреть файл

@ -0,0 +1,92 @@
import os
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django_jinja.backend import Jinja2
from mock import patch
from lib import l10n_utils
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files')
TEMPLATE_DIRS = (os.path.join(ROOT, 'templates'),)
jinja_env = Jinja2.get_default()
@patch.object(jinja_env.env.loader, 'searchpath', TEMPLATE_DIRS)
@override_settings(ROOT=ROOT)
@override_settings(DEV=False)
class TestRender(TestCase):
urls = 'lib.l10n_utils.tests.test_files.urls'
def _test(self, path, template, locale, accept_lang, status, destination=None):
request = RequestFactory().get(path)
request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang
request.locale = locale
response = l10n_utils.render(request, template)
if status == 302:
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], destination)
self.assertEqual(response['Vary'], 'Accept-Language')
else:
self.assertEqual(response.status_code, 200)
def test_firefox(self):
path = '/firefox/new/'
template = 'firefox/new.html'
# Nothing to do with a valid locale
self._test(path, template, 'en-US', 'en-us,en;q=0.5',
200)
# en-GB is activated on /firefox/new/
with patch.object(l10n_utils, 'template_is_active') as active_mock:
active_mock.return_value = True
self._test(path, template, 'en-GB', 'en-gb,en;q=0.5',
200)
active_mock.reset_mock()
active_mock.side_effect = [False, True]
# fr-FR should be treated as fr
self._test(path, template, 'fr-FR', 'fr-fr',
302, '/fr/firefox/new/')
active_mock.reset_mock()
active_mock.side_effect = [False, False, True]
# Should fallback to the user's second preferred language
self._test(path, template, 'zu', 'zu,fr;q=0.7,en;q=0.3',
302, '/fr/firefox/new/')
active_mock.reset_mock()
active_mock.side_effect = [False, False, False, False, True]
# Should fallback to one of the site's fallback languages
self._test(path, template, 'es-CL', 'es-CL,es;q=0.7,en;q=0.3',
302, '/es-ES/firefox/new/')
class TestGetAcceptLanguages(TestCase):
def _test(self, accept_lang, list):
request = RequestFactory().get('/')
request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang
self.assertEqual(l10n_utils.get_accept_languages(request), list)
def test_valid_lang_codes(self):
"""
Should return a list of valid lang codes
"""
self._test('fr-FR', ['fr'])
self._test('en-us,en;q=0.5', ['en-US', 'en'])
self._test('pt-pt,fr;q=0.8,it-it;q=0.5,de;q=0.3',
['pt-PT', 'fr', 'it', 'de'])
self._test('ja-JP-mac,ja-JP;q=0.7,ja;q=0.3', ['ja'])
self._test('foo,bar;q=0.5', ['foo', 'bar'])
def test_invalid_lang_codes(self):
"""
Should return a list of valid lang codes or an empty list
"""
self._test('', [])
self._test('en_us,en*;q=0.5', [])
self._test('Chinese,zh-cn;q=0.5', ['zh-CN'])

Просмотреть файл

@ -8,6 +8,7 @@ import os
from django.conf import settings
from django.core.cache import caches
from django.test import TestCase
from django.test.utils import override_settings
from mock import ANY, MagicMock, Mock, patch
@ -18,7 +19,6 @@ from lib.l10n_utils.gettext import (_append_to_lang_file, langfiles_for_path,
po_msgs, pot_to_langfiles, template_is_active,
_get_template_tag_set, template_has_tag)
from lib.l10n_utils.tests import TempFileMixin
from bedrock.mozorg.tests import TestCase
cache = caches['l10n']
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files')