Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

string composition from form fields #79

Merged
merged 6 commits into from
Aug 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import logging
import logging.handlers
import conf
import time


class Forms(object):
Expand Down Expand Up @@ -111,7 +112,9 @@ def are_fields_invalid(self, request):
self.error = 'Invalid Name'
error_number = 2
invalid_option = 'name'
elif not (is_hidden_field_empty(request) and is_valid_token(request)):
elif (not (is_hidden_field_empty(request) and
is_valid_token(request)) or
not (is_valid_fields_to_join(request))):
self.error = 'Improper Form Submission'
error_number = 3
invalid_option = 'name'
Expand Down Expand Up @@ -346,6 +349,18 @@ def is_valid_token(request):
return False


def is_valid_fields_to_join(request):
"""
Make sure that if request has 'fields_to_join' field, that the specified
fields to join exist
"""
if 'fields_to_join' in request.form:
for field in request.form['fields_to_join'].split(','):
if field not in request.form and field != 'date':
return False
return True


def create_error_url(error_number, message, request):
"""Construct error message and append to redirect url"""
values = [('error', str(error_number)), ('message', message)]
Expand All @@ -362,7 +377,8 @@ def format_message(msg):
"""Formats a dict (msg) into a nice-looking string"""
# Ignore these fields when writing to formatted message
hidden_fields = ['redirect', 'last_name', 'token', 'op',
'name', 'email', 'mail_subject', 'send_to']
'name', 'email', 'mail_subject', 'send_to',
'fields_to_join']
# Contact information goes at the top
f_message = ("Contact:\n--------\n"
"NAME: {0}\nEMAIL: {1}\n"
Expand All @@ -374,6 +390,11 @@ def format_message(msg):
if key not in hidden_fields:
f_message += ('{0}:\n\n{1}\n\n'.format(convert_key_to_title(key),
msg[key]))
if 'fields_to_join' in msg:
# handle fields_to_join
fields_to_join = msg['fields_to_join'].split(',') # list of fields
f_message += (
':'.join(str(int(time.time())) if field == 'date' else msg[field] for field in fields_to_join) + '\n\n')
return f_message


Expand Down Expand Up @@ -453,6 +474,7 @@ def send_email(msg, subject, send_to_email='default',
msg_send['Subject'] = subject
msg_send['To'] = conf.EMAIL[send_to_email]

# print(msg_send)
# Sets up a temporary mail server to send from
smtp = smtplib.SMTP(conf.SMTP_HOST)
# Attempts to send the mail to EMAIL, with the message formatted as a string
Expand Down
1 change: 1 addition & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ <h2>Test Form</h2>
<input type="hidden" name="token" value="15674hsda//*q23%^13jnxccv3ds54sa4g4sa532323!OoRdsfISDIdks38*(dsfjk)aS" />
<input type="hidden" name="redirect" value="http://www.osuosl.org" />
<input type="hidden" id="edit-submit-mail-sub" name="mail_subject" value="FORM: New Hosting Request" class="form-text" />
<input type="hidden" name="fields_to_join" value="email,name" />
<input type="submit" name="op" value="Submit" />
</form>
</body>
57 changes: 57 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from mock import Mock, patch
from email.mime.text import MIMEText
import conf
import time
import request_handler as handler


Expand Down Expand Up @@ -213,6 +214,32 @@ def test_validations_invalid_token(self, mock_validate_email):
app.on_form_page(req)
self.assertEqual(app.error, 'Improper Form Submission')

@patch('request_handler.validate_email')
def test_validations_invalid_fields_to_join(self, mock_validate_email):
"""
Tests the form validation with an invalid 'fields_to_join' field.

on_form_page checks for valid fields in submitted form and
returns an error message if an invalid field is found.
An invalid token causes the 'Improper Form Submission' error.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'last_name': '',
'token': conf.TOKEN,
'redirect': 'http://www.example.com',
'fields_to_join': 'name,missing,email'})
env = builder.get_environ()
req = Request(env)
# Mock external validate_email so returns true in Travis
mock_validate_email.return_value = True
app = handler.create_app()
# Mock sendmail function so it doesn't send an actual email
smtplib.SMTP = Mock('smtplib.SMTP')
app.on_form_page(req)
self.assertEqual(app.error, 'Improper Form Submission')

@patch('request_handler.validate_email')
def test_is_valid_email_with_valid(self, mock_validate_email):
"""
Expand Down Expand Up @@ -1030,5 +1057,35 @@ def test_server_status_view_responds_with_HTTP_400_on_non_GET_request(self):

self.assertEqual(resp.status_code, 400)
self.assertEquals(app.error, None)

def test_string_comp_from_fields_to_join(self):
"""
Tests that values can be pulled from form fields and composed into a
string to be included in the body of the email.
"""
builder = EnvironBuilder(method='POST',
data={'name': 'Valid Guy',
'email': '[email protected]',
'some_field': "This is some info.",
'redirect': 'http://www.example.com',
'last_name': '',
'token': conf.TOKEN,
'fields_to_join': 'name,email,date,some_field'})
env = builder.get_environ()
req = Request(env)
target_message = ("Contact:\n"
"--------\n"
"NAME: Valid Guy\n"
"EMAIL: [email protected]\n\n"
"Information:\n"
"------------\n"
"Some Field:\n\n"
"This is some info.\n\n"
"Valid Guy:[email protected]:%s:This is some info.\n\n" % str(int(time.time())))
message = handler.create_msg(req)
formatted_message = handler.format_message(message)
self.assertEqual(formatted_message, target_message)


if __name__ == '__main__':
unittest.main()