Skip to content

Commit

Permalink
tests passing
Browse files Browse the repository at this point in the history
  • Loading branch information
jparker165 committed Jun 11, 2014
1 parent 6d9c45e commit 890fd04
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 37 deletions.
14 changes: 11 additions & 3 deletions backend/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,26 @@ def Subscribe(self, **kwargs):


class ProdMailSender(handlers.MailSender):
def Send(self, to, subject, text_body, html_body):
deferred.defer(_send_mail, to, subject, text_body, html_body)
def __init__(self, defer=True):
self.defer = defer

def Send(self, to, subject, text_body, html_body, reply_to=None):
if self.defer:
deferred.defer(_send_mail, to, subject, text_body, html_body)
else:
_send_mail(to, subject, text_body, html_body, reply_to)


def _send_mail(to, subject, text_body, html_body):
def _send_mail(to, subject, text_body, html_body, reply_to=None):
"""Deferred email task"""
sender = ('MayOne no-reply <noreply@%s.appspotmail.com>' %
model.Config.get().app_name)
message = mail.EmailMessage(sender=sender, subject=subject)
message.to = to
message.body = text_body
message.html = html_body
if reply_to:
message.reply_to = reply_to
message.send()


Expand Down
38 changes: 23 additions & 15 deletions backend/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import templates
import util


# Immutable environment with both configuration variables, and backends to be
# mocked out in tests.
Environment = namedtuple(
Expand All @@ -38,6 +39,8 @@
'mail_sender',
])



class PaymentError(Exception):
pass

Expand Down Expand Up @@ -214,9 +217,9 @@ class SubscribeHandler(webapp2.RequestHandler):

def post(self):
env = self.app.config['env']

logging.info('body: %s' % self.request.body)

email_input = cgi.escape(self.request.get('email'))
if len(email_input) == 0:
logging.warning("Bad Request: required field (email) missing.")
Expand Down Expand Up @@ -250,7 +253,7 @@ def post(self):
rootstrikers_input = 'Yes'
elif rootstrikers_input=='off':
rootstrikers_input = ''

source_input = cgi.escape(self.request.get('source'))
if len(source_input) == 0:
source_input = 'subscribe'
Expand Down Expand Up @@ -369,34 +372,39 @@ def get(self):
def options(self):
util.EnableCors(self)

class ThankYouHandler(webapp2.RequestHandler):
class ThankTeamHandler(webapp2.RequestHandler):
"""
"""
def post(self):
env = self.app.config['env']
util.EnableCors(self)
for field in ['team', 'reply_to', 'subject', 'message_body', 'new_members']:

for field in ['team', 'team_leader_email', 'reply_to', 'subject', 'message_body', 'new_members']:
if not field in self.request.POST:
msg = "Bad Request: required field %s missing." % field
logging.warning(msg)
self.error(400)
self.response.write(msg)
return

pledges = model.Pledge.all().filter('email =',self.request.POST['team'])
pledges = model.Pledge.all().filter(
'team =',self.request.POST['team']).filter(
'email !=', self.request.POST['team_leader_email'])

for pledge in pledges:
if self.request.POST['new_members'] and pledge.thank_you_sent_at:
continue

replyto = '%s <%s>' % (ascii_name, ascii_email)
message = mail.EmailMessage(sender=('MayOne no-reply <noreply@%s.appspotmail.com>' %
model.Config.get().app_name),
reply_to=self.request.POST["reply_to"],
subject=self.request.POST["subject"])
message.to = pledge.email
message.body = self.request.POST["message_body"]
message.send()
env.mail_sender.Send(to=pledge.email,
subject=self.request.POST['subject'],
text_body=self.request.POST['message_body'],
html_body=self.request.POST['message_body'],
reply_to=self.request.POST['reply_to'])

pledge.thank_you_sent_at = datetime.datetime.now()
pledge.put()

# TODO: respond back with the number of messages sent

def options(self):
util.EnableCors(self)
Expand All @@ -407,6 +415,6 @@ def options(self):
('/receipt/(.+)', ReceiptHandler),
('/r/payment_config', PaymentConfigHandler),
('/r/total', TotalHandler),
('/r/thank', ThankYouHandler),
('/r/thank', ThankTeamHandler),
('/r/subscribe', SubscribeHandler),
]
75 changes: 56 additions & 19 deletions unittests/test_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import datetime

from google.appengine.api import mail_stub
from google.appengine.ext import db
from google.appengine.ext import testbed
import mox
Expand All @@ -10,6 +11,7 @@

import handlers
import model
import env


class BaseTest(unittest.TestCase):
Expand All @@ -20,11 +22,16 @@ def setUp(self):
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()

self.testbed.init_mail_stub()
self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)

self.mockery = mox.Mox()
self.stripe = self.mockery.CreateMock(handlers.StripeBackend)
self.mailing_list_subscriber = self.mockery.CreateMock(
handlers.MailingListSubscriber)
self.mail_sender = self.mockery.CreateMock(handlers.MailSender)
self.mail_sender = env.ProdMailSender(defer=False)

# self.mockery.CreateMock(env.ProdMailSender)

self.env = handlers.Environment(
app_name='unittest',
Expand Down Expand Up @@ -58,6 +65,7 @@ def setUp(self):
amountCents=4200,
pledgeType='CONDITIONAL',
team='rocket',
thank_you_sent_at=None,
payment=dict(
STRIPE=dict(
token='tok_1234',
Expand Down Expand Up @@ -101,9 +109,10 @@ def expectSubscribe(self):
source='pledge', nonce=mox.Regex('.*'))

def expectMailSend(self):
self.mail_sender.Send(to=mox.IsA(str), subject=mox.IsA(str),
text_body=mox.IsA(str),
html_body=mox.IsA(str))
# i don't think was doing what was expected
pass



def makeDefaultRequest(self):
self.expectStripe()
Expand All @@ -113,6 +122,17 @@ def makeDefaultRequest(self):

return self.app.post_json('/r/pledge', self.pledge)

def testMailOnCreatePledge(self):
self.expectStripe()
self.expectSubscribe()
self.mockery.ReplayAll()
self.app.post_json('/r/pledge', self.pledge)
messages = self.mail_stub.get_sent_messages(to=self.pledge["email"])
self.assertEquals(1, len(messages))
self.assertEquals(self.pledge["email"], messages[0].to)
self.assertTrue('MayOne no-reply' in messages[0].sender)
self.assertEquals('Thank you for your pledge', messages[0].subject)

def testBadJson(self):
self.app.post('/r/pledge', '{foo', status=400)

Expand Down Expand Up @@ -341,21 +361,38 @@ def testTeamTotal(self):
teamTotalCents=8400,
), resp.json)

def testThankYou(self):
form_data = {'team': 'rocket', 'reply_to': 'the reply to',
'subject': 'the email subject', 'message_body': 'the message body',
'new_members': False}
resp = self.app.post('/r/thank', form_data)
print resp
# self.assertEquals(1,2)

# resp = self.app.get('/r/contributors?team=rocket')
# self.assertEquals(dict(
# totalCents=self.balance_baseline + 2 * 4200,
# team='rocket',
# teamPledges=2,
# teamTotalCents=8400,
# ), resp.json)
def testThankTeam(self):
self.makeDefaultRequest()

post_data = {'team': 'rocket', 'team_leader_email': self.pledge["email"],
'reply_to': 'the reply to', 'subject': 'the email subject',
'message_body': 'the message body', 'new_members': False}

# fails with a 400 error if the post request is missing any keys
with self.assertRaises(Exception):
resp = self.app.post('/r/thank', {})

# pledge doesn't get the email if they are the team leader
resp = self.app.post('/r/thank', post_data)
messages = self.mail_stub.get_sent_messages(to=self.pledge["email"])
self.assertEquals(len(messages), 1)

# this is the happy path
self.assertEquals(model.Pledge.all()[0].thank_you_sent_at, None)
post_data['team_leader_email'] = 'bob.loblaw@gmail.com'
resp = self.app.post('/r/thank', post_data)
messages = self.mail_stub.get_sent_messages(to=self.pledge["email"])
self.assertEquals(len(messages), 2)
self.assertEquals(messages[1].reply_to, post_data["reply_to"])
self.assertEquals(messages[1].subject, post_data["subject"])
self.assertEquals(type(model.Pledge.all()[0].thank_you_sent_at), datetime.datetime)

# make sure it isn't sent a message again when new_member is set to true
post_data['new_members'] = True
resp = self.app.post('/r/thank', post_data)
messages = self.mail_stub.get_sent_messages(to=self.pledge["email"])
self.assertEquals(len(messages), 2)


def testUserInfoNotFound(self):
resp = self.app.get('/user-info/nouserhere', status=404)
Expand Down

0 comments on commit 890fd04

Please sign in to comment.