import os
import sys
-if __name__ == "__main__":
+if __name__ == '__main__':
os.environ.setdefault(
- "DJANGO_SETTINGS_MODULE", "patchwork.settings.production"
+ 'DJANGO_SETTINGS_MODULE', 'patchwork.settings.production'
)
import django
def run_validation(self, data):
if 'state' not in data or data['state'] == '':
- raise ValidationError({'state': ["A check must have a state."]})
+ raise ValidationError({'state': ['A check must have a state.']})
for val, label in Check.STATE_CHOICES:
if label != data['state']:
min_length=1,
max_length=50,
label='Name',
- error_messages={'invalid': 'Bundle names can\'t contain slashes'},
+ error_messages={'invalid': "Bundle names can't contain slashes"},
)
class Meta:
opts = instance.__class__._meta
if self.errors:
raise ValueError(
- "The %s could not be changed because the data "
+ 'The %s could not be changed because the data '
"didn't validate." % opts.object_name
)
data = self.cleaned_data
errors = send_notifications()
for recipient, error in errors:
self.stderr.write(
- "Failed sending to %s: %s" % (recipient.email, error)
+ 'Failed sending to %s: %s' % (recipient.email, error)
)
expire_notifications()
logger.info('Parsing mail loaded from stdin')
mail = email.message_from_binary_file(sys.stdin.buffer)
except AttributeError:
- logger.warning("Broken email ignored")
+ logger.warning('Broken email ignored')
return
# it's important to get exit codes correct here. The key is to allow
models.CharField(
blank=True,
help_text=b"URL format for the list archive's "
- b"Message-ID redirector. {} will be "
- b"replaced by the Message-ID.",
+ b'Message-ID redirector. {} will be '
+ b'replaced by the Message-ID.',
max_length=2000,
),
),
models.BooleanField(
default=True,
help_text=b"Show a column displaying this tag's count "
- b"in the patch list view",
+ b'in the patch list view',
),
),
],
def copy_comment_field(apps, schema_editor):
if connection.vendor == 'postgresql':
schema_editor.execute(
- '''
+ """
UPDATE patchwork_patch
SET content = patchwork_comment.content
FROM patchwork_comment
WHERE patchwork_patch.id=patchwork_comment.patch_id
AND patchwork_patch.msgid=patchwork_comment.msgid
- '''
+ """
)
elif connection.vendor == 'mysql':
schema_editor.execute(
- '''
+ """
UPDATE patchwork_patch, patchwork_comment
SET patchwork_patch.content = patchwork_comment.content
WHERE patchwork_patch.id=patchwork_comment.patch_id
AND patchwork_patch.msgid=patchwork_comment.msgid
- '''
+ """
)
else:
Comment = apps.get_model('patchwork', 'Comment')
def remove_duplicate_comments(apps, schema_editor):
if connection.vendor == 'postgresql':
schema_editor.execute(
- '''
+ """
DELETE FROM patchwork_comment
USING patchwork_patch
WHERE patchwork_patch.id=patchwork_comment.patch_id
AND patchwork_patch.msgid=patchwork_comment.msgid
- '''
+ """
)
elif connection.vendor == 'mysql':
schema_editor.execute(
- '''
+ """
DELETE FROM patchwork_comment
USING patchwork_patch, patchwork_comment
WHERE patchwork_patch.id=patchwork_comment.patch_id
AND patchwork_patch.msgid=patchwork_comment.msgid
- '''
+ """
)
else:
Comment = apps.get_model('patchwork', 'Comment')
operations = [
migrations.RunSQL(
- '''INSERT INTO patchwork_patch
+ """INSERT INTO patchwork_patch
(submission_ptr_id, diff2, commit_ref2, pull_url2,
delegate2_id, state2_id, archived2, hash2)
SELECT id, diff, commit_ref, pull_url, delegate_id, state_id,
archived, hash
FROM patchwork_submission
- ''',
- '''UPDATE patchwork_submission SET
+ """,
+ """UPDATE patchwork_submission SET
diff=diff2, commit_ref=commit_ref2, pull_url=pull_url2,
delegate_id=delegate2_id, state_id=state2_id,
archived=archived2, hash=hash2
FROM patchwork_patch WHERE
patchwork_submission.id = patchwork_patch.submission_ptr_id
- ''',
+ """,
),
]
field=models.BooleanField(
default=True,
help_text=b"Show a column displaying this tag's count in the "
- b"patch list view",
+ b'patch list view',
),
),
]
),
# as with 10, this will break if you use non-default table names
migrations.RunSQL(
- '''UPDATE patchwork_patch SET patch_project_id =
+ """UPDATE patchwork_patch SET patch_project_id =
(SELECT project_id FROM patchwork_submission
WHERE patchwork_submission.id =
- patchwork_patch.submission_ptr_id);'''
+ patchwork_patch.submission_ptr_id);"""
),
migrations.AlterField(
model_name='patch',
field=models.CharField(
blank=True,
help_text=b"URL format for the list archive's Message-ID "
- b"redirector. {} will be replaced by the "
- b"Message-ID.",
+ b'redirector. {} will be replaced by the '
+ b'Message-ID.',
max_length=2000,
),
),
field=models.CharField(
blank=True,
help_text="URL format for the list archive's Message-ID "
- "redirector. {} will be replaced by the Message-ID.",
+ 'redirector. {} will be replaced by the Message-ID.',
max_length=2000,
),
),
field=models.BooleanField(
default=True,
help_text="Show a column displaying this tag's count in the "
- "patch list view",
+ 'patch list view',
),
),
migrations.AlterField(
max_length=2000,
blank=True,
help_text="URL format for the list archive's Message-ID redirector. "
- "{} will be replaced by the Message-ID.",
+ '{} will be replaced by the Message-ID.',
)
commit_url_format = models.CharField(
max_length=2000,
)
show_column = models.BooleanField(
help_text='Show a column displaying this'
- ' tag\'s count in the patch list view',
+ " tag's count in the patch list view",
default=True,
)
for tag in tags:
select[tag.attr_name] = (
- "coalesce("
- "(SELECT count FROM patchwork_patchtag"
- " WHERE patchwork_patchtag.patch_id=patchwork_patch.id"
- " AND patchwork_patchtag.tag_id=%s), 0)"
+ 'coalesce('
+ '(SELECT count FROM patchwork_patchtag'
+ ' WHERE patchwork_patchtag.patch_id=patchwork_patch.id'
+ ' AND patchwork_patchtag.tag_id=%s), 0)'
)
select_params.append(tag.id)
if not project:
logger.debug(
- "Could not find a valid project for given list-id and " "subject."
+ 'Could not find a valid project for given list-id and ' 'subject.'
)
return project
cc_headers = mail.get_all('Cc') or []
for header in reply_to_headers + cc_headers:
header = clean_header(header)
- addrs = header.split(",")
+ addrs = header.split(',')
for addr in addrs:
new_name, new_email = split_from_header(addr)
if new_name:
# about this
logger.info(
"Malformed 'Message-Id' header. The 'msg-id' component should be "
- "surrounded by angle brackets. Saving raw header. This may "
- "include comments and extra whitespace."
+ 'surrounded by angle brackets. Saving raw header. This may '
+ 'include comments and extra whitespace.'
)
msgid = header.strip()
else:
logger.info(
"Malformed 'In-Reply-To' header. The 'msg-id' component "
- "should be surrounded by angle brackets. Saving raw header. "
- "This may include comments and extra whitespace."
+ 'should be surrounded by angle brackets. Saving raw header. '
+ 'This may include comments and extra whitespace.'
)
ref = header.strip()
refs.append(ref)
count = getattr(patch, tag.attr_name)
titles.append('%d %s' % (count, tag.name))
if count == 0:
- counts.append("-")
+ counts.append('-')
else:
counts.append(str(count))
self._create_events()
resp = self.client.get(self.api_url())
- events = Event.objects.order_by("-date").all()
+ events = Event.objects.order_by('-date').all()
for api_event, event in zip(resp.data, events):
- self.assertEqual(api_event["id"], event.id)
+ self.assertEqual(api_event['id'], event.id)
def test_order_by_date_ascending(self):
"""Assert the default ordering is by date descending."""
self._create_events()
resp = self.client.get(self.api_url(), {'order': 'date'})
- events = Event.objects.order_by("date").all()
+ events = Event.objects.order_by('date').all()
for api_event, event in zip(resp.data, events):
- self.assertEqual(api_event["id"], event.id)
+ self.assertEqual(api_event['id'], event.id)
def test_create(self):
"""Ensure creates aren't allowed"""
state=state_obj,
project=project_obj,
submitter=person_obj,
- **kwargs
+ **kwargs,
)
return patch_obj
self.client.force_authenticate(user=user)
resp = self.client.patch(
- self.api_url(patch.id, version="1.1"),
+ self.api_url(patch.id, version='1.1'),
{'state': state.slug, 'delegate': user.id},
)
self.assertEqual(status.HTTP_200_OK, resp.status_code, resp)
format=None,
content_type=None,
follow=False,
- **extra
+ **extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
format='json',
content_type=content_type,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
response = super(APIClient, self).post(
path,
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
validator.validate_data(
format=None,
content_type=None,
follow=False,
- **extra
+ **extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
format='json',
content_type=content_type,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
response = super(APIClient, self).put(
path,
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
validator.validate_data(
format=None,
content_type=None,
follow=False,
- **extra
+ **extra,
):
validate_request = extra.pop('validate_request', True)
validate_response = extra.pop('validate_response', True)
format='json',
content_type=content_type,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
response = super(APIClient, self).patch(
path,
content_type=content_type,
follow=follow,
SERVER_NAME='example.com',
- **extra
+ **extra,
)
validator.validate_data(
if unexpectedSuccesses:
self.stream.writeln('=' * 70)
for test in unexpectedSuccesses:
- self.stream.writeln(f"UNEXPECTED SUCCESS: {str(test)}")
+ self.stream.writeln(f'UNEXPECTED SUCCESS: {str(test)}')
self.stream.flush()
def printErrorList(self, flavour, errors):
def test_git_rename(self):
diff, _ = self._find_content('0008-git-rename.mbox')
self.assertTrue(diff is not None)
- self.assertEqual(diff.count("\nrename from "), 2)
- self.assertEqual(diff.count("\nrename to "), 2)
+ self.assertEqual(diff.count('\nrename from '), 2)
+ self.assertEqual(diff.count('\nrename to '), 2)
def test_git_rename_with_diff(self):
diff, message = self._find_content('0009-git-rename-with-diff.mbox')
self.assertTrue(diff is not None)
self.assertTrue(message is not None)
- self.assertEqual(diff.count("\nrename from "), 2)
- self.assertEqual(diff.count("\nrename to "), 2)
+ self.assertEqual(diff.count('\nrename from '), 2)
+ self.assertEqual(diff.count('\nrename to '), 2)
self.assertEqual(diff.count('\n-a\n+b'), 1)
def test_git_new_empty_file(self):
class DelegateRequestTest(TestCase):
patch_filename = '0001-add-line.patch'
msgid = '<1@example.com>'
- invalid_delegate_email = "nobody"
+ invalid_delegate_email = 'nobody'
def setUp(self):
self.patch = read_patch(self.patch_filename)
class InitialPatchStateTest(TestCase):
patch_filename = '0001-add-line.patch'
msgid = '<1@example.com>'
- invalid_state_name = "Nonexistent Test State"
+ invalid_state_name = 'Nonexistent Test State'
def setUp(self):
self.default_state = create_state()
self.assertEqual(clean_subject('Re: meep'), ('meep', []))
self.assertEqual(clean_subject('[PATCH] meep'), ('meep', []))
self.assertEqual(
- clean_subject("[PATCH] meep \n meep"), ('meep meep', [])
+ clean_subject('[PATCH] meep \n meep'), ('meep meep', [])
)
self.assertEqual(
- clean_subject("[PATCH] meep,\n meep"), ('meep, meep', [])
+ clean_subject('[PATCH] meep,\n meep'), ('meep, meep', [])
)
self.assertEqual(
clean_subject('[PATCH RFC] meep'), ('[RFC] meep', ['RFC'])
response = self.client.get(reverse('password_change_done'))
self.assertContains(
- response, "Your password has been changed successfully"
+ response, 'Your password has been changed successfully'
)
date = tz_utils.now() - datetime.timedelta(days=1)
date = date.replace(tzinfo=tz, microsecond=0)
- patch.headers = 'Date: %s\n' % date.strftime("%a, %d %b %Y %T %z")
+ patch.headers = 'Date: %s\n' % date.strftime('%a, %d %b %Y %T %z')
patch.save()
mbox = utils.patch_to_mbox(patch)
def test_list_max_count(self):
objs = self.create_multiple(5)
- result = self.list_endpoint("", 2)
+ result = self.list_endpoint('', 2)
self.assertEqual(len(result), 2)
self.assertEqual(result[0]['id'], objs[0].id)
def test_list_negative_max_count(self):
objs = self.create_multiple(5)
- result = self.list_endpoint("", -1)
+ result = self.list_endpoint('', -1)
self.assertEqual(len(result), 1)
self.assertEqual(result[0]['id'], objs[-1].id)
if action == 'create':
bundle_name = data['bundle_name'].strip()
if '/' in bundle_name:
- return ['Bundle names can\'t contain slashes']
+ return ["Bundle names can't contain slashes"]
if not bundle_name:
return ['No bundle name was specified']
bundle = Bundle(owner=user, project=project, name=bundle_name)
bundle.save()
- messages.success(request, "Bundle %s created" % bundle.name)
+ messages.success(request, 'Bundle %s created' % bundle.name)
elif action == 'add':
bundle = get_object_or_404(Bundle, id=data['bundle_id'])
elif action == 'remove':
return HttpResponseNotFound()
response = HttpResponse(content_type='text/plain')
- response[
- 'Content-Disposition'
- ] = 'attachment; filename=bundle-%d-%s.mbox' % (bundle.id, bundle.name)
+ response['Content-Disposition'] = (
+ 'attachment; filename=bundle-%d-%s.mbox' % (bundle.id, bundle.name)
+ )
response.write(bundle_to_mbox(bundle))
return response
and EmailOptout.objects.filter(email=email).count() == 0
):
context['error'] = (
- "The email address %s is not on the patchwork "
+ 'The email address %s is not on the patchwork '
"opt-out list, so you don't need to opt back in" % email
)
context['form'] = form
project = get_object_or_404(Project, linkname=project_id)
patch = get_object_or_404(Patch, project_id=project.id, msgid=db_msgid)
- response = HttpResponse(content_type="text/x-patch")
+ response = HttpResponse(content_type='text/x-patch')
response.write(patch.diff)
response['Content-Disposition'] = 'attachment; filename=%s.diff' % (
patch.filename
body = ''
if submission.content:
- body = submission.content.strip() + "\n"
+ body = submission.content.strip() + '\n'
parts = postscript_re.split(body, 1)
if len(parts) == 2:
(body, postscript) = parts
- body = body.strip() + "\n"
+ body = body.strip() + '\n'
postscript = postscript.rstrip()
else:
postscript = ''
@xmlrpc_method(login_required=True)
def check_create(
- user, patch_id, context, state, target_url="", description=""
+ user, patch_id, context, state, target_url='', description=''
):
"""Add a Check to a patch.
state = state_val
break
else:
- raise Exception("Invalid check state: %s" % state)
+ raise Exception('Invalid check state: %s' % state)
Check.objects.create(
patch=patch,
context=context,