【发布时间】:2015-10-23 20:37:30
【问题描述】:
我试图在我的 Flask 视图函数中模拟 SendGrid 方法,以便它在测试期间不会发送电子邮件。当我运行以下代码时,我收到错误“ImportError:没有名为 sg 的模块”。如何正确配置 'sg' 方法以便在测试中找到它?
# test_helpers.py
from unittest import TestCase
from views import app
class PhotogTestCase(TestCase):
def setUp(self):
app.config['WTF_CSRF_ENABLED'] = False
app.config['TESTING'] = True
self.app = app
self.client = app.test_client()
# test_views.py
import mock
from test_helpers import PhotogTestCase
import sendgrid
class TestAddUser(PhotogTestCase):
sg = sendgrid.SendGridClient(app.config['SENDGRID_API_KEY'])
@mock.patch('sg.send')
def test_add_user_page_loads(self, mocked_send):
mocked_send.return_value = None # Do nothing on send
resp = self.client.post('/add_user', data={
'email': 'joe@hotmail.com'
}, follow_redirects=True)
assert 'Wow' in resp.data
# views.py
import sendgrid
from itsdangerous import URLSafeTimedSerializer
from flask import Flask, redirect, render_template, \
request, url_for, flash, current_app, abort
from flask.ext.stormpath import login_required
from forms import RegistrationForm, AddContactForm, \
AddUserForm
@app.route('/add_user', methods=['GET', 'POST'])
@login_required
def add_user():
"""
Send invite email with token to invited user
"""
form = AddUserForm()
if form.validate_on_submit():
# token serializer
ts = URLSafeTimedSerializer(app.config['SECRET_KEY'])
email = request.form['email']
tenant_id = user.custom_data['tenant_id']
# create token containing email and tenant_id
token = ts.dumps([email, tenant_id])
# create url with token, e.g. /add_user_confirm/asdf-asd-fasdf
confirm_url = url_for(
'add_user_confirm',
token=token,
_external=True)
try:
# sendgrid setup
sg = sendgrid.SendGridClient(
app.config['SENDGRID_API_KEY'],
raise_errors=True
)
# email setup
message = sendgrid.Mail(
to=request.form['email'],
subject='Account Invitation',
html='You have been invited to set up an account on PhotogApp. Click here: ' + confirm_url,
from_email='support@photogapp.com'
)
# send email
status, msg = sg.send(message)
flash('Invite sent successfully.')
return render_template('dashboard/add_user_complete.html')
return render_template('dashboard/add_user.html', form=form)
【问题讨论】:
标签: python unit-testing flask mocking