Commit 7d02a633 authored by Claude Paroz's avatar Claude Paroz

Fixed a bunch of PEP-8 issues

parent 85352897
......@@ -12,6 +12,7 @@ from teams.models import Team, Role
from .utils import lc_sorted, pyicu_present, trans_sort_object_list
class CommonTest(TestCase):
def setUp(self):
......@@ -45,7 +46,7 @@ class CommonTest(TestCase):
def test_activate_account(self):
# Testing if is_active is False by default
response = self.client.post(reverse('register'),
{'username':'newuser', 'email': 'newuser@example.org',
{'username': 'newuser', 'email': 'newuser@example.org',
'password1': 'blah012', 'password2': 'blah012'})
self.newu = Person.objects.get(username='newuser')
......@@ -86,17 +87,17 @@ class LcSortedTest(TestCase):
@skipUnless(pyicu_present, "PyICU package is required for this test")
def test_lc_sorted_en_case_insensitive(self):
with translation.override('en'):
self.assertEqual(['A','b', 'C', 'z'], lc_sorted(['z', 'C', 'b', "A"]))
self.assertEqual(['A', 'b', 'C', 'z'], lc_sorted(['z', 'C', 'b', 'A']))
@skipUnless(pyicu_present, "PyICU package is required for this test")
def test_lc_sorted_fr_eacute_between_d_and_f(self):
with translation.override('fr'):
self.assertEqual(['d', 'é', 'f', 'z'], lc_sorted(['é', 'z', 'd', "f"]))
self.assertEqual(['d', 'é', 'f', 'z'], lc_sorted(['é', 'z', 'd', 'f']))
@skipUnless(pyicu_present, "PyICU package is required for this test")
def test_lc_sorted_sv_ouml_after_z(self):
with translation.override('sv'):
self.assertEqual(['a', 'o', 'z', 'ö'], lc_sorted(['z', 'ö', 'o', "a"]))
self.assertEqual(['a', 'o', 'z', 'ö'], lc_sorted(['z', 'ö', 'o', 'a']))
def test_lc_sorted_with_custom_key(self):
mykey = operator.itemgetter(1)
......@@ -129,7 +130,7 @@ class TransSortObjectListTest(TestCase):
(here gettext reverses the string so foo (oof) comes before bar (rab)).
"""
foo, bar = self.mkItem('foo'), self.mkItem('bar')
actual = trans_sort_object_list([foo,bar], 'name')
actual = trans_sort_object_list([foo, bar], 'name')
self.assertEqual([foo, bar], actual, "wrong order")
@skipUnless(pyicu_present, "PyICU package is required for this test")
......
......@@ -87,7 +87,7 @@ def site_register(request):
if request.method == 'POST':
form = RegistrationForm(data = request.POST)
if form.is_valid():
new_user = form.save(request)
form.save(request)
return HttpResponseRedirect(reverse('register_success'))
else:
form = RegistrationForm()
......@@ -113,7 +113,7 @@ def activate_account(request, key):
def help(request, topic, modal):
template = 'help/%s.html' % topic
try:
t = get_template(template)
get_template(template)
except TemplateDoesNotExist:
raise Http404
return render(request, template, {
......
......@@ -25,7 +25,7 @@ class Language(models.Model):
iana_splitted = ianacode.split("-", 1)
lang_code = iana_splitted[0]
iana_suffix = len(iana_splitted) > 1 and iana_splitted[1] or ""
iana_suffix = iana_suffix.replace('Latn','latin').replace('Cyrl','cyrillic')
iana_suffix = iana_suffix.replace('Latn', 'latin').replace('Cyrl', 'cyrillic')
lang_list = cls.objects.filter(Q(locale=lang_code) | Q(locale__regex=r'^%s[@_].+' % lang_code))
if len(lang_list) == 0:
return None
......@@ -48,7 +48,7 @@ class Language(models.Model):
return self.locale
def get_suffix(self):
splitted = self.locale.replace('@','_').split('_')
splitted = self.locale.replace('@', '_').split('_')
if len(splitted) > 1:
return splitted[-1]
return None
......
......@@ -141,6 +141,7 @@ def language_release_xml(request, locale, release_name):
content += "</stats>"
return HttpResponse(content, content_type='text/xml')
def get_domain_stats(mods, node_name):
""" Iterate module domains to get stats """
content = ""
......@@ -156,12 +157,13 @@ def get_domain_stats(mods, node_name):
content += "</%s>" % node_name
return content
# ********* Utility functions ******************
def clean_tar_files():
""" Delete outdated tar.gz files generated by the language_release_tar view """
tar_directory = os.path.join(settings.POTDIR, 'tar')
if not os.path.exists(tar_directory):
return
for tarfile in os.listdir(tar_directory):
if not tarfile.endswith("%s.tar.gz" % date.today()):
for tar_file in os.listdir(tar_directory):
if not tar_file.endswith("%s.tar.gz" % date.today()):
os.remove(os.path.join(tar_directory, tarfile))
......@@ -30,7 +30,7 @@ class RegistrationForm(forms.Form):
def clean_username(self):
""" Validate the username (correctness and uniqueness)"""
try:
user = Person.objects.get(username__iexact=self.cleaned_data['username'])
Person.objects.get(username__iexact=self.cleaned_data['username'])
except Person.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_('This username is already taken. Please choose another.'))
......@@ -40,7 +40,7 @@ class RegistrationForm(forms.Form):
if self.cleaned_data['openid_url']:
from django_openid_auth.models import UserOpenID
try:
oid = UserOpenID.objects.get(claimed_id=self.cleaned_data['openid_url'])
UserOpenID.objects.get(claimed_id=self.cleaned_data['openid_url'])
except UserOpenID.DoesNotExist:
return self.cleaned_data['openid_url']
raise forms.ValidationError(_('This OpenID URL is already taken by a registered user'))
......@@ -71,7 +71,7 @@ class RegistrationForm(forms.Form):
openid = self.cleaned_data['openid_url']
if openid:
from django_openid_auth.models import UserOpenID
user_oid = UserOpenID.objects.create(user=new_user, claimed_id=openid)
UserOpenID.objects.create(user=new_user, claimed_id=openid)
salt = hashlib.sha1(force_bytes(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(force_bytes(salt + username)).hexdigest()
new_user.activation_key = activation_key
......
from django.db import migrations, models
import django.contrib.auth.models
class Migration(migrations.Migration):
......
......@@ -83,12 +83,12 @@ class PeopleTestCase(TestCase):
# Create Users
p1 = self._create_person(seq='1', last_login=datetime.datetime.now()-datetime.timedelta(days=700))
p2 = self._create_person(seq='2', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
role = Role.objects.create(team=team, person=p2, role='coordinator')
Role.objects.create(team=team, person=p2, role='coordinator')
p3 = self._create_person(seq='3', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
module.maintainers.add(p3)
p4 = self._create_person(seq='4', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
state = StateTranslating.objects.create(branch=branch, domain=domain, language=lang, person=p4)
p5 = self._create_person(seq='5', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
StateTranslating.objects.create(branch=branch, domain=domain, language=lang, person=p4)
self._create_person(seq='5', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
# Test only p5 should be deleted
self.assertEqual(Person.objects.all().count(), 5)
Person.clean_obsolete_accounts()
......
[flake8]
max-line-length = 119
......@@ -4,12 +4,13 @@ from django.contrib import admin
from django.contrib.admin import helpers
from django.shortcuts import render
from django.utils.encoding import force_text
from django import forms
from stats.models import (
Statistics, Information, PoFile, Module, Branch, Domain, Category,
CategoryName, Release,
)
class BranchInline(admin.TabularInline):
model = Branch
......
from django.db import models, migrations
from django.db import migrations
CATEGORY_CHOICES = (
('default', 'Default'),
......
......@@ -29,13 +29,13 @@ class FixtureFactory(TestCase):
webpage_url="http://www.it.gnome.org/")
# Creating models: Languages
l_en = Language.objects.create(name='en', locale='en', plurals="nplurals=2; plural=(n != 1)")
Language.objects.create(name='en', locale='en', plurals="nplurals=2; plural=(n != 1)")
l_fr = Language.objects.create(name='French', locale='fr', plurals="nplurals=2; plural=(n > 1)",
team=t1)
l_it = Language.objects.create(name='Italian', locale='it', plurals="nplurals=2; plural=(n != 1)",
team=t2)
# Lang with no team and no stats
l_bem = Language.objects.create(name='Bemba', locale='bem')
Language.objects.create(name='Bemba', locale='bem')
# Creating models: Persons/Roles
p0 = Person.objects.create(username='admin1') # Fake person (deleted below), just not to use pk=1 for user
......@@ -43,15 +43,15 @@ class FixtureFactory(TestCase):
email='bob@example.org', username='bob', irc_nick='bobby',
svn_account='bob1')
p1.set_password('bob')
r1 = Role.objects.create(team=t1, person=p1, role='translator')
Role.objects.create(team=t1, person=p1, role='translator')
p2 = Person.objects.create(first_name='John', last_name='Coordinator',
email='coord@example.org', username='coord', svn_account='coord_fr')
p2.set_password('coord')
r2 = Role.objects.create(team=t1, person=p2, role='coordinator')
Role.objects.create(team=t1, person=p2, role='coordinator')
p3 = Person.objects.create(first_name='Alessio', last_name='Reviewer',
email='alessio@example.org', username='alessio')
p1.set_password('alessio')
r3 = Role.objects.create(team=t2, person=p3, role='reviewer')
Role.objects.create(team=t2, person=p3, role='reviewer')
p0.delete()
# Creating models: Modules
......@@ -106,10 +106,10 @@ class FixtureFactory(TestCase):
string_frozen=False)
cat_name = CategoryName.objects.create(name='Desktop')
cat1 = Category.objects.create(release=rel1, branch=b1, name=cat_name)
cat2 = Category.objects.create(release=rel2, branch=b1, name=cat_name)
cat3 = Category.objects.create(release=rel1, branch=b2, name=cat_name)
cat4 = Category.objects.create(release=rel3, branch=b4, name=cat_name)
Category.objects.create(release=rel1, branch=b1, name=cat_name)
Category.objects.create(release=rel2, branch=b1, name=cat_name)
Category.objects.create(release=rel1, branch=b2, name=cat_name)
Category.objects.create(release=rel3, branch=b4, name=cat_name)
# Creating models: Statistics
# gnome-hello ui, gnome-hello doc (POT, fr, it)
......
......@@ -236,7 +236,7 @@ class ModuleTestCase(TestCase):
@test_scratchdir
def test_dynamic_po(self):
""" Test the creation of a blank po file for a new language """
lang = Language.objects.create(name="Tamil", locale="ta")
Language.objects.create(name="Tamil", locale="ta")
self.branch.update_stats(force=False) # At least POT stats needed
response = self.client.get('/module/po/gnome-hello/po/master/ta.po')
self.assertContains(response, """# Tamil translation for gnome-hello.
......
......@@ -4,7 +4,6 @@ import logging
import os
import re
import shutil
import sys
import time
from itertools import islice
from subprocess import Popen, PIPE
......@@ -20,7 +19,7 @@ from django.contrib.sites.models import Site
from django.core.files.base import File
from django.core.mail import send_mail
from django.template.loader import get_template
from django.utils.encoding import force_bytes, force_text
from django.utils.encoding import force_text
from django.utils.translation import ugettext_noop
from . import potdiff
......
......@@ -94,7 +94,6 @@ def module_edit_branches(request, module_name):
category_has_changed = (key + '_cat') in form.changed_data
if form.cleaned_data[key] and (release_has_changed or category_has_changed):
if field.initial:
old_release = Release.objects.get(pk=field.initial)
cat = Category.objects.get(pk=key)
if release_has_changed:
cat.release = form.cleaned_data[key]
......
......@@ -2,15 +2,17 @@ from django.contrib import admin
from teams.models import Team, Role
from languages.models import Language
class LanguageInline(admin.TabularInline):
model = Language
# Languages are not supposed to be created in this form
extra = 0
class TeamAdmin(admin.ModelAdmin):
search_fields = ('name', 'description')
list_display = ('description', 'use_workflow')
inlines = [ LanguageInline ]
inlines = [LanguageInline]
def formfield_for_dbfield(self, db_field, **kwargs):
# Reduced text area for aliases
......@@ -20,8 +22,10 @@ class TeamAdmin(admin.ModelAdmin):
return field
class RoleAdmin(admin.ModelAdmin):
search_fields = ('person__first_name', 'person__last_name', 'team__description', 'role')
admin.site.register(Team, TeamAdmin)
admin.site.register(Role, RoleAdmin)
......@@ -167,10 +167,10 @@ class TeamTest(TeamsAndRolesTests):
def test_edit_team_roles(self):
team_url = reverse('team_slug', args = ['fr'])
# Login as team coordinator
response = self.client.post('/login/',
self.client.post('/login/',
{'username': self.pcoo.username, 'password': 'password'})
# Team member role modification
response = self.client.post(team_url, {
self.client.post(team_url, {
'form_type': 'reviewer',
'%d' % Role.objects.get(team=self.t, person=self.pr).pk: 'committer',
})
......@@ -182,7 +182,7 @@ class TeamTest(TeamsAndRolesTests):
)
mail.outbox = []
# Team member removal
response = self.client.post(team_url, {
self.client.post(team_url, {
'form_type': 'translator',
'%d' % Role.objects.get(team=self.t, person=self.pt).pk: 'remove',
})
......
......@@ -383,7 +383,7 @@ class ActionAbstract(models.Model):
"""
history = []
if state or sequence:
file_history = [{'action_id':0, 'title': ugettext("File in repository")}]
file_history = [{'action_id': 0, 'title': ugettext("File in repository")}]
if not sequence:
query = cls.objects.filter(state_db__id=state.id)
else:
......@@ -396,7 +396,7 @@ class ActionAbstract(models.Model):
'action_id': action.id,
'title': ugettext("Uploaded file by %(name)s on %(date)s") % {
'name': action.person.name,
'date': action.created },
'date': action.created},
})
return history
......
......@@ -32,28 +32,35 @@ class VertimusTest(TeamsAndRolesTests):
def setUp(self):
super().setUp()
self.m = Module.objects.create(name='gedit', description='GNOME Editor',
self.m = Module.objects.create(
name='gedit', description='GNOME Editor',
bugs_base="https://bugzilla.gnome.org/",
bugs_product='gedit', bugs_component='general',
vcs_type='git', vcs_root="git://git.gnome.org/gedit",
vcs_web="http://git.gnome.org/browse/gedit/")
vcs_web="http://git.gnome.org/browse/gedit/"
)
Branch.checkout_on_creation = False
self.b = Branch(name='gnome-2-24', module=self.m)
# Block the update of Statistics by the thread
self.b.save(update_statistics=False)
self.r = Release.objects.create(name='gnome-2-24', status='official',
self.r = Release.objects.create(
name='gnome-2-24', status='official',
description='GNOME 2.24 (stable)',
string_frozen=True)
string_frozen=True
)
self.c = Category.objects.create(
release=self.r, branch=self.b, name=CategoryName.objects.create(name='Desktop'))
release=self.r, branch=self.b, name=CategoryName.objects.create(name='Desktop')
)
self.d = Domain.objects.create(module=self.m, name='po',
self.d = Domain.objects.create(
module=self.m, name='po',
description='UI translations',
dtype='ui', directory='po')
pot_stat = Statistics.objects.create(language=None, branch=self.b, domain=self.d)
dtype='ui', directory='po'
)
Statistics.objects.create(language=None, branch=self.b, domain=self.d)
self.files_to_clean = []
def tearDown(self):
......@@ -414,7 +421,7 @@ class VertimusTest(TeamsAndRolesTests):
# Upload a new file
action_file = self.upload_file(state, 'UP')
self.assertEqual(len(mail.outbox), 1) # Mail sent to mailing list
self.assertEqual(len(mail.outbox), 1) # Mail sent to mailing list
mail.outbox = []
file_path = os.path.join(settings.MEDIA_ROOT, action_file.name)
......@@ -422,7 +429,7 @@ class VertimusTest(TeamsAndRolesTests):
action = Action.new_by_name('TC', person=self.pc)
action.apply_on(state, {'send_to_ml': action.send_mail_to_ml, 'comment': ''})
self.assertEqual(len(mail.outbox), 1) # Mail sent to committers
self.assertEqual(len(mail.outbox), 1) # Mail sent to committers
mail.outbox = []
action = Action.new_by_name('RC', person=self.pc)
......@@ -490,7 +497,10 @@ class VertimusTest(TeamsAndRolesTests):
action.apply_on(state, {'send_to_ml': action.send_mail_to_ml, 'comment': "Reserved!"})
action = Action.new_by_name('UNDO', person=self.pt)
action.apply_on(state, {'send_to_ml': action.send_mail_to_ml, 'comment': "Ooops! I don't want to do that. Sorry."})
action.apply_on(state, {
'send_to_ml': action.send_mail_to_ml,
'comment': "Ooops! I don't want to do that. Sorry."
})
self.assertEqual(action.comment, "Ooops! I don't want to do that. Sorry.")
self.assertEqual(state.name, 'Translated')
......@@ -536,14 +546,14 @@ class VertimusTest(TeamsAndRolesTests):
self.assertEqual(Action.objects.all().count(), 0)
def test_delete_domain(self):
state = StateTranslating.objects.create(branch=self.b, domain=self.d, language=self.l, person=self.pt)
StateTranslating.objects.create(branch=self.b, domain=self.d, language=self.l, person=self.pt)
self.d.delete()
self.assertEqual(State.objects.all().count(), 0)
def test_delete_statistics(self):
""" Test clean_dangling_states receiver """
po_stat = Statistics.objects.create(branch=self.b, domain=self.d, language=self.l)
state = StateTranslating.objects.create(branch=self.b, domain=self.d, language=self.l, person=self.pt)
StateTranslating.objects.create(branch=self.b, domain=self.d, language=self.l, person=self.pt)
po_stat.delete()
self.assertEqual(State.objects.all().count(), 0)
......@@ -551,8 +561,10 @@ class VertimusTest(TeamsAndRolesTests):
url = reverse('vertimus_by_ids', args=[self.b.id, self.d.id, self.l.id])
response = self.client.get(url)
self.assertNotContains(response, '<option value="WC">')
self.assertContains(response,
'<span class="num1"> 0</span><span class="num2"> 0</span><span class="num3"> 0</span>')
self.assertContains(
response,
'<span class="num1"> 0</span><span class="num2"> 0</span><span class="num3"> 0</span>'
)
self.client.login(username=self.pn.username, password='password')
response = self.client.get(url)
......@@ -569,9 +581,11 @@ class VertimusTest(TeamsAndRolesTests):
# Block the update of Statistics by the thread
master.save(update_statistics=False)
Statistics.objects.create(branch=master, domain=self.d, language=None)
dom_alt = Domain.objects.create(module=self.m, name='po',
dom_alt = Domain.objects.create(
module=self.m, name='po',
description='UI translations',
dtype='ui', directory='po')
dtype='ui', directory='po'
)
StateNone.objects.create(branch=master, domain=self.d, language=self.l)
StateNone.objects.create(branch=self.b, domain=dom_alt, language=self.l)
......@@ -611,18 +625,26 @@ class VertimusTest(TeamsAndRolesTests):
response = self.client.get(reverse('lang_feed', args=[self.l.locale]))
doc = parseString(response.content)
self.assertEqual(doc.childNodes[0].tagName, 'rss')
self.assertEqual(doc.childNodes[0].getAttribute('xmlns:atom'), "http://www.w3.org/2005/Atom")
self.assertEqual(doc.getElementsByTagName('title')[1].toxml(),
"""<title>po (gedit/User Interface) - gedit (gnome-2-24) - Reserve for translation\n</title>""")
self.assertEqual(doc.getElementsByTagName('guid')[0].toxml(),
"""<guid>http://example.com/vertimus/gedit/gnome-2-24/po/fr#%d</guid>""" % action.id)
self.assertEqual(
doc.childNodes[0].getAttribute('xmlns:atom'), "http://www.w3.org/2005/Atom"
)
self.assertEqual(
doc.getElementsByTagName('title')[1].toxml(),
"""<title>po (gedit/User Interface) - gedit (gnome-2-24) - Reserve for translation\n</title>"""
)
self.assertEqual(
doc.getElementsByTagName('guid')[0].toxml(),
"""<guid>http://example.com/vertimus/gedit/gnome-2-24/po/fr#%d</guid>""" % action.id
)
response = self.client.get(reverse('team_feed', args=[self.l.team.name]))
self.assertContains(response,
"""<title>po (gedit/User Interface) - gedit (gnome-2-24) - Reserve for translation\n</title>""")
self.assertContains(
response,
"""<title>po (gedit/User Interface) - gedit (gnome-2-24) - Reserve for translation\n</title>"""
)
def test_activity_summary(self):
state = StateTranslating.objects.create(
StateTranslating.objects.create(
branch=self.b, domain=self.d,
language=self.l,
person=self.pt)
......
......@@ -2,6 +2,7 @@ from django.conf.urls import url
from vertimus import views
module_branch_domain = r'(?P<module_name>[\w\+\-\.]+)/(?P<branch_name>[\w\-\.]+)/(?P<domain_name>[\w~\-]+)'
urlpatterns = [
url(r'^(?P<stats_id>\d+)/(?P<lang_id>\d+)$',
......@@ -13,13 +14,13 @@ urlpatterns = [
url(r'^diff/(?P<action_id_1>\d+)/(?P<action_id_2>\d+)/(?P<level>\d+)/$',
views.vertimus_diff,
name='vertimus_diff'),
url(r'^uploads/(?P<module_name>[\w\+\-\.]+)/(?P<branch_name>[\w\-\.]+)/(?P<domain_name>[\w~\-]+)/(?P<locale_name>[\w\-@]+)/latest/$',
url(r'^uploads/%s/(?P<locale_name>[\w\-@]+)/latest/$' % module_branch_domain,
views.latest_uploaded_po,
name='latest_uploaded_po'),
url('^(?P<module_name>[\w\+\-\.]+)/(?P<branch_name>[\w\-\.]+)/(?P<domain_name>[\w~\-]+)/(?P<locale_name>[\w\-@]+)/level(?P<level>\d+)/$',
url(r'^%s/(?P<locale_name>[\w\-@]+)/level(?P<level>\d+)/$' % module_branch_domain,
views.vertimus_by_names,
name='vertimus_archives_by_names'),
url(r'^(?P<module_name>[\w\+\-\.]+)/(?P<branch_name>[\w\-\.]+)/(?P<domain_name>[\w~\-]+)/(?P<locale_name>[\w\-@]+)',
url(r'^%s/(?P<locale_name>[\w\-@]+)' % module_branch_domain,
views.vertimus_by_names,
name='vertimus_by_names'),
url(r'^(?P<locale>[\w\-@]+)/activity_summary/$',
......
......@@ -132,7 +132,7 @@ def vertimus(request, branch, domain, language, stats=None, level="0"):
'domain': domain,
'language': language,
'module': branch.module,
'non_standard_repo_msg' : _(settings.VCS_HOME_WARNING),
'non_standard_repo_msg': _(settings.VCS_HOME_WARNING),
'state': state,
'action_history': action_history,
'action_form': action_form,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment