From aa876f80169c750a6d67f7016a525dc0fc625ea8 Mon Sep 17 00:00:00 2001
From: Martin Whitehouse
Date: Tue, 12 Jul 2022 12:34:19 +0200
Subject: [PATCH] pycodestyle formatting
---
demo/demodesk/config/settings.py | 16 +-
demo/demodesk/manage.py | 2 +
demo/manage.py | 2 +
demo/setup.py | 2 +-
docs/conf.py | 15 +-
helpdesk/admin.py | 4 +-
helpdesk/apps.py | 3 +-
helpdesk/email.py | 123 +++++---
helpdesk/forms.py | 120 +++++---
helpdesk/lib.py | 6 +-
.../commands/create_escalation_exclusions.py | 15 +-
.../commands/create_queue_permissions.py | 9 +-
.../management/commands/escalate_tickets.py | 6 +-
helpdesk/models.py | 65 +++--
helpdesk/query.py | 15 +-
helpdesk/settings.py | 80 ++++--
helpdesk/templated_email.py | 18 +-
helpdesk/templatetags/helpdesk_staff.py | 3 +-
helpdesk/templatetags/helpdesk_util.py | 9 +-
helpdesk/tests/test_api.py | 46 +--
helpdesk/tests/test_attachments.py | 27 +-
helpdesk/tests/test_get_email.py | 269 ++++++++++++------
helpdesk/tests/test_kb.py | 33 ++-
helpdesk/tests/test_navigation.py | 39 ++-
.../tests/test_per_queue_staff_permission.py | 36 ++-
helpdesk/tests/test_public_actions.py | 3 +-
helpdesk/tests/test_query.py | 18 +-
helpdesk/tests/test_ticket_actions.py | 63 ++--
helpdesk/tests/test_ticket_lookup.py | 18 +-
helpdesk/tests/test_ticket_submission.py | 59 ++--
helpdesk/tests/test_usersettings.py | 3 +-
helpdesk/urls.py | 27 +-
helpdesk/user.py | 4 +-
helpdesk/validators.py | 16 +-
helpdesk/views/abstract_views.py | 12 +-
helpdesk/views/feeds.py | 3 +-
helpdesk/views/public.py | 30 +-
helpdesk/views/staff.py | 123 +++++---
quicktest.py | 14 +-
39 files changed, 892 insertions(+), 464 deletions(-)
diff --git a/demo/demodesk/config/settings.py b/demo/demodesk/config/settings.py
index ec301a91..5aaccfbf 100644
--- a/demo/demodesk/config/settings.py
+++ b/demo/demodesk/config/settings.py
@@ -97,13 +97,13 @@ WSGI_APPLICATION = 'demo.demodesk.config.wsgi.application'
# Some common settings are below.
HELPDESK_DEFAULT_SETTINGS = {
- 'use_email_as_submitter': True,
- 'email_on_ticket_assign': True,
- 'email_on_ticket_change': True,
- 'login_view_ticketlist': True,
- 'email_on_ticket_apichange': True,
- 'preset_replies': True,
- 'tickets_per_page': 25
+ 'use_email_as_submitter': True,
+ 'email_on_ticket_assign': True,
+ 'email_on_ticket_change': True,
+ 'login_view_ticketlist': True,
+ 'email_on_ticket_apichange': True,
+ 'preset_replies': True,
+ 'tickets_per_page': 25
}
# Should the public web portal be enabled?
@@ -153,7 +153,7 @@ SITE_ID = 1
# Sessions
# https://docs.djangoproject.com/en/1.11/topics/http/sessions
-SESSION_COOKIE_AGE = 86400 # = 1 day
+SESSION_COOKIE_AGE = 86400 # = 1 day
# For better default security, set these cookie flags, but
# these are likely to cause problems when testing locally
diff --git a/demo/demodesk/manage.py b/demo/demodesk/manage.py
index 3427b7bc..0bc07500 100755
--- a/demo/demodesk/manage.py
+++ b/demo/demodesk/manage.py
@@ -2,6 +2,7 @@
import os
import sys
+
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demodesk.config.settings")
try:
@@ -21,5 +22,6 @@ def main():
raise
execute_from_command_line(sys.argv)
+
if __name__ == "__main__":
main()
diff --git a/demo/manage.py b/demo/manage.py
index 3427b7bc..0bc07500 100755
--- a/demo/manage.py
+++ b/demo/manage.py
@@ -2,6 +2,7 @@
import os
import sys
+
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demodesk.config.settings")
try:
@@ -21,5 +22,6 @@ def main():
raise
execute_from_command_line(sys.argv)
+
if __name__ == "__main__":
main()
diff --git a/demo/setup.py b/demo/setup.py
index 463a15e0..93b1ab32 100644
--- a/demo/setup.py
+++ b/demo/setup.py
@@ -28,7 +28,7 @@ KEYWORDS = []
PACKAGES = ['demodesk']
REQUIREMENTS = [
'django-helpdesk'
- ]
+]
ENTRY_POINTS = {
'console_scripts': ['demodesk = demodesk.manage:main']
}
diff --git a/docs/conf.py b/docs/conf.py
index 3d4ce533..6e384cb3 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -11,14 +11,15 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys, os
+import sys
+import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
-# -- General configuration -----------------------------------------------------
+# -- General configuration -----------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
@@ -87,7 +88,7 @@ pygments_style = 'sphinx'
#modindex_common_prefix = []
-# -- Options for HTML output ---------------------------------------------------
+# -- Options for HTML output ---------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
@@ -167,7 +168,7 @@ html_static_path = ['_static']
htmlhelp_basename = 'django-helpdeskdoc'
-# -- Options for LaTeX output --------------------------------------------------
+# -- Options for LaTeX output --------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
@@ -178,8 +179,8 @@ htmlhelp_basename = 'django-helpdeskdoc'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
- ('index', 'django-helpdesk.tex', u'django-helpdesk Documentation',
- u'Ross Poulton + django-helpdesk Contributors', 'manual'),
+ ('index', 'django-helpdesk.tex', u'django-helpdesk Documentation',
+ u'Ross Poulton + django-helpdesk Contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -206,7 +207,7 @@ latex_documents = [
#latex_domain_indices = True
-# -- Options for manual page output --------------------------------------------
+# -- Options for manual page output --------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
diff --git a/helpdesk/admin.py b/helpdesk/admin.py
index b074d5ae..6fbd352d 100644
--- a/helpdesk/admin.py
+++ b/helpdesk/admin.py
@@ -9,6 +9,7 @@ if helpdesk_settings.HELPDESK_KB_ENABLED:
from helpdesk.models import KBCategory
from helpdesk.models import KBItem
+
@admin.register(Queue)
class QueueAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'email_address', 'locale', 'time_spent')
@@ -74,7 +75,8 @@ class FollowUpAdmin(admin.ModelAdmin):
if helpdesk_settings.HELPDESK_KB_ENABLED:
@admin.register(KBItem)
class KBItemAdmin(admin.ModelAdmin):
- list_display = ('category', 'title', 'last_updated', 'team', 'order', 'enabled')
+ list_display = ('category', 'title', 'last_updated',
+ 'team', 'order', 'enabled')
inlines = [KBIAttachmentInline]
readonly_fields = ('voted_by', 'downvoted_by')
diff --git a/helpdesk/apps.py b/helpdesk/apps.py
index fff4c8f2..a3ed19d2 100644
--- a/helpdesk/apps.py
+++ b/helpdesk/apps.py
@@ -5,5 +5,6 @@ class HelpdeskConfig(AppConfig):
name = 'helpdesk'
verbose_name = "Helpdesk"
# for Django 3.2 support:
- # see: https://docs.djangoproject.com/en/3.2/ref/applications/#django.apps.AppConfig.default_auto_field
+ # see:
+ # https://docs.djangoproject.com/en/3.2/ref/applications/#django.apps.AppConfig.default_auto_field
default_auto_field = 'django.db.models.AutoField'
diff --git a/helpdesk/email.py b/helpdesk/email.py
index 537f9af4..6fe347ac 100644
--- a/helpdesk/email.py
+++ b/helpdesk/email.py
@@ -72,7 +72,8 @@ def process_email(quiet=False):
# Log messages to specific file only if the queue has it configured
if (q.logging_type in logging_types) and q.logging_dir: # if it's enabled and the dir is set
- log_file_handler = logging.FileHandler(join(q.logging_dir, q.slug + '_get_email.log'))
+ log_file_handler = logging.FileHandler(
+ join(q.logging_dir, q.slug + '_get_email.log'))
logger.addHandler(log_file_handler)
else:
log_file_handler = None
@@ -105,7 +106,8 @@ def pop3_sync(q, logger, server):
try:
server.stls()
except Exception:
- logger.warning("POP3 StartTLS failed or unsupported. Connection will be unencrypted.")
+ logger.warning(
+ "POP3 StartTLS failed or unsupported. Connection will be unencrypted.")
server.user(q.email_box_user or settings.QUEUE_EMAIL_BOX_USER)
server.pass_(q.email_box_pass or settings.QUEUE_EMAIL_BOX_PASSWORD)
@@ -127,16 +129,21 @@ def pop3_sync(q, logger, server):
raw_content = server.retr(msgNum)[1]
if type(raw_content[0]) is bytes:
- full_message = "\n".join([elm.decode('utf-8') for elm in raw_content])
+ full_message = "\n".join([elm.decode('utf-8')
+ for elm in raw_content])
else:
- full_message = encoding.force_str("\n".join(raw_content), errors='replace')
- ticket = object_from_message(message=full_message, queue=q, logger=logger)
+ full_message = encoding.force_str(
+ "\n".join(raw_content), errors='replace')
+ ticket = object_from_message(
+ message=full_message, queue=q, logger=logger)
if ticket:
server.dele(msgNum)
- logger.info("Successfully processed message %s, deleted from POP3 server" % msgNum)
+ logger.info(
+ "Successfully processed message %s, deleted from POP3 server" % msgNum)
else:
- logger.warn("Message %s was not successfully processed, and will be left on POP3 server" % msgNum)
+ logger.warn(
+ "Message %s was not successfully processed, and will be left on POP3 server" % msgNum)
server.quit()
@@ -146,7 +153,8 @@ def imap_sync(q, logger, server):
try:
server.starttls()
except Exception:
- logger.warning("IMAP4 StartTLS unsupported or failed. Connection will be unencrypted.")
+ logger.warning(
+ "IMAP4 StartTLS unsupported or failed. Connection will be unencrypted.")
server.login(q.email_box_user or
settings.QUEUE_EMAIL_BOX_USER,
q.email_box_pass or
@@ -177,14 +185,17 @@ def imap_sync(q, logger, server):
status, data = server.fetch(num, '(RFC822)')
full_message = encoding.force_str(data[0][1], errors='replace')
try:
- ticket = object_from_message(message=full_message, queue=q, logger=logger)
+ ticket = object_from_message(
+ message=full_message, queue=q, logger=logger)
except TypeError:
ticket = None # hotfix. Need to work out WHY.
if ticket:
server.store(num, '+FLAGS', '\\Deleted')
- logger.info("Successfully processed message %s, deleted from IMAP server" % num)
+ logger.info(
+ "Successfully processed message %s, deleted from IMAP server" % num)
else:
- logger.warn("Message %s was not successfully processed, and will be left on IMAP server" % num)
+ logger.warn(
+ "Message %s was not successfully processed, and will be left on IMAP server" % num)
except imaplib.IMAP4.error:
logger.error(
"IMAP retrieve failed. Is the folder '%s' spelled correctly, and does it exist on the server?",
@@ -261,7 +272,8 @@ def process_queue(q, logger):
elif email_box_type == 'local':
mail_dir = q.email_box_local_dir or '/var/lib/mail/helpdesk/'
- mail = [join(mail_dir, f) for f in os.listdir(mail_dir) if isfile(join(mail_dir, f))]
+ mail = [join(mail_dir, f)
+ for f in os.listdir(mail_dir) if isfile(join(mail_dir, f))]
logger.info("Found %d messages in local mailbox directory" % len(mail))
logger.info("Found %d messages in local mailbox directory" % len(mail))
@@ -269,17 +281,22 @@ def process_queue(q, logger):
logger.info("Processing message %d" % i)
with open(m, 'r') as f:
full_message = encoding.force_str(f.read(), errors='replace')
- ticket = object_from_message(message=full_message, queue=q, logger=logger)
+ ticket = object_from_message(
+ message=full_message, queue=q, logger=logger)
if ticket:
- logger.info("Successfully processed message %d, ticket/comment created.", i)
+ logger.info(
+ "Successfully processed message %d, ticket/comment created.", i)
try:
- os.unlink(m) # delete message file if ticket was successful
+ # delete message file if ticket was successful
+ os.unlink(m)
except OSError as e:
- logger.error("Unable to delete message %d (%s).", i, str(e))
+ logger.error(
+ "Unable to delete message %d (%s).", i, str(e))
else:
logger.info("Successfully deleted message %d.", i)
else:
- logger.warn("Message %d was not successfully processed, and will be left in local directory", i)
+ logger.warn(
+ "Message %d was not successfully processed, and will be left in local directory", i)
def decodeUnknown(charset, string):
@@ -309,8 +326,10 @@ def is_autoreply(message):
So we don't start mail loops
"""
any_if_this = [
- False if not message.get("Auto-Submitted") else message.get("Auto-Submitted").lower() != "no",
- True if message.get("X-Auto-Response-Suppress") in ("DR", "AutoReply", "All") else False,
+ False if not message.get(
+ "Auto-Submitted") else message.get("Auto-Submitted").lower() != "no",
+ True if message.get("X-Auto-Response-Suppress") in ("DR",
+ "AutoReply", "All") else False,
message.get("List-Id"),
message.get("List-Unsubscribe"),
]
@@ -340,7 +359,8 @@ def create_ticket_cc(ticket, cc_list):
pass
try:
- ticket_cc = subscribe_to_ticket_updates(ticket=ticket, user=user, email=cced_email)
+ ticket_cc = subscribe_to_ticket_updates(
+ ticket=ticket, user=user, email=cced_email)
new_ticket_ccs.append(ticket_cc)
except ValidationError:
pass
@@ -370,7 +390,8 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
if in_reply_to is not None:
try:
- queryset = FollowUp.objects.filter(message_id=in_reply_to).order_by('-date')
+ queryset = FollowUp.objects.filter(
+ message_id=in_reply_to).order_by('-date')
if queryset.count() > 0:
previous_followup = queryset.first()
ticket = previous_followup.ticket
@@ -386,7 +407,8 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
new = False
# Check if the ticket has been merged to another ticket
if ticket.merged_to:
- logger.info("Ticket has been merged to %s" % ticket.merged_to.ticket)
+ logger.info("Ticket has been merged to %s" %
+ ticket.merged_to.ticket)
# Use the ticket in which it was merged to for next operations
ticket = ticket.merged_to
@@ -402,7 +424,8 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
priority=payload['priority'],
)
ticket.save()
- logger.debug("Created new ticket %s-%s" % (ticket.queue.slug, ticket.id))
+ logger.debug("Created new ticket %s-%s" %
+ (ticket.queue.slug, ticket.id))
new = True
@@ -413,7 +436,8 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
f = FollowUp(
ticket=ticket,
- title=_('E-Mail Received from %(sender_email)s' % {'sender_email': sender_email}),
+ title=_('E-Mail Received from %(sender_email)s' %
+ {'sender_email': sender_email}),
date=now,
public=True,
comment=payload.get('full_body', payload['body']) or "",
@@ -422,7 +446,8 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
if ticket.status == Ticket.REOPENED_STATUS:
f.new_status = Ticket.REOPENED_STATUS
- f.title = _('Ticket Re-Opened by E-Mail Received from %(sender_email)s' % {'sender_email': sender_email})
+ f.title = _('Ticket Re-Opened by E-Mail Received from %(sender_email)s' %
+ {'sender_email': sender_email})
f.save()
logger.debug("Created new FollowUp for Ticket")
@@ -445,14 +470,16 @@ def create_object_from_email_message(message, ticket_id, payload, files, logger)
if queue.enable_notifications_on_email_events and len(notifications_to_be_sent):
- ticket_cc_list = TicketCC.objects.filter(ticket=ticket).all().values_list('email', flat=True)
+ ticket_cc_list = TicketCC.objects.filter(
+ ticket=ticket).all().values_list('email', flat=True)
for email_address in ticket_cc_list:
notifications_to_be_sent.append(email_address)
autoreply = is_autoreply(message)
if autoreply:
- logger.info("Message seems to be auto-reply, not sending any emails back to the sender")
+ logger.info(
+ "Message seems to be auto-reply, not sending any emails back to the sender")
else:
# send mail to appropriate people now depending on what objects
# were created and who was CC'd
@@ -494,7 +521,8 @@ def object_from_message(message, queue, logger):
message = email.message_from_string(message)
subject = message.get('subject', _('Comment from e-mail'))
- subject = decode_mail_headers(decodeUnknown(message.get_charset(), subject))
+ subject = decode_mail_headers(
+ decodeUnknown(message.get_charset(), subject))
for affix in STRIPPED_SUBJECT_STRINGS:
subject = subject.replace(affix, "")
subject = subject.strip()
@@ -508,13 +536,16 @@ def object_from_message(message, queue, logger):
# Note that the replace won't work on just an email with no real name,
# but the getaddresses() function seems to be able to handle just unclosed quotes
# correctly. Not ideal, but this seems to work for now.
- sender_email = email.utils.getaddresses(['\"' + sender.replace('<', '\" <')])[0][1]
+ sender_email = email.utils.getaddresses(
+ ['\"' + sender.replace('<', '\" <')])[0][1]
cc = message.get_all('cc', None)
if cc:
# first, fixup the encoding if necessary
- cc = [decode_mail_headers(decodeUnknown(message.get_charset(), x)) for x in cc]
- # get_all checks if multiple CC headers, but individual emails may be comma separated too
+ cc = [decode_mail_headers(decodeUnknown(
+ message.get_charset(), x)) for x in cc]
+ # get_all checks if multiple CC headers, but individual emails may be
+ # comma separated too
tempcc = []
for hdr in cc:
tempcc.extend(hdr.split(','))
@@ -561,14 +592,16 @@ def object_from_message(message, queue, logger):
# have to use django_settings here so overwritting it works in tests
# the default value is False anyway
if ticket is None and getattr(django_settings, 'HELPDESK_FULL_FIRST_MESSAGE_FROM_EMAIL', False):
- # first message in thread, we save full body to avoid losing forwards and things like that
+ # first message in thread, we save full body to avoid
+ # losing forwards and things like that
body_parts = []
for f in EmailReplyParser.read(body).fragments:
body_parts.append(f.content)
full_body = '\n\n'.join(body_parts)
body = EmailReplyParser.parse_reply(body)
else:
- # second and other reply, save only first part of the message
+ # second and other reply, save only first part of the
+ # message
body = EmailReplyParser.parse_reply(body)
full_body = body
# workaround to get unicode text out rather than escaped text
@@ -579,13 +612,17 @@ def object_from_message(message, queue, logger):
logger.debug("Discovered plain text MIME part")
else:
try:
- email_body = encoding.smart_str(part.get_payload(decode=True))
+ email_body = encoding.smart_str(
+ part.get_payload(decode=True))
except UnicodeDecodeError:
- email_body = encoding.smart_str(part.get_payload(decode=False))
+ email_body = encoding.smart_str(
+ part.get_payload(decode=False))
if not body and not full_body:
- # no text has been parsed so far - try such deep parsing for some messages
- altered_body = email_body.replace("
", "\n").replace(" ", "\n").replace(" '
) % email_body
files.append(
- SimpleUploadedFile(_("email_html_body.html"), payload.encode("utf-8"), 'text/html')
+ SimpleUploadedFile(
+ _("email_html_body.html"), payload.encode("utf-8"), 'text/html')
)
logger.debug("Discovered HTML MIME part")
else:
@@ -627,7 +665,8 @@ def object_from_message(message, queue, logger):
# except non_b64_err:
# logger.debug("Payload was not base64 encoded, using raw bytes")
# # payloadToWrite = payload
- files.append(SimpleUploadedFile(name, part.get_payload(decode=True), mimetypes.guess_type(name)[0]))
+ files.append(SimpleUploadedFile(name, part.get_payload(
+ decode=True), mimetypes.guess_type(name)[0]))
logger.debug("Found MIME attachment %s" % name)
counter += 1
@@ -645,7 +684,8 @@ def object_from_message(message, queue, logger):
body = ""
if getattr(django_settings, 'HELPDESK_ALWAYS_SAVE_INCOMING_EMAIL_MESSAGE', False):
- # save message as attachment in case of some complex markup renders wrong
+ # save message as attachment in case of some complex markup renders
+ # wrong
files.append(
SimpleUploadedFile(
_("original_message.eml").replace(
@@ -660,7 +700,8 @@ def object_from_message(message, queue, logger):
smtp_priority = message.get('priority', '')
smtp_importance = message.get('importance', '')
high_priority_types = {'high', 'important', '1', 'urgent'}
- priority = 2 if high_priority_types & {smtp_priority, smtp_importance} else 3
+ priority = 2 if high_priority_types & {
+ smtp_priority, smtp_importance} else 3
payload = {
'body': body,
diff --git a/helpdesk/forms.py b/helpdesk/forms.py
index 4b74aac2..9aa32a69 100644
--- a/helpdesk/forms.py
+++ b/helpdesk/forms.py
@@ -37,40 +37,49 @@ class CustomFieldMixin(object):
def customfield_to_field(self, field, instanceargs):
# Use TextInput widget by default
- instanceargs['widget'] = forms.TextInput(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.TextInput(
+ attrs={'class': 'form-control'})
# if-elif branches start with special cases
if field.data_type == 'varchar':
fieldclass = forms.CharField
instanceargs['max_length'] = field.max_length
elif field.data_type == 'text':
fieldclass = forms.CharField
- instanceargs['widget'] = forms.Textarea(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.Textarea(
+ attrs={'class': 'form-control'})
instanceargs['max_length'] = field.max_length
elif field.data_type == 'integer':
fieldclass = forms.IntegerField
- instanceargs['widget'] = forms.NumberInput(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.NumberInput(
+ attrs={'class': 'form-control'})
elif field.data_type == 'decimal':
fieldclass = forms.DecimalField
instanceargs['decimal_places'] = field.decimal_places
instanceargs['max_digits'] = field.max_length
- instanceargs['widget'] = forms.NumberInput(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.NumberInput(
+ attrs={'class': 'form-control'})
elif field.data_type == 'list':
fieldclass = forms.ChoiceField
instanceargs['choices'] = field.get_choices()
- instanceargs['widget'] = forms.Select(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.Select(
+ attrs={'class': 'form-control'})
else:
# Try to use the immediate equivalences dictionary
try:
fieldclass = CUSTOMFIELD_TO_FIELD_DICT[field.data_type]
# Change widgets for the following classes
if fieldclass == forms.DateField:
- instanceargs['widget'] = forms.DateInput(attrs={'class': 'form-control date-field'})
+ instanceargs['widget'] = forms.DateInput(
+ attrs={'class': 'form-control date-field'})
elif fieldclass == forms.DateTimeField:
- instanceargs['widget'] = forms.DateTimeInput(attrs={'class': 'form-control datetime-field'})
+ instanceargs['widget'] = forms.DateTimeInput(
+ attrs={'class': 'form-control datetime-field'})
elif fieldclass == forms.TimeField:
- instanceargs['widget'] = forms.TimeInput(attrs={'class': 'form-control time-field'})
+ instanceargs['widget'] = forms.TimeInput(
+ attrs={'class': 'form-control time-field'})
elif fieldclass == forms.BooleanField:
- instanceargs['widget'] = forms.CheckboxInput(attrs={'class': 'form-control'})
+ instanceargs['widget'] = forms.CheckboxInput(
+ attrs={'class': 'form-control'})
except KeyError:
# The data_type was not found anywhere
@@ -83,10 +92,12 @@ class EditTicketForm(CustomFieldMixin, forms.ModelForm):
class Meta:
model = Ticket
- exclude = ('created', 'modified', 'status', 'on_hold', 'resolution', 'last_escalation', 'assigned_to')
+ exclude = ('created', 'modified', 'status', 'on_hold',
+ 'resolution', 'last_escalation', 'assigned_to')
class Media:
- js = ('helpdesk/js/init_due_date.js', 'helpdesk/js/init_datetime_classes.js')
+ js = ('helpdesk/js/init_due_date.js',
+ 'helpdesk/js/init_datetime_classes.js')
def __init__(self, *args, **kwargs):
"""
@@ -96,21 +107,28 @@ class EditTicketForm(CustomFieldMixin, forms.ModelForm):
# Disable and add help_text to the merged_to field on this form
self.fields['merged_to'].disabled = True
- self.fields['merged_to'].help_text = _('This ticket is merged into the selected ticket.')
+ self.fields['merged_to'].help_text = _(
+ 'This ticket is merged into the selected ticket.')
for field in CustomField.objects.all():
initial_value = None
try:
- current_value = TicketCustomFieldValue.objects.get(ticket=self.instance, field=field)
+ current_value = TicketCustomFieldValue.objects.get(
+ ticket=self.instance, field=field)
initial_value = current_value.value
- # Attempt to convert from fixed format string to date/time data type
+ # Attempt to convert from fixed format string to date/time data
+ # type
if 'datetime' == current_value.field.data_type:
- initial_value = datetime.strptime(initial_value, CUSTOMFIELD_DATETIME_FORMAT)
+ initial_value = datetime.strptime(
+ initial_value, CUSTOMFIELD_DATETIME_FORMAT)
elif 'date' == current_value.field.data_type:
- initial_value = datetime.strptime(initial_value, CUSTOMFIELD_DATE_FORMAT)
+ initial_value = datetime.strptime(
+ initial_value, CUSTOMFIELD_DATE_FORMAT)
elif 'time' == current_value.field.data_type:
- initial_value = datetime.strptime(initial_value, CUSTOMFIELD_TIME_FORMAT)
- # If it is boolean field, transform the value to a real boolean instead of a string
+ initial_value = datetime.strptime(
+ initial_value, CUSTOMFIELD_TIME_FORMAT)
+ # If it is boolean field, transform the value to a real boolean
+ # instead of a string
elif 'boolean' == current_value.field.data_type:
initial_value = 'True' == initial_value
except (TicketCustomFieldValue.DoesNotExist, ValueError, TypeError):
@@ -133,9 +151,11 @@ class EditTicketForm(CustomFieldMixin, forms.ModelForm):
field_name = field.replace('custom_', '', 1)
customfield = CustomField.objects.get(name=field_name)
try:
- cfv = TicketCustomFieldValue.objects.get(ticket=self.instance, field=customfield)
+ cfv = TicketCustomFieldValue.objects.get(
+ ticket=self.instance, field=customfield)
except ObjectDoesNotExist:
- cfv = TicketCustomFieldValue(ticket=self.instance, field=customfield)
+ cfv = TicketCustomFieldValue(
+ ticket=self.instance, field=customfield)
cfv.value = convert_value(value)
cfv.save()
@@ -152,7 +172,8 @@ class EditFollowUpForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
"""Filter not openned tickets here."""
super(EditFollowUpForm, self).__init__(*args, **kwargs)
- self.fields["ticket"].queryset = Ticket.objects.filter(status__in=(Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS))
+ self.fields["ticket"].queryset = Ticket.objects.filter(
+ status__in=(Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS))
class AbstractTicketForm(CustomFieldMixin, forms.Form):
@@ -178,7 +199,8 @@ class AbstractTicketForm(CustomFieldMixin, forms.Form):
widget=forms.Textarea(attrs={'class': 'form-control'}),
label=_('Description of your issue'),
required=True,
- help_text=_('Please be as descriptive as possible and include all details'),
+ help_text=_(
+ 'Please be as descriptive as possible and include all details'),
)
priority = forms.ChoiceField(
@@ -187,13 +209,16 @@ class AbstractTicketForm(CustomFieldMixin, forms.Form):
required=True,
initial=getattr(settings, 'HELPDESK_PUBLIC_TICKET_PRIORITY', '3'),
label=_('Priority'),
- help_text=_("Please select a priority carefully. If unsure, leave it as '3'."),
+ help_text=_(
+ "Please select a priority carefully. If unsure, leave it as '3'."),
)
due_date = forms.DateTimeField(
- widget=forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'}),
+ widget=forms.TextInput(
+ attrs={'class': 'form-control', 'autocomplete': 'off'}),
required=False,
- input_formats=[CUSTOMFIELD_DATE_FORMAT, CUSTOMFIELD_DATETIME_FORMAT, '%d/%m/%Y', '%m/%d/%Y', "%d.%m.%Y"],
+ input_formats=[CUSTOMFIELD_DATE_FORMAT,
+ CUSTOMFIELD_DATETIME_FORMAT, '%d/%m/%Y', '%m/%d/%Y', "%d.%m.%Y"],
label=_('Due on'),
)
@@ -205,7 +230,8 @@ class AbstractTicketForm(CustomFieldMixin, forms.Form):
)
class Media:
- js = ('helpdesk/js/init_due_date.js', 'helpdesk/js/init_datetime_classes.js')
+ js = ('helpdesk/js/init_due_date.js',
+ 'helpdesk/js/init_datetime_classes.js')
def __init__(self, kbcategory=None, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -215,7 +241,8 @@ class AbstractTicketForm(CustomFieldMixin, forms.Form):
widget=forms.Select(attrs={'class': 'form-control'}),
required=False,
label=_('Knowledge Base Item'),
- choices=[(kbi.pk, kbi.title) for kbi in KBItem.objects.filter(category=kbcategory.pk, enabled=True)],
+ choices=[(kbi.pk, kbi.title) for kbi in KBItem.objects.filter(
+ category=kbcategory.pk, enabled=True)],
)
def _add_form_custom_fields(self, staff_only_filter=None):
@@ -307,7 +334,8 @@ class TicketForm(AbstractTicketForm):
submitter_email = forms.EmailField(
required=False,
label=_('Submitter E-Mail Address'),
- widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'email'}),
+ widget=forms.TextInput(
+ attrs={'class': 'form-control', 'type': 'email'}),
help_text=_('This e-mail address will receive copies of all public '
'updates to this ticket.'),
)
@@ -335,10 +363,13 @@ class TicketForm(AbstractTicketForm):
self.fields['queue'].choices = queue_choices
if helpdesk_settings.HELPDESK_STAFF_ONLY_TICKET_OWNERS:
- assignable_users = User.objects.filter(is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
+ assignable_users = User.objects.filter(
+ is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
else:
- assignable_users = User.objects.filter(is_active=True).order_by(User.USERNAME_FIELD)
- self.fields['assigned_to'].choices = [('', '--------')] + [(u.id, u.get_username()) for u in assignable_users]
+ assignable_users = User.objects.filter(
+ is_active=True).order_by(User.USERNAME_FIELD)
+ self.fields['assigned_to'].choices = [
+ ('', '--------')] + [(u.id, u.get_username()) for u in assignable_users]
self._add_form_custom_fields()
def save(self, user):
@@ -380,7 +411,8 @@ class PublicTicketForm(AbstractTicketForm):
Ticket Form creation for all users (public-facing).
"""
submitter_email = forms.EmailField(
- widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'email'}),
+ widget=forms.TextInput(
+ attrs={'class': 'form-control', 'type': 'email'}),
required=True,
label=_('Your E-Mail Address'),
help_text=_('We will e-mail you when your ticket is updated.'),
@@ -406,7 +438,8 @@ class PublicTicketForm(AbstractTicketForm):
}
for field_name, field_setting_key in field_deletion_table.items():
- has_settings_default_value = getattr(settings, field_setting_key, None)
+ has_settings_default_value = getattr(
+ settings, field_setting_key, None)
if has_settings_default_value is not None:
del self.fields[field_name]
@@ -485,9 +518,11 @@ class TicketCCForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TicketCCForm, self).__init__(*args, **kwargs)
if helpdesk_settings.HELPDESK_STAFF_ONLY_TICKET_CC:
- users = User.objects.filter(is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
+ users = User.objects.filter(
+ is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
else:
- users = User.objects.filter(is_active=True).order_by(User.USERNAME_FIELD)
+ users = User.objects.filter(
+ is_active=True).order_by(User.USERNAME_FIELD)
self.fields['user'].queryset = users
@@ -497,9 +532,11 @@ class TicketCCUserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TicketCCUserForm, self).__init__(*args, **kwargs)
if helpdesk_settings.HELPDESK_STAFF_ONLY_TICKET_CC:
- users = User.objects.filter(is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
+ users = User.objects.filter(
+ is_active=True, is_staff=True).order_by(User.USERNAME_FIELD)
else:
- users = User.objects.filter(is_active=True).order_by(User.USERNAME_FIELD)
+ users = User.objects.filter(
+ is_active=True).order_by(User.USERNAME_FIELD)
self.fields['user'].queryset = users
class Meta:
@@ -538,8 +575,11 @@ class MultipleTicketSelectForm(forms.Form):
if len(tickets) < 2:
raise ValidationError(_('Please choose at least 2 tickets.'))
if len(tickets) > 4:
- raise ValidationError(_('Impossible to merge more than 4 tickets...'))
- queues = tickets.order_by('queue').distinct().values_list('queue', flat=True)
+ raise ValidationError(
+ _('Impossible to merge more than 4 tickets...'))
+ queues = tickets.order_by('queue').distinct(
+ ).values_list('queue', flat=True)
if len(queues) != 1:
- raise ValidationError(_('All selected tickets must share the same queue in order to be merged.'))
+ raise ValidationError(
+ _('All selected tickets must share the same queue in order to be merged.'))
return tickets
diff --git a/helpdesk/lib.py b/helpdesk/lib.py
index 7d2a1c04..911c7a96 100644
--- a/helpdesk/lib.py
+++ b/helpdesk/lib.py
@@ -129,7 +129,8 @@ def text_is_spam(text, request):
def process_attachments(followup, attached_files):
- max_email_attachment_size = getattr(settings, 'HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE', 512000)
+ max_email_attachment_size = getattr(
+ settings, 'HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE', 512000)
attachments = []
for attached in attached_files:
@@ -152,7 +153,8 @@ def process_attachments(followup, attached_files):
if attached.size < max_email_attachment_size:
# Only files smaller than 512kb (or as defined in
- # settings.HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE) are sent via email.
+ # settings.HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE) are sent via
+ # email.
attachments.append([filename, att.file])
return attachments
diff --git a/helpdesk/management/commands/create_escalation_exclusions.py b/helpdesk/management/commands/create_escalation_exclusions.py
index 8801e0f0..9e2148d5 100644
--- a/helpdesk/management/commands/create_escalation_exclusions.py
+++ b/helpdesk/management/commands/create_escalation_exclusions.py
@@ -66,7 +66,8 @@ class Command(BaseCommand):
raise CommandError("Queue %s does not exist." % queue)
queues.append(q)
- create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)
+ create_exclusions(days=days, occurrences=occurrences,
+ verbose=verbose, queues=queues)
day_names = {
@@ -90,11 +91,13 @@ def create_exclusions(days, occurrences, verbose, queues):
while i < occurrences:
if day == workdate.weekday():
if EscalationExclusion.objects.filter(date=workdate).count() == 0:
- esc = EscalationExclusion(name='Auto Exclusion for %s' % day_name, date=workdate)
+ esc = EscalationExclusion(
+ name='Auto Exclusion for %s' % day_name, date=workdate)
esc.save()
if verbose:
- print("Created exclusion for %s %s" % (day_name, workdate))
+ print("Created exclusion for %s %s" %
+ (day_name, workdate))
for q in queues:
esc.queues.add(q)
@@ -116,7 +119,8 @@ def usage():
if __name__ == '__main__':
# This script can be run from the command-line or via Django's manage.py.
try:
- opts, args = getopt.getopt(sys.argv[1:], 'd:o:q:v', ['days=', 'occurrences=', 'verbose', 'queues='])
+ opts, args = getopt.getopt(sys.argv[1:], 'd:o:q:v', [
+ 'days=', 'occurrences=', 'verbose', 'queues='])
except getopt.GetoptError:
usage()
sys.exit(2)
@@ -151,4 +155,5 @@ if __name__ == '__main__':
sys.exit(2)
queues.append(q)
- create_exclusions(days=days, occurrences=occurrences, verbose=verbose, queues=queues)
+ create_exclusions(days=days, occurrences=occurrences,
+ verbose=verbose, queues=queues)
diff --git a/helpdesk/management/commands/create_queue_permissions.py b/helpdesk/management/commands/create_queue_permissions.py
index fb72f3fe..91f064dc 100644
--- a/helpdesk/management/commands/create_queue_permissions.py
+++ b/helpdesk/management/commands/create_queue_permissions.py
@@ -55,14 +55,17 @@ class Command(BaseCommand):
self.stdout.write("Preparing Queue %s [%s]" % (q.title, q.slug))
if q.permission_name:
- self.stdout.write(" .. already has `permission_name=%s`" % q.permission_name)
+ self.stdout.write(
+ " .. already has `permission_name=%s`" % q.permission_name)
basename = q.permission_name[9:]
else:
basename = q.generate_permission_name()
- self.stdout.write(" .. generated `permission_name=%s`" % q.permission_name)
+ self.stdout.write(
+ " .. generated `permission_name=%s`" % q.permission_name)
q.save()
- self.stdout.write(" .. checking permission codename `%s`" % basename)
+ self.stdout.write(
+ " .. checking permission codename `%s`" % basename)
try:
Permission.objects.create(
diff --git a/helpdesk/management/commands/escalate_tickets.py b/helpdesk/management/commands/escalate_tickets.py
index 07c9a1c4..020a3b78 100644
--- a/helpdesk/management/commands/escalate_tickets.py
+++ b/helpdesk/management/commands/escalate_tickets.py
@@ -62,7 +62,8 @@ class Command(BaseCommand):
def escalate_tickets(queues, verbose):
""" Only include queues with escalation configured """
- queryset = Queue.objects.filter(escalate_days__isnull=False).exclude(escalate_days=0)
+ queryset = Queue.objects.filter(
+ escalate_days__isnull=False).exclude(escalate_days=0)
if queues:
queryset = queryset.filter(slug__in=queues)
@@ -143,7 +144,8 @@ def usage():
if __name__ == '__main__':
try:
- opts, args = getopt.getopt(sys.argv[1:], ['queues=', 'verboseescalation'])
+ opts, args = getopt.getopt(
+ sys.argv[1:], ['queues=', 'verboseescalation'])
except getopt.GetoptError:
usage()
sys.exit(2)
diff --git a/helpdesk/models.py b/helpdesk/models.py
index 5e3eaebb..7ef1b9c9 100644
--- a/helpdesk/models.py
+++ b/helpdesk/models.py
@@ -128,7 +128,8 @@ class Queue(models.Model):
_('Allow Public Submission?'),
blank=True,
default=False,
- help_text=_('Should this queue be listed on the public submission form?'),
+ help_text=_(
+ 'Should this queue be listed on the public submission form?'),
)
allow_email_submission = models.BooleanField(
@@ -180,7 +181,8 @@ class Queue(models.Model):
email_box_type = models.CharField(
_('E-Mail Box Type'),
max_length=5,
- choices=(('pop3', _('POP 3')), ('imap', _('IMAP')), ('local', _('Local Directory'))),
+ choices=(('pop3', _('POP 3')), ('imap', _('IMAP')),
+ ('local', _('Local Directory'))),
blank=True,
null=True,
help_text=_('E-Mail server type for creating tickets automatically '
@@ -262,7 +264,8 @@ class Queue(models.Model):
email_box_interval = models.IntegerField(
_('E-Mail Check Interval'),
- help_text=_('How often do you wish to check this mailbox? (in Minutes)'),
+ help_text=_(
+ 'How often do you wish to check this mailbox? (in Minutes)'),
blank=True,
null=True,
default='5',
@@ -281,7 +284,8 @@ class Queue(models.Model):
choices=(('socks4', _('SOCKS4')), ('socks5', _('SOCKS5'))),
blank=True,
null=True,
- help_text=_('SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'),
+ help_text=_(
+ 'SOCKS4 or SOCKS5 allows you to proxy your connections through a SOCKS server.'),
)
socks_proxy_host = models.GenericIPAddressField(
@@ -295,7 +299,8 @@ class Queue(models.Model):
_('Socks Proxy Port'),
blank=True,
null=True,
- help_text=_('Socks proxy port number. Default: 9150 (default TOR port)'),
+ help_text=_(
+ 'Socks proxy port number. Default: 9150 (default TOR port)'),
)
logging_type = models.CharField(
@@ -356,7 +361,8 @@ class Queue(models.Model):
"""
if not self.email_address:
# must check if given in format "Foo "
- default_email = re.match(".*<(?P.*@*.)>", settings.DEFAULT_FROM_EMAIL)
+ default_email = re.match(
+ ".*<(?P.*@*.)>", settings.DEFAULT_FROM_EMAIL)
if default_email is not None:
# already in the right format, so just include it here
return u'NO QUEUE EMAIL ADDRESS DEFINED %s' % settings.DEFAULT_FROM_EMAIL
@@ -532,7 +538,8 @@ class Ticket(models.Model):
_('On Hold'),
blank=True,
default=False,
- help_text=_('If a ticket is on hold, it will not automatically be escalated.'),
+ help_text=_(
+ 'If a ticket is on hold, it will not automatically be escalated.'),
)
description = models.TextField(
@@ -582,7 +589,8 @@ class Ticket(models.Model):
blank=True,
null=True,
on_delete=models.CASCADE,
- verbose_name=_('Knowledge base item the user was viewing when they created this ticket.'),
+ verbose_name=_(
+ 'Knowledge base item the user was viewing when they created this ticket.'),
)
merged_to = models.ForeignKey(
@@ -648,7 +656,8 @@ class Ticket(models.Model):
def send(role, recipient):
if recipient and recipient not in recipients and role in roles:
template, context = roles[role]
- send_templated_mail(template, context, recipient, sender=self.queue.from_address, **kwargs)
+ send_templated_mail(
+ template, context, recipient, sender=self.queue.from_address, **kwargs)
recipients.add(recipient)
send('submitter', self.submitter_email)
@@ -844,7 +853,8 @@ class Ticket(models.Model):
# Ignore if user has no email address
return
elif not email:
- raise ValueError('You must provide at least one parameter to get the email from')
+ raise ValueError(
+ 'You must provide at least one parameter to get the email from')
# Prepare all emails already into the ticket
ticket_emails = [x.display for x in self.ticketcc_set.all()]
@@ -1280,7 +1290,8 @@ class EmailTemplate(models.Model):
html = models.TextField(
_('HTML'),
- help_text=_('The same context is available here as in plain_text, above.'),
+ help_text=_(
+ 'The same context is available here as in plain_text, above.'),
)
locale = models.CharField(
@@ -1329,7 +1340,8 @@ class KBCategory(models.Model):
blank=True,
null=True,
on_delete=models.CASCADE,
- verbose_name=_('Default queue when creating a ticket after viewing this category.'),
+ verbose_name=_(
+ 'Default queue when creating a ticket after viewing this category.'),
)
public = models.BooleanField(
@@ -1396,7 +1408,8 @@ class KBItem(models.Model):
last_updated = models.DateTimeField(
_('Last Updated'),
- help_text=_('The date on which this question was most recently changed.'),
+ help_text=_(
+ 'The date on which this question was most recently changed.'),
blank=True,
)
@@ -1555,7 +1568,8 @@ class UserSettings(models.Model):
login_view_ticketlist = models.BooleanField(
verbose_name=_('Show Ticket List on Login?'),
- help_text=_('Display the ticket list upon login? Otherwise, the dashboard is shown.'),
+ help_text=_(
+ 'Display the ticket list upon login? Otherwise, the dashboard is shown.'),
default=login_view_ticketlist_default,
)
@@ -1570,13 +1584,15 @@ class UserSettings(models.Model):
email_on_ticket_assign = models.BooleanField(
verbose_name=_('E-mail me when assigned a ticket?'),
- help_text=_('If you are assigned a ticket via the web, do you want to receive an e-mail?'),
+ help_text=_(
+ 'If you are assigned a ticket via the web, do you want to receive an e-mail?'),
default=email_on_ticket_assign_default,
)
tickets_per_page = models.IntegerField(
verbose_name=_('Number of tickets to show per page'),
- help_text=_('How many tickets do you want to see on the Ticket List page?'),
+ help_text=_(
+ 'How many tickets do you want to see on the Ticket List page?'),
default=tickets_per_page_default,
choices=PAGE_SIZES,
)
@@ -1611,7 +1627,8 @@ def create_usersettings(sender, instance, created, **kwargs):
UserSettings.objects.create(user=instance)
-models.signals.post_save.connect(create_usersettings, sender=settings.AUTH_USER_MODEL)
+models.signals.post_save.connect(
+ create_usersettings, sender=settings.AUTH_USER_MODEL)
class IgnoreEmail(models.Model):
@@ -1851,14 +1868,16 @@ class CustomField(models.Model):
ordering = models.IntegerField(
_('Ordering'),
- help_text=_('Lower numbers are displayed first; higher numbers are listed later'),
+ help_text=_(
+ 'Lower numbers are displayed first; higher numbers are listed later'),
blank=True,
null=True,
)
def _choices_as_array(self):
valuebuffer = StringIO(self.list_values)
- choices = [[item.strip(), item.strip()] for item in valuebuffer.readlines()]
+ choices = [[item.strip(), item.strip()]
+ for item in valuebuffer.readlines()]
valuebuffer.close()
return choices
choices_as_array = property(_choices_as_array)
@@ -1912,10 +1931,10 @@ class CustomField(models.Model):
# Prepare attributes for each types
attributes = {
- 'label': self.label,
- 'help_text': self.help_text,
- 'required': self.required,
- }
+ 'label': self.label,
+ 'help_text': self.help_text,
+ 'required': self.required,
+ }
if self.data_type in ('varchar', 'text'):
attributes['max_length'] = self.max_length
if self.data_type == 'text':
diff --git a/helpdesk/query.py b/helpdesk/query.py
index c347c406..14da72a8 100644
--- a/helpdesk/query.py
+++ b/helpdesk/query.py
@@ -103,8 +103,10 @@ def get_query_class():
class __Query__:
def __init__(self, huser, base64query=None, query_params=None):
self.huser = huser
- self.params = query_params if query_params else query_from_base64(base64query)
- self.base64 = base64query if base64query else query_to_base64(query_params)
+ self.params = query_params if query_params else query_from_base64(
+ base64query)
+ self.base64 = base64query if base64query else query_to_base64(
+ query_params)
self.result = None
def get_search_filter_args(self):
@@ -128,7 +130,8 @@ class __Query__:
"""
filter = self.params.get('filtering', {})
filter_or = self.params.get('filtering_or', {})
- queryset = queryset.filter((Q(**filter) | Q(**filter_or)) & self.get_search_filter_args())
+ queryset = queryset.filter(
+ (Q(**filter) | Q(**filter_or)) & self.get_search_filter_args())
sorting = self.params.get('sorting', None)
if sorting:
sortreverse = self.params.get('sortreverse', None)
@@ -191,11 +194,13 @@ class __Query__:
'text': {
'headline': ticket.title + ' - ' + followup.title,
'text': (
- (escape(followup.comment) if followup.comment else _('No text'))
+ (escape(followup.comment)
+ if followup.comment else _('No text'))
+
' %s'
%
- (reverse('helpdesk:view', kwargs={'ticket_id': ticket.pk}), _("View ticket"))
+ (reverse('helpdesk:view', kwargs={
+ 'ticket_id': ticket.pk}), _("View ticket"))
),
},
'group': _('Messages'),
diff --git a/helpdesk/settings.py b/helpdesk/settings.py
index f24335f0..2724c01b 100644
--- a/helpdesk/settings.py
+++ b/helpdesk/settings.py
@@ -46,13 +46,13 @@ HELPDESK_REDIRECT_TO_LOGIN_BY_DEFAULT = getattr(settings,
# Enable the Dependencies field on ticket view
HELPDESK_ENABLE_DEPENDENCIES_ON_TICKET = getattr(settings,
- 'HELPDESK_ENABLE_DEPENDENCIES_ON_TICKET',
- True)
+ 'HELPDESK_ENABLE_DEPENDENCIES_ON_TICKET',
+ True)
# Enable the Time spent on field on ticket view
HELPDESK_ENABLE_TIME_SPENT_ON_TICKET = getattr(settings,
- 'HELPDESK_ENABLE_TIME_SPENT_ON_TICKET',
- True)
+ 'HELPDESK_ENABLE_TIME_SPENT_ON_TICKET',
+ True)
# raises a 404 to anon users. It's like it was invisible
HELPDESK_ANON_ACCESS_RAISES_404 = getattr(settings,
@@ -63,10 +63,13 @@ HELPDESK_ANON_ACCESS_RAISES_404 = getattr(settings,
HELPDESK_KB_ENABLED = getattr(settings, 'HELPDESK_KB_ENABLED', True)
# Disable Timeline on ticket list
-HELPDESK_TICKETS_TIMELINE_ENABLED = getattr(settings, 'HELPDESK_TICKETS_TIMELINE_ENABLED', True)
+HELPDESK_TICKETS_TIMELINE_ENABLED = getattr(
+ settings, 'HELPDESK_TICKETS_TIMELINE_ENABLED', True)
-# show extended navigation by default, to all users, irrespective of staff status?
-HELPDESK_NAVIGATION_ENABLED = getattr(settings, 'HELPDESK_NAVIGATION_ENABLED', False)
+# show extended navigation by default, to all users, irrespective of staff
+# status?
+HELPDESK_NAVIGATION_ENABLED = getattr(
+ settings, 'HELPDESK_NAVIGATION_ENABLED', False)
# use public CDNs to serve jquery and other javascript by default?
# otherwise, use built-in static copy
@@ -84,7 +87,8 @@ HELPDESK_TRANSLATE_TICKET_COMMENTS_LANG = getattr(settings,
["en", "de", "es", "fr", "it", "ru"])
# show link to 'change password' on 'User Settings' page?
-HELPDESK_SHOW_CHANGE_PASSWORD = getattr(settings, 'HELPDESK_SHOW_CHANGE_PASSWORD', False)
+HELPDESK_SHOW_CHANGE_PASSWORD = getattr(
+ settings, 'HELPDESK_SHOW_CHANGE_PASSWORD', False)
# allow user to override default layout for 'followups' - work in progress.
HELPDESK_FOLLOWUP_MOD = getattr(settings, 'HELPDESK_FOLLOWUP_MOD', False)
@@ -96,17 +100,19 @@ HELPDESK_AUTO_SUBSCRIBE_ON_TICKET_RESPONSE = getattr(settings,
# URL schemes that are allowed within links
ALLOWED_URL_SCHEMES = getattr(settings, 'ALLOWED_URL_SCHEMES', (
- 'file', 'ftp', 'ftps', 'http', 'https', 'irc', 'mailto', 'sftp', 'ssh', 'tel', 'telnet', 'tftp', 'vnc', 'xmpp',
+ 'file', 'ftp', 'ftps', 'http', 'https', 'irc', 'mailto', 'sftp', 'ssh', 'tel', 'telnet', 'tftp', 'vnc', 'xmpp',
))
############################
# options for public pages #
############################
# show 'view a ticket' section on public page?
-HELPDESK_VIEW_A_TICKET_PUBLIC = getattr(settings, 'HELPDESK_VIEW_A_TICKET_PUBLIC', True)
+HELPDESK_VIEW_A_TICKET_PUBLIC = getattr(
+ settings, 'HELPDESK_VIEW_A_TICKET_PUBLIC', True)
# show 'submit a ticket' section on public page?
-HELPDESK_SUBMIT_A_TICKET_PUBLIC = getattr(settings, 'HELPDESK_SUBMIT_A_TICKET_PUBLIC', True)
+HELPDESK_SUBMIT_A_TICKET_PUBLIC = getattr(
+ settings, 'HELPDESK_SUBMIT_A_TICKET_PUBLIC', True)
# change that to custom class to have extra fields or validation (like captcha)
HELPDESK_PUBLIC_TICKET_FORM_CLASS = getattr(
@@ -137,8 +143,10 @@ CUSTOMFIELD_DATETIME_FORMAT = f"{CUSTOMFIELD_DATE_FORMAT}T%H:%M"
''' options for update_ticket views '''
# allow non-staff users to interact with tickets?
-# can be True/False or a callable accepting the active user and returning True if they must be considered helpdesk staff
-HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE = getattr(settings, 'HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE', False)
+# can be True/False or a callable accepting the active user and returning
+# True if they must be considered helpdesk staff
+HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE = getattr(
+ settings, 'HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE', False)
if not (HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE in (True, False) or callable(HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE)):
warnings.warn(
"HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE should be set to either True/False or a callable.",
@@ -154,14 +162,18 @@ HELPDESK_SHOW_EDIT_BUTTON_FOLLOW_UP = getattr(settings,
HELPDESK_SHOW_DELETE_BUTTON_SUPERUSER_FOLLOW_UP = getattr(
settings, 'HELPDESK_SHOW_DELETE_BUTTON_SUPERUSER_FOLLOW_UP', False)
-# make all updates public by default? this will hide the 'is this update public' checkbox
-HELPDESK_UPDATE_PUBLIC_DEFAULT = getattr(settings, 'HELPDESK_UPDATE_PUBLIC_DEFAULT', False)
+# make all updates public by default? this will hide the 'is this update
+# public' checkbox
+HELPDESK_UPDATE_PUBLIC_DEFAULT = getattr(
+ settings, 'HELPDESK_UPDATE_PUBLIC_DEFAULT', False)
# only show staff users in ticket owner drop-downs
-HELPDESK_STAFF_ONLY_TICKET_OWNERS = getattr(settings, 'HELPDESK_STAFF_ONLY_TICKET_OWNERS', False)
+HELPDESK_STAFF_ONLY_TICKET_OWNERS = getattr(
+ settings, 'HELPDESK_STAFF_ONLY_TICKET_OWNERS', False)
# only show staff users in ticket cc drop-down
-HELPDESK_STAFF_ONLY_TICKET_CC = getattr(settings, 'HELPDESK_STAFF_ONLY_TICKET_CC', False)
+HELPDESK_STAFF_ONLY_TICKET_CC = getattr(
+ settings, 'HELPDESK_STAFF_ONLY_TICKET_CC', False)
# allow the subject to have a configurable template.
HELPDESK_EMAIL_SUBJECT_TEMPLATE = getattr(
@@ -173,11 +185,13 @@ if HELPDESK_EMAIL_SUBJECT_TEMPLATE.find("ticket.ticket") < 0:
raise ImproperlyConfigured
# default fallback locale when queue locale not found
-HELPDESK_EMAIL_FALLBACK_LOCALE = getattr(settings, 'HELPDESK_EMAIL_FALLBACK_LOCALE', 'en')
+HELPDESK_EMAIL_FALLBACK_LOCALE = getattr(
+ settings, 'HELPDESK_EMAIL_FALLBACK_LOCALE', 'en')
# default maximum email attachment size, in bytes
# only attachments smaller than this size will be sent via email
-HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE = getattr(settings, 'HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE', 512000)
+HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE = getattr(
+ settings, 'HELPDESK_MAX_EMAIL_ATTACHMENT_SIZE', 512000)
########################################
@@ -189,7 +203,8 @@ HELPDESK_CREATE_TICKET_HIDE_ASSIGNED_TO = getattr(
settings, 'HELPDESK_CREATE_TICKET_HIDE_ASSIGNED_TO', False)
# Activate the API endpoint to manage tickets thanks to Django REST Framework
-HELPDESK_ACTIVATE_API_ENDPOINT = getattr(settings, 'HELPDESK_ACTIVATE_API_ENDPOINT', False)
+HELPDESK_ACTIVATE_API_ENDPOINT = getattr(
+ settings, 'HELPDESK_ACTIVATE_API_ENDPOINT', False)
#################
@@ -204,25 +219,32 @@ QUEUE_EMAIL_BOX_USER = getattr(settings, 'QUEUE_EMAIL_BOX_USER', None)
QUEUE_EMAIL_BOX_PASSWORD = getattr(settings, 'QUEUE_EMAIL_BOX_PASSWORD', None)
# only process emails with a valid tracking ID? (throws away all other mail)
-QUEUE_EMAIL_BOX_UPDATE_ONLY = getattr(settings, 'QUEUE_EMAIL_BOX_UPDATE_ONLY', False)
+QUEUE_EMAIL_BOX_UPDATE_ONLY = getattr(
+ settings, 'QUEUE_EMAIL_BOX_UPDATE_ONLY', False)
# only allow users to access queues that they are members of?
HELPDESK_ENABLE_PER_QUEUE_STAFF_PERMISSION = getattr(
settings, 'HELPDESK_ENABLE_PER_QUEUE_STAFF_PERMISSION', False)
# use https in the email links
-HELPDESK_USE_HTTPS_IN_EMAIL_LINK = getattr(settings, 'HELPDESK_USE_HTTPS_IN_EMAIL_LINK', False)
+HELPDESK_USE_HTTPS_IN_EMAIL_LINK = getattr(
+ settings, 'HELPDESK_USE_HTTPS_IN_EMAIL_LINK', False)
-HELPDESK_TEAMS_MODEL = getattr(settings, 'HELPDESK_TEAMS_MODEL', 'pinax_teams.Team')
-HELPDESK_TEAMS_MIGRATION_DEPENDENCIES = getattr(settings, 'HELPDESK_TEAMS_MIGRATION_DEPENDENCIES', [('pinax_teams', '0004_auto_20170511_0856')])
-HELPDESK_KBITEM_TEAM_GETTER = getattr(settings, 'HELPDESK_KBITEM_TEAM_GETTER', lambda kbitem: kbitem.team)
+HELPDESK_TEAMS_MODEL = getattr(
+ settings, 'HELPDESK_TEAMS_MODEL', 'pinax_teams.Team')
+HELPDESK_TEAMS_MIGRATION_DEPENDENCIES = getattr(settings, 'HELPDESK_TEAMS_MIGRATION_DEPENDENCIES', [
+ ('pinax_teams', '0004_auto_20170511_0856')])
+HELPDESK_KBITEM_TEAM_GETTER = getattr(
+ settings, 'HELPDESK_KBITEM_TEAM_GETTER', lambda kbitem: kbitem.team)
# Include all signatures and forwards in the first ticket message if set
-# Useful if you get forwards dropped from them while they are useful part of request
-HELPDESK_FULL_FIRST_MESSAGE_FROM_EMAIL = getattr(settings, 'HELPDESK_FULL_FIRST_MESSAGE_FROM_EMAIL', False)
+# Useful if you get forwards dropped from them while they are useful part
+# of request
+HELPDESK_FULL_FIRST_MESSAGE_FROM_EMAIL = getattr(
+ settings, 'HELPDESK_FULL_FIRST_MESSAGE_FROM_EMAIL', False)
# If set then we always save incoming emails as .eml attachments
# which is quite noisy but very helpful for complicated markup, forwards and so on
# (which gets stripped/corrupted otherwise)
-HELPDESK_ALWAYS_SAVE_INCOMING_EMAIL_MESSAGE = getattr(settings, "HELPDESK_ALWAYS_SAVE_INCOMING_EMAIL_MESSAGE", False)
-
+HELPDESK_ALWAYS_SAVE_INCOMING_EMAIL_MESSAGE = getattr(
+ settings, "HELPDESK_ALWAYS_SAVE_INCOMING_EMAIL_MESSAGE", False)
diff --git a/helpdesk/templated_email.py b/helpdesk/templated_email.py
index 4b20fc83..2fc83973 100644
--- a/helpdesk/templated_email.py
+++ b/helpdesk/templated_email.py
@@ -58,12 +58,15 @@ def send_templated_mail(template_name,
locale = context['queue'].get('locale') or HELPDESK_EMAIL_FALLBACK_LOCALE
try:
- t = EmailTemplate.objects.get(template_name__iexact=template_name, locale=locale)
+ t = EmailTemplate.objects.get(
+ template_name__iexact=template_name, locale=locale)
except EmailTemplate.DoesNotExist:
try:
- t = EmailTemplate.objects.get(template_name__iexact=template_name, locale__isnull=True)
+ t = EmailTemplate.objects.get(
+ template_name__iexact=template_name, locale__isnull=True)
except EmailTemplate.DoesNotExist:
- logger.warning('template "%s" does not exist, no mail sent', template_name)
+ logger.warning(
+ 'template "%s" does not exist, no mail sent', template_name)
return # just ignore if template doesn't exist
subject_part = from_string(
@@ -77,10 +80,12 @@ def send_templated_mail(template_name,
"%s\n\n{%% include '%s' %%}" % (t.plain_text, footer_file)
).render(context)
- email_html_base_file = os.path.join('helpdesk', locale, 'email_html_base.html')
+ email_html_base_file = os.path.join(
+ 'helpdesk', locale, 'email_html_base.html')
# keep new lines in html emails
if 'comment' in context:
- context['comment'] = mark_safe(context['comment'].replace('\r\n', ' '))
+ context['comment'] = mark_safe(
+ context['comment'].replace('\r\n', ' '))
html_part = from_string(
"{%% extends '%s' %%}"
@@ -112,7 +117,8 @@ def send_templated_mail(template_name,
try:
return msg.send()
except SMTPException as e:
- logger.exception('SMTPException raised while sending email to {}'.format(recipients))
+ logger.exception(
+ 'SMTPException raised while sending email to {}'.format(recipients))
if not fail_silently:
raise e
return 0
diff --git a/helpdesk/templatetags/helpdesk_staff.py b/helpdesk/templatetags/helpdesk_staff.py
index ad916264..ab1ea3cf 100644
--- a/helpdesk/templatetags/helpdesk_staff.py
+++ b/helpdesk/templatetags/helpdesk_staff.py
@@ -19,4 +19,5 @@ def helpdesk_staff(user):
try:
return is_helpdesk_staff(user)
except Exception:
- logger.exception("'helpdesk_staff' template tag (django-helpdesk) crashed")
+ logger.exception(
+ "'helpdesk_staff' template tag (django-helpdesk) crashed")
diff --git a/helpdesk/templatetags/helpdesk_util.py b/helpdesk/templatetags/helpdesk_util.py
index 3ad345d4..b096824c 100644
--- a/helpdesk/templatetags/helpdesk_util.py
+++ b/helpdesk/templatetags/helpdesk_util.py
@@ -22,13 +22,16 @@ def datetime_string_format(value):
:return: String - reformatted to default datetime, date, or time string if received in one of the expected formats
"""
try:
- new_value = date_filter(datetime.strptime(value, CUSTOMFIELD_DATETIME_FORMAT), settings.DATETIME_FORMAT)
+ new_value = date_filter(datetime.strptime(
+ value, CUSTOMFIELD_DATETIME_FORMAT), settings.DATETIME_FORMAT)
except (TypeError, ValueError):
try:
- new_value = date_filter(datetime.strptime(value, CUSTOMFIELD_DATE_FORMAT), settings.DATE_FORMAT)
+ new_value = date_filter(datetime.strptime(
+ value, CUSTOMFIELD_DATE_FORMAT), settings.DATE_FORMAT)
except (TypeError, ValueError):
try:
- new_value = date_filter(datetime.strptime(value, CUSTOMFIELD_TIME_FORMAT), settings.TIME_FORMAT)
+ new_value = date_filter(datetime.strptime(
+ value, CUSTOMFIELD_TIME_FORMAT), settings.TIME_FORMAT)
except (TypeError, ValueError):
# If NoneType return empty string, else return original value
new_value = "" if value is None else value
diff --git a/helpdesk/tests/test_api.py b/helpdesk/tests/test_api.py
index 0a0dedfe..b3edf084 100644
--- a/helpdesk/tests/test_api.py
+++ b/helpdesk/tests/test_api.py
@@ -69,23 +69,28 @@ class TicketTest(APITestCase):
self.assertEqual(response.status_code, HTTP_201_CREATED)
created_ticket = Ticket.objects.get()
self.assertEqual(created_ticket.title, 'Test title')
- self.assertEqual(created_ticket.description, 'Test description\nMulti lines')
+ self.assertEqual(created_ticket.description,
+ 'Test description\nMulti lines')
self.assertEqual(created_ticket.submitter_email, 'test@mail.com')
self.assertEqual(created_ticket.priority, 4)
def test_create_api_ticket_with_basic_auth(self):
username = 'admin'
password = 'admin'
- User.objects.create_user(username=username, password=password, is_staff=True)
+ User.objects.create_user(
+ username=username, password=password, is_staff=True)
test_user = User.objects.create_user(username='test')
- merge_ticket = Ticket.objects.create(queue=self.queue, title='merge ticket')
+ merge_ticket = Ticket.objects.create(
+ queue=self.queue, title='merge ticket')
# Generate base64 credentials string
credentials = f"{username}:{password}"
- base64_credentials = base64.b64encode(credentials.encode(HTTP_HEADER_ENCODING)).decode(HTTP_HEADER_ENCODING)
+ base64_credentials = base64.b64encode(credentials.encode(
+ HTTP_HEADER_ENCODING)).decode(HTTP_HEADER_ENCODING)
- self.client.credentials(HTTP_AUTHORIZATION=f"Basic {base64_credentials}")
+ self.client.credentials(
+ HTTP_AUTHORIZATION=f"Basic {base64_credentials}")
response = self.client.post(
'/api/tickets/',
{
@@ -107,21 +112,27 @@ class TicketTest(APITestCase):
created_ticket = Ticket.objects.last()
self.assertEqual(created_ticket.title, 'Title')
self.assertEqual(created_ticket.description, 'Description')
- self.assertIsNone(created_ticket.resolution) # resolution can not be set on creation
+ # resolution can not be set on creation
+ self.assertIsNone(created_ticket.resolution)
self.assertEqual(created_ticket.assigned_to, test_user)
self.assertEqual(created_ticket.submitter_email, 'test@mail.com')
self.assertEqual(created_ticket.priority, 1)
- self.assertFalse(created_ticket.on_hold) # on_hold is False on creation
- self.assertEqual(created_ticket.status, Ticket.OPEN_STATUS) # status is always open on creation
+ # on_hold is False on creation
+ self.assertFalse(created_ticket.on_hold)
+ # status is always open on creation
+ self.assertEqual(created_ticket.status, Ticket.OPEN_STATUS)
self.assertEqual(created_ticket.due_date, self.due_date)
- self.assertIsNone(created_ticket.merged_to) # merged_to can not be set on creation
+ # merged_to can not be set on creation
+ self.assertIsNone(created_ticket.merged_to)
def test_edit_api_ticket(self):
staff_user = User.objects.create_user(username='admin', is_staff=True)
- test_ticket = Ticket.objects.create(queue=self.queue, title='Test ticket')
+ test_ticket = Ticket.objects.create(
+ queue=self.queue, title='Test ticket')
test_user = User.objects.create_user(username='test')
- merge_ticket = Ticket.objects.create(queue=self.queue, title='merge ticket')
+ merge_ticket = Ticket.objects.create(
+ queue=self.queue, title='merge ticket')
self.client.force_authenticate(staff_user)
response = self.client.put(
@@ -156,7 +167,8 @@ class TicketTest(APITestCase):
def test_partial_edit_api_ticket(self):
staff_user = User.objects.create_user(username='admin', is_staff=True)
- test_ticket = Ticket.objects.create(queue=self.queue, title='Test ticket')
+ test_ticket = Ticket.objects.create(
+ queue=self.queue, title='Test ticket')
self.client.force_authenticate(staff_user)
response = self.client.patch(
@@ -172,7 +184,8 @@ class TicketTest(APITestCase):
def test_delete_api_ticket(self):
staff_user = User.objects.create_user(username='admin', is_staff=True)
- test_ticket = Ticket.objects.create(queue=self.queue, title='Test ticket')
+ test_ticket = Ticket.objects.create(
+ queue=self.queue, title='Test ticket')
self.client.force_authenticate(staff_user)
response = self.client.delete('/api/tickets/%d/' % test_ticket.id)
self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)
@@ -195,7 +208,8 @@ class TicketTest(APITestCase):
Blue
Red
Yellow'''
- CustomField.objects.create(name=field_type, label=field_display, data_type=field_type, **extra_data)
+ CustomField.objects.create(
+ name=field_type, label=field_display, data_type=field_type, **extra_data)
staff_user = User.objects.create_user(username='test', is_staff=True)
self.client.force_authenticate(staff_user)
@@ -209,7 +223,8 @@ class TicketTest(APITestCase):
'priority': 4
})
self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
- self.assertEqual(response.data, {'custom_integer': [ErrorDetail(string='This field is required.', code='required')]})
+ self.assertEqual(response.data, {'custom_integer': [ErrorDetail(
+ string='This field is required.', code='required')]})
# Test creation with custom field values
response = self.client.post('/api/tickets/', {
@@ -261,4 +276,3 @@ class TicketTest(APITestCase):
'custom_ipaddress': '127.0.0.1',
'custom_slug': 'test-slug'
})
-
diff --git a/helpdesk/tests/test_attachments.py b/helpdesk/tests/test_attachments.py
index 6c91cb7b..46e7151d 100644
--- a/helpdesk/tests/test_attachments.py
+++ b/helpdesk/tests/test_attachments.py
@@ -47,7 +47,8 @@ class AttachmentIntegrationTests(TestCase):
}
def test_create_pub_ticket_with_attachment(self):
- test_file = SimpleUploadedFile('test_att.txt', b'attached file content', 'text/plain')
+ test_file = SimpleUploadedFile(
+ 'test_att.txt', b'attached file content', 'text/plain')
post_data = self.ticket_data.copy()
post_data.update({
'queue': self.queue_public.id,
@@ -55,17 +56,20 @@ class AttachmentIntegrationTests(TestCase):
})
# Ensure ticket form submits with attachment successfully
- response = self.client.post(reverse('helpdesk:home'), post_data, follow=True)
+ response = self.client.post(
+ reverse('helpdesk:home'), post_data, follow=True)
self.assertContains(response, test_file.name)
# Ensure attachment is available with correct content
- att = models.FollowUpAttachment.objects.get(followup__ticket=response.context['ticket'])
+ att = models.FollowUpAttachment.objects.get(
+ followup__ticket=response.context['ticket'])
with open(os.path.join(MEDIA_DIR, att.file.name)) as file_on_disk:
disk_content = file_on_disk.read()
self.assertEqual(disk_content, 'attached file content')
def test_create_pub_ticket_with_attachment_utf8(self):
- test_file = SimpleUploadedFile('ß°äöü.txt', 'โจ'.encode('utf-8'), 'text/utf-8')
+ test_file = SimpleUploadedFile(
+ 'ß°äöü.txt', 'โจ'.encode('utf-8'), 'text/utf-8')
post_data = self.ticket_data.copy()
post_data.update({
'queue': self.queue_public.id,
@@ -73,11 +77,13 @@ class AttachmentIntegrationTests(TestCase):
})
# Ensure ticket form submits with attachment successfully
- response = self.client.post(reverse('helpdesk:home'), post_data, follow=True)
+ response = self.client.post(
+ reverse('helpdesk:home'), post_data, follow=True)
self.assertContains(response, test_file.name)
# Ensure attachment is available with correct content
- att = models.FollowUpAttachment.objects.get(followup__ticket=response.context['ticket'])
+ att = models.FollowUpAttachment.objects.get(
+ followup__ticket=response.context['ticket'])
with open(os.path.join(MEDIA_DIR, att.file.name)) as file_on_disk:
disk_content = smart_str(file_on_disk.read(), 'utf-8')
self.assertEqual(disk_content, 'โจ')
@@ -105,7 +111,8 @@ class AttachmentUnitTests(TestCase):
@skip("Rework with model relocation")
def test_unicode_attachment_filename(self, mock_att_save, mock_queue_save, mock_ticket_save, mock_follow_up_save):
""" check utf-8 data is parsed correctly """
- filename, fileobj = lib.process_attachments(self.follow_up, [self.test_file])[0]
+ filename, fileobj = lib.process_attachments(
+ self.follow_up, [self.test_file])[0]
mock_att_save.assert_called_with(
file=self.test_file,
filename=self.file_attrs['filename'],
@@ -154,8 +161,10 @@ class AttachmentUnitTests(TestCase):
@override_settings(MEDIA_ROOT=MEDIA_DIR)
def test_unicode_filename_to_filesystem(self, mock_att_save, mock_queue_save, mock_ticket_save, mock_follow_up_save):
""" don't mock saving to filesystem to test file renames caused by storage layer """
- filename, fileobj = lib.process_attachments(self.follow_up, [self.test_file])[0]
- # Attachment object was zeroth positional arg (i.e. self) of att.save call
+ filename, fileobj = lib.process_attachments(
+ self.follow_up, [self.test_file])[0]
+ # Attachment object was zeroth positional arg (i.e. self) of att.save
+ # call
attachment_obj = mock_att_save.return_value
mock_att_save.assert_called_once_with(attachment_obj)
diff --git a/helpdesk/tests/test_get_email.py b/helpdesk/tests/test_get_email.py
index 07df3348..f1cf010e 100644
--- a/helpdesk/tests/test_get_email.py
+++ b/helpdesk/tests/test_get_email.py
@@ -37,7 +37,8 @@ class GetEmailCommonTests(TestCase):
# tests correct syntax for command line option
def test_get_email_quiet_option(self):
"""Test quiet option is properly propagated"""
- # Test get_email with quiet set to True and also False, and verify handle receives quiet option set properly
+ # Test get_email with quiet set to True and also False, and verify
+ # handle receives quiet option set properly
for quiet_test_value in [True, False]:
with mock.patch.object(Command, 'handle', return_value=None) as mocked_handle:
call_command('get_email', quiet=quiet_test_value)
@@ -52,7 +53,8 @@ class GetEmailCommonTests(TestCase):
"""
with open(os.path.join(THIS_DIR, "test_files/blank-body-with-attachment.eml")) as fd:
test_email = fd.read()
- ticket = helpdesk.email.object_from_message(test_email, self.queue_public, self.logger)
+ ticket = helpdesk.email.object_from_message(
+ test_email, self.queue_public, self.logger)
# title got truncated because of max_lengh of the model.title field
assert ticket.title == (
@@ -68,16 +70,19 @@ class GetEmailCommonTests(TestCase):
"""
with open(os.path.join(THIS_DIR, "test_files/quoted_printable.eml")) as fd:
test_email = fd.read()
- ticket = helpdesk.email.object_from_message(test_email, self.queue_public, self.logger)
+ ticket = helpdesk.email.object_from_message(
+ test_email, self.queue_public, self.logger)
self.assertEqual(ticket.title, "Český test")
- self.assertEqual(ticket.description, "Tohle je test českých písmen odeslaných z gmailu.")
+ self.assertEqual(ticket.description,
+ "Tohle je test českých písmen odeslaných z gmailu.")
followups = FollowUp.objects.filter(ticket=ticket)
self.assertEqual(len(followups), 1)
followup = followups[0]
attachments = FollowUpAttachment.objects.filter(followup=followup)
self.assertEqual(len(attachments), 1)
attachment = attachments[0]
- self.assertIn('