我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用django.core.mail.outbox()。
def test_send_set_password_email(staff_user): site = Site.objects.get_current() ctx = {'protocol': 'http', 'domain': site.domain, 'site_name': site.name, 'uid': urlsafe_base64_encode(force_bytes(staff_user.pk)), 'token': default_token_generator.make_token(staff_user)} send_templated_mail(template_name='dashboard/staff/set_password', from_email=DEFAULT_FROM_EMAIL, recipient_list=[staff_user.email], context=ctx) assert len(mail.outbox) == 1 generated_link = ('http://%s/account/password/reset/%s/%s/' % (ctx['domain'], ctx['uid'].decode('utf-8'), ctx['token'])) sended_message = mail.outbox[0].body assert generated_link in sended_message
def setup_test_environment(): """Perform any global pre-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem email backend. - Setting the active locale to match the LANGUAGE_CODE setting. """ Template._original_render = Template._render Template._render = instrumented_test_render # Storing previous values in the settings module itself is problematic. # Store them in arbitrary (but related) modules instead. See #20636. mail._original_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' request._original_allowed_hosts = settings.ALLOWED_HOSTS settings.ALLOWED_HOSTS = ['*'] mail.outbox = [] deactivate()
def test_messaging_as_attendee(self): self.presentation.proposal.registrants.add(self.user) self.login() rsp = self.client.get(self.tutorial_url) self.assertIn('id="messages"', rsp.content) # We can display the page prompting for a message to send them url = reverse( 'tutorial_message', kwargs={'pk': self.presentation.proposal.pk}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) # "Send" a message to those two applications test_message = 'One if by land and two if by sea' data = {'message': test_message, } rsp = self.client.post(url, data=data) self.assertEqual(302, rsp.status_code) msg = PyConTutorialMessage.objects.get( user=self.user, tutorial=self.presentation.proposal) self.assertEqual(test_message, msg.message) # For each message, it's visible, so it should have been emailed to # both the other attendees and speakers. Total: 1 message for this case self.assertEqual(1, len(mail.outbox))
def test_valid_form(self): response = self.client.post( '/contact/', self.data, follow=True ) self.assertEqual(200, response.status_code ) self.assertEqual(1, len(mail.outbox) ) self.assertEqual(mail.outbox[0].subject, str(' '.join(('Contact Form:', self.data['first_name'], self.data['last_name'], ))) )
def test_bad_email_header(self): form = contact_forms.ContactForm(self.data) self.assertTrue( form.is_valid() ) ret = form.send_email() self.assertIsInstance(ret, contact_forms.HttpResponse ) self.assertEqual(200, ret.status_code ) self.assertRegex(ret.content.decode(), r'BadHeaderError' ) self.assertEqual(0, len(mail.outbox) )
def testCanPostReverseDomains(self): name = '0.8.0.0.0.1.c.a.2.4.6.0.c.e.e.d.4.4.0.1.a.0.1.0.8.f.4.0.1.0.a.2.ip6.arpa' httpretty.enable() httpretty.register_uri(httpretty.POST, settings.NSLORD_PDNS_API + '/zones', status=201) httpretty.register_uri(httpretty.GET, settings.NSLORD_PDNS_API + '/zones/' + name + '.', body='{"rrsets": []}', content_type="application/json") httpretty.register_uri(httpretty.GET, settings.NSLORD_PDNS_API + '/zones/' + name + './cryptokeys', body='[]', content_type="application/json") url = reverse('domain-list') data = {'name': name} response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(len(mail.outbox), 0)
def test_token_email(self): outboxlen = len(mail.outbox) url = reverse('register') data = { 'email': utils.generateRandomString() + '@test-same-email.desec.io', 'password': utils.generateRandomString(size=12), 'dyn': False, } response = self.client.post(url, data, REMOTE_ADDR=utils.generateRandomIPv4Address()) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(len(mail.outbox), outboxlen + 1) user = models.User.objects.get(email=data['email']) self.assertTrue(user.get_token() in mail.outbox[-1].body)
def test_post_authenticated_success(self): user = self.signup() data = { "password_current": "bar", "password_new": "new-bar", "password_new_confirm": "new-bar", } response = self.client.post(reverse("account_password"), data) self.assertRedirects( response, reverse(settings.ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL), fetch_redirect_response=False ) updated_user = User.objects.get(username=user.username) self.assertNotEqual(user.password, updated_user.password) self.assertEqual(len(mail.outbox), 1)
def test_issue_survey(self): """ Test survey issuing TODO: test multiple users Returns the number of users a survey was sent to. TODO: issue_survey can probably return something with more info in the future """ with mock.patch.object(Report, 'can_issue_daily', return_value=True): result = issue_surveys.apply().get() self.assertEqual(result, 1, 'task should generate at least one survey') self.assertEquals(len(mail.outbox), 1, 'there should be nice email sent to user') message = mail.outbox[0] html_body = message.alternatives[0][0] self.assertIn('Boomerang call from team', message.subject, 'title contains positive message') self.assertIn(str(Survey.objects.get().pk), message.body, 'body contains link with survey pk') self.assertIn(str(Survey.objects.get().pk), html_body, 'also html body') for question in self.report.question_set.active().values_list('text', flat=True): self.assertIn(question, html_body, 'survey contains questions')
def test_issue_summaries(self): with mock.patch.object(Report, 'can_issue_daily', return_value=True): result = issue_surveys.apply().get() self.assertEqual(result, 1, 'task should generate at least one survey') survey = Survey.objects.get() survey.completed = now() with mock.patch.object(Report, 'can_issue_summary', return_value=True): issue_summaries.apply() self.assertEquals(len(mail.outbox), 2, 'there should be two emails sent to user') self.assertIsNotNone(Report.objects.get().dailyreport_set.get().summary_submitted) message = mail.outbox[1] self.assertIn('Boomerang summary report', message.subject, 'title contains positive message') html_body = message.alternatives[0][0] for question in self.report.question_set.active().values_list('text', flat=True): self.assertIn(question, html_body, 'report contains questions') self.assertIn('no answer', html_body, "and doesn't contain answers but contains this string at least once")
def test_attachment_executed(self): def handler(instance, **kwarg): # get post on landing page event if instance.target_tracker.key != TRACKER_ATTACHMENT_EXECUTED: # ignore other target event return self.assertEqual(instance.ip, '127.0.0.1') self.assertEqual(instance.user_agent, 'Outlook') raise SuccessException() post_save.connect(handler, sender=TrackerInfos) # call tracker self.send_campaign() attachment = json.loads(mail.outbox[-1].attachments[0][1].decode()) tracker_url = attachment['tracker_url'] # test if handler has call with self.assertRaises(SuccessException): self.client.defaults['HTTP_USER_AGENT'] = 'Outlook' self.client.get(tracker_url) # clean self.assertTrue(post_save.disconnect(handler, sender=TrackerInfos))
def test_email_open(self): def handler(instance, **kwarg): # get email open event if instance.target_tracker.key != TRACKER_EMAIL_OPEN: # ignore other target event return self.assertEqual(instance.ip, '127.0.0.1') self.assertEqual(instance.user_agent, 'Outlook') raise SuccessException() post_save.connect(handler, sender=TrackerInfos) # call tracker self.send_campaign() mail_html = mail.outbox[-1].alternatives[0][0] tracker_url = mail_html.split('src="')[-1].split('"')[0] # test if handler has call with self.assertRaises(SuccessException): self.client.defaults['HTTP_USER_AGENT'] = 'Outlook' self.client.get(tracker_url) # clean self.assertTrue(post_save.disconnect(handler, sender=TrackerInfos))
def test_alerts_with_old_logins_and_unopened_apps(self): user1 = UserFactory(last_login=old_login_date) user2 = UserFactory(last_login=old_login_date - timedelta(days=2)) user3 = UserFactory(last_login=None) UserProfileFactory(user=user1, organization=self.org) UserProfileFactory(user=user2, organization=self.org) UserProfileFactory(user=user3, organization=self.org) self.run_command() self.assertEqual(1, len(mail.outbox)) email = mail.outbox[0] expected_subject = "Inactive organization on localhost:8000" expected_body = "Alameda County Pubdef has not logged in since " \ "{} and has 1 unopened applications".format( old_login_date.strftime("%a %b %-d %Y")) self.assertEqual(expected_subject, email.subject) self.assertIn(expected_body, email.body)
def test_can_leave_organization(self): """ Test it's possible to leave the organization """ mail.outbox = [] self.assertTrue(len(mail.outbox) == 0) self.assertTrue(self.user2 in self.organization.members.all()) self.client.force_authenticate(self.user2) response = self.client.post(reverse("organization-leave", ["test-organization"]), {}, format="json") self.assertTrue(response.status_code == 200) self.assertTrue(response.data["detail"] == "You've left the organization.") self.assertTrue(self.user2 not in self.organization.members.all()) subjects = [x.subject for x in mail.outbox] if is_email_enabled("default", "userLeft-toUser"): # pragma: no cover self.assertTrue(get_email_subject("default", "userLeft-toUser", "You have left an organization")) if is_email_enabled("default", "userLeft-toOwner"): # pragma: no cover self.assertTrue(get_email_subject("default", "userLeft-toOwner", "An user has left an organization you own"))
def test_wizard_logged_in_user(self, event, client, question, user): submission_type = SubmissionType.objects.filter(event=event).first().pk answer_data = {f'questions-question_{question.pk}': '42', } client.force_login(user) response, current_url = self.perform_init_wizard(client) response, current_url = self.perform_info_wizard(client, response, current_url, submission_type=submission_type) response, current_url = self.perform_question_wizard(client, response, current_url, answer_data, next='profile') response, current_url = self.perform_profile_form(client, response, current_url) doc = bs4.BeautifulSoup(response.rendered_content, "lxml") assert doc.select('.alert-success') assert doc.select('.user-row') sub = Submission.objects.last() assert sub.title == 'Submission title' answ = sub.answers.first() assert answ.question == question assert answ.answer == '42' s_user = sub.speakers.first() assert s_user.pk == user.pk assert s_user.nick == 'testuser' assert s_user.name == 'Jane Doe' assert s_user.profiles.get(event=event).biography == 'l337 hax0r' assert len(djmail.outbox) == 1
def test_wizard_logged_in_user_no_questions(self, event, client, user): submission_type = SubmissionType.objects.filter(event=event).first().pk client.force_login(user) response, current_url = self.perform_init_wizard(client) response, current_url = self.perform_info_wizard(client, response, current_url, submission_type=submission_type, next='profile') response, current_url = self.perform_profile_form(client, response, current_url) doc = bs4.BeautifulSoup(response.rendered_content, "lxml") assert doc.select('.alert-success') assert doc.select('.user-row') sub = Submission.objects.last() assert sub.title == 'Submission title' assert not sub.answers.exists() s_user = sub.speakers.first() assert s_user.pk == user.pk assert s_user.nick == 'testuser' assert s_user.name == 'Jane Doe' assert s_user.profiles.get(event=event).biography == 'l337 hax0r' assert len(djmail.outbox) == 1
def test_reviews_create(self): url = reverse('pages:review_create') response = self.client.post(url, { 'text': 'test_text', 'contacts': 'client contacts' }) self.assertContains( response, 'message' ) review = Review.objects.filter( text__startswith='test_text', text__contains='client contacts', is_enabled=False ) self.assertGreater(review.count(), 0) self.assertEqual(mail.outbox[0].subject, settings.EMAIL_SUBJECT_PREFIX + 'New client review.')
def test_event_notifications_task(self): """ Test event_notifications_task """ event_notifications_task.delay() self.assertEqual(len(mail.outbox), 2) event = Event.objects.first() self.assertEqual( mail.outbox[0].subject, settings.EMAIL_SUBJECT_PREFIX + 'Upcoming event - ' + event.title) self.assertEqual(mail.outbox[1].subject, settings.EMAIL_SUBJECT_PREFIX + '??????????? ? ??????????? ??????????') self.assertNotEqual(event.notified_at, None) begin = arrow.get(event.begin).to(settings.TIME_ZONE).datetime sms = Sms.objects.first() self.assertTrue(begin.strftime('%d.%m.%Y %H:%M') in sms.text)
def _test_signup_email_verified_externally(self, signup_email, verified_email): username = 'johndoe' request = RequestFactory().post(reverse('account_signup'), {'username': username, 'email': signup_email, 'password1': 'johndoe', 'password2': 'johndoe'}) # Fake stash_verified_email from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) request.user = AnonymousUser() request.session['account_verified_email'] = verified_email from .views import signup resp = signup(request) self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], get_adapter().get_login_redirect_url(request)) self.assertEqual(len(mail.outbox), 0) return get_user_model().objects.get(username=username)
def __init__(self, *args, **kwargs): super(EmailBackend, self).__init__(*args, **kwargs) if not hasattr(mail, 'outbox'): mail.outbox = []
def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() msg_count += 1 mail.outbox.extend(messages) return msg_count
def _pre_setup(self): """Performs any pre-test setup. This includes: * Creating a test client. * If the class has a 'urls' attribute, replace ROOT_URLCONF with it. * Clearing the mail test outbox. """ self.client = self.client_class() self._urlconf_setup() mail.outbox = []
def test_post_should_send_email_to_user_with_password_rest_link(self): user = create_user() data = { 'email': user.email, } request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) self.assert_emails_in_mailbox(1) self.assert_email_exists(to=[user.email]) site = djoser.utils.get_current_site(request) self.assertIn(site.domain, mail.outbox[0].body) self.assertIn(site.name, mail.outbox[0].body)
def test_post_should_send_email_to_user_with_custom_domain_and_site_name(self): user = create_user() data = { 'email': user.email, } request = self.factory.post(data=data) self.view(request) self.assertIn(settings.DJOSER['DOMAIN'], mail.outbox[0].body) self.assertIn(settings.DJOSER['SITE_NAME'], mail.outbox[0].body)
def test_post_should_send_email_to_user_with_domain_and_site_name_from_request(self): user = create_user() data = { 'email': user.email, } request = self.factory.post(data=data) self.view(request) self.assertIn(request.get_host(), mail.outbox[0].body)
def test_real_send_attachments(self): MyNotification().send() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].attachments[0][1],'Some Report Data')
def test_messaging_as_speaker(self): speaker = SpeakerFactory(user=self.user) self.presentation.speaker = speaker self.presentation.save() self.login() rsp = self.client.get(self.tutorial_url) self.assertIn('id="messages"', rsp.content) # We can display the page prompting for a message to send them url = reverse( 'tutorial_message', kwargs={'pk': self.presentation.proposal.pk}) rsp = self.client.get(url) self.assertEqual(200, rsp.status_code) # "Send" a message to those two applications test_message = 'One if by land and two if by sea' data = {'message': test_message, } rsp = self.client.post(url, data=data) self.assertEqual(302, rsp.status_code) msg = PyConTutorialMessage.objects.get( user=self.user, tutorial=self.presentation.proposal) self.assertEqual(test_message, msg.message) # For each message, it's visible, so it should have been emailed to # both the other attendees and speakers. Total: 1 message for this case self.assertEqual(1, len(mail.outbox))
def then_django_send_mail_should_be_called_with_correct_processed_params(self): assert mail.outbox[0].subject == 'Abidria account confirmation' confirmation_url = "{}?token={}".format(self.url, self.confirmation_token) context_params = {'username': self.username, 'confirmation_url': confirmation_url} plain_text_message = get_template('ask_confirmation_email.txt').render(context_params) html_message = get_template('ask_confirmation_email.html').render(context_params) assert mail.outbox[0].body == plain_text_message assert mail.outbox[0].from_email == settings.EMAIL_HOST_USER assert mail.outbox[0].to == [self.email, ] assert mail.outbox[0].alternatives[0][0] == html_message return self
def then_ask_confirmation_email_should_be_sent(self): assert mail.outbox[0].subject == 'Abidria account confirmation' confirmation_token = ORMConfirmationToken.objects.get(person_id=self.orm_person.id).token confirmation_reverse_url = self.response.wsgi_request.build_absolute_uri(reverse('email-confirmation')) confirmation_url = "{}?token={}".format(confirmation_reverse_url, confirmation_token) context_params = {'username': self.username, 'confirmation_url': confirmation_url} plain_text_message = get_template('ask_confirmation_email.txt').render(context_params) html_message = get_template('ask_confirmation_email.html').render(context_params) assert mail.outbox[0].body == plain_text_message assert mail.outbox[0].from_email == settings.EMAIL_HOST_USER assert mail.outbox[0].to == [self.email, ] assert mail.outbox[0].alternatives[0][0] == html_message return self
def then_ask_confirmation_email_should_not_be_sent(self): assert len(mail.outbox) == 0 return self