Python django.core.mail.outbox() Examples
The following are 30
code examples of django.core.mail.outbox().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.mail
, or try the search function
.
Example #1
Source File: views.py From anytask with MIT License | 6 votes |
def test_registration_view_failure(self): """ A ``POST`` to the ``register`` view with invalid data does not create a user, and displays appropriate error messages. """ # with translation.override('en'): response = self.client.post(reverse('registration_register'), data={'username': 'bob', 'email': 'bobe@example.com', 'password1': 'foo', 'password2': 'bar'}) self.assertEqual(response.status_code, 200) self.failIf(response.context['form'].is_valid()) self.assertFormError(response, 'form', field=None, errors=u"Два поля с паролями не совпадают.") self.assertEqual(len(mail.outbox), 0)
Example #2
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_decline_application(self): self.client.force_login(user=self.member) response = self.client.post('/api/applications/{}/decline/'.format(self.application.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['status'], 'declined') self.assertEqual(response.data['decided_by'], self.member.id) self.assertGreaterEqual(parse(response.data['decided_at']), timezone.now() - relativedelta(seconds=5)) self.assertFalse(GroupMembership.objects.filter( group=self.group, user=self.applicant, ).exists()) # applicant should receive email notification = mail.outbox[0] self.assertEqual(notification.to[0], self.applicant.email) self.assertIn('was declined', notification.subject)
Example #3
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_accept_application(self): self.client.force_login(user=self.member) response = self.client.post('/api/applications/{}/accept/'.format(self.application.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['status'], 'accepted') self.assertEqual(response.data['decided_by'], self.member.id) self.assertGreaterEqual(parse(response.data['decided_at']), timezone.now() - relativedelta(seconds=5)) self.assertTrue(GroupMembership.objects.filter( group=self.group, user=self.applicant, ).exists()) # applicant should receive email notification = mail.outbox[0] self.assertEqual(notification.to[0], self.applicant.email) self.assertIn('was accepted', notification.subject) # accepting user gets saved to group membership entry self.assertEqual(GroupMembership.objects.get( group=self.group, user=self.applicant, ).added_by, self.member)
Example #4
Source File: testcase.py From coursys with GNU General Public License v3.0 | 6 votes |
def _pre_setup(self): """Disable transaction methods, and clear some globals.""" # Repeat stuff from TransactionTestCase, because I'm not calling its # _pre_setup, because that would load fixtures again. cache.cache.clear() settings.TEMPLATE_DEBUG = settings.DEBUG = False self.client = self.client_class() #self._fixture_setup() self._urlconf_setup() mail.outbox = [] # Clear site cache in case somebody's mutated Site objects and then # cached the mutated stuff: from django.contrib.sites.models import Site Site.objects.clear_cache()
Example #5
Source File: test_digest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def test_email_weekly_command_other_day(self): """Test that admin cannot digest email not on weekly digest day unless forced.""" setattr(settings, 'DIGEST_WEEKLY_DAY', 0) previous = timezone.now() static = previous # make sure we're not on a scheduled digest day while static.weekday() == 0: static += timezone.timedelta(days=1) with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock: timezone_mock.return_value = static logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday()) create_board(board_title='New Board', days=-1) call_command('senddigest', 'weekly') self.assertEqual(len(mail.outbox), 0, 'Weekly digest email sent on wrong day') call_command('senddigest', 'weekly', '--force') self.assertEqual(len(mail.outbox), 1, 'Weekly digest email not sent when forced')
Example #6
Source File: test_digest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def test_email_weekly_command_digest_day(self): """Test that admin can send digest on the weekly digest day.""" setattr(settings, 'DIGEST_WEEKLY_DAY', 0) previous = timezone.now() static = previous # find the next scheduled digest day while static.weekday() != 0: static += timezone.timedelta(days=1) with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock: timezone_mock.return_value = static logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday()) create_board(board_title='New Board', days=-1) call_command('senddigest', 'weekly') self.assertEqual(len(mail.outbox), 1, 'No weekly digest email sent')
Example #7
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_disable_notifications(self): self.client.force_login(user=self.member) response = self.client.delete( '/api/groups/{}/notification_types/{}/'.format( self.group.id, GroupNotificationType.NEW_APPLICATION, ) ) self.assertEqual(response.status_code, status.HTTP_200_OK) # create application self.client.force_login(user=self.applicant) answers = faker.text() self.client.post('/api/applications/', { 'group': self.group.id, 'answers': answers, }) # no emails should be received by member self.assertEqual(len(mail.outbox), 0)
Example #8
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_newcomer_replies_in_conversation(self): newcomer = UserFactory() self.group.groupmembership_set.create(user=newcomer) mail.outbox = [] self.client.force_login(user=newcomer) chat_message = faker.sentence() with execute_scheduled_tasks_immediately(): response = self.client.post( '/api/messages/', { 'conversation': self.conversation.id, 'content': chat_message, } ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) notification = mail.outbox[0] self.assertIn('New message in', notification.subject) self.assertIn(chat_message, notification.body)
Example #9
Source File: utils.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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()
Example #10
Source File: test_user_management.py From desec-stack with MIT License | 6 votes |
def assertEmailSent(self, subject_contains='', body_contains='', recipient=None, reset=True, pattern=None): total = 1 self.assertEqual(len(mail.outbox), total, "Expected %i message in the outbox, but found %i." % (total, len(mail.outbox))) email = mail.outbox[-1] self.assertTrue(subject_contains in email.subject, "Expected '%s' in the email subject, but found '%s'" % (subject_contains, email.subject)) self.assertTrue(body_contains in email.body, "Expected '%s' in the email body, but found '%s'" % (body_contains, email.body)) if recipient is not None: if isinstance(recipient, list): self.assertListEqual(recipient, email.recipients()) else: self.assertIn(recipient, email.recipients()) body = email.body self.assertIn('user_id = ', body) if reset: mail.outbox = [] return body if not pattern else re.search(pattern, body).group(1)
Example #11
Source File: test_receivers.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_playground_members_are_always_editors(self): new_member = UserFactory() mail.outbox = [] self.group.add_member(new_member) self.assertTrue(self.group.is_editor(new_member)) # no email should be sent when joining playground self.assertEqual(len(mail.outbox), 0) # no email should be sent when giving trust membership = GroupMembership.objects.get(group=self.group, user=new_member) another_user = UserFactory() self.group.add_member(another_user) mail.outbox = [] Trust.objects.create(membership=membership, given_by=another_user) self.assertEqual(len(mail.outbox), 0)
Example #12
Source File: test_donations.py From desec-stack with MIT License | 6 votes |
def test_create_donation(self): url = reverse('v1:donation') data = { 'name': 'Komplizierter Vörnämü-ßßß 马大为', 'iban': 'DE89370400440532013000', 'bic': 'BYLADEM1SWU', 'amount': 123.45, 'message': 'hi there, thank you. Also, some random chars: ™ • ½ ¼ ¾ ⅓ ⅔ † ‡ µ ¢ £ € « » ♤ ♧ ♥ ♢ ¿ ', 'email': 'email@example.com', } response = self.client.post(url, data) self.assertTrue(mail.outbox) email_internal = str(mail.outbox[0].message()) direct_debit = str(mail.outbox[0].attachments[0][1]) self.assertStatus(response, status.HTTP_201_CREATED) self.assertEqual(len(mail.outbox), 2) self.assertEqual(response.data['iban'], data['iban']) self.assertTrue('Komplizierter Vornamu' in direct_debit) self.assertTrue(data['iban'] in email_internal)
Example #13
Source File: test_domains.py From desec-stack with MIT License | 6 votes |
def test_create_domain_name_validation(self): for name in [ 'with space.dedyn.io', 'another space.de', ' spaceatthebeginning.com', 'percentage%sign.com', '%percentagesign.dedyn.io', 'slash/desec.io', '/slashatthebeginning.dedyn.io', '\\backslashatthebeginning.dedyn.io', 'backslash\\inthemiddle.at', '@atsign.com', 'at@sign.com', 'UPPER.case', 'case.UPPER', ]: response = self.client.post(self.reverse('v1:domain-list'), {'name': name}) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(len(mail.outbox), 0)
Example #14
Source File: test_models.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_further_discussion(self): self.vote_on(OptionTypes.FURTHER_DISCUSSION.value) mail.outbox = [] self.process_votings() with self.fast_forward_to_voting_expiration(): self.issue.refresh_from_db() self.assertFalse(self.issue.is_decided()) self.assertTrue(self.group.is_member(self.affected_member)) self.assertEqual(self.issue.votings.count(), 2) self.assertEqual([v.is_expired() for v in self.issue.votings.order_by('created_at')], [True, False]) # check if emails have been sent self.assertEqual(len(mail.outbox), 2) email_to_affected_user = next(email for email in mail.outbox if email.to[0] == self.affected_member.email) email_to_editor = next(email for email in mail.outbox if email.to[0] == self.member.email) self.assertIn('with you', email_to_affected_user.subject) self.assertIn('with {}'.format(self.affected_member.display_name), email_to_editor.subject)
Example #15
Source File: backends.py From anytask with MIT License | 6 votes |
def test_email_send_action_no_sites(self): """ Test re-sending of activation emails via admin action when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ Site._meta.installed = False admin_class = RegistrationAdmin(RegistrationProfile, admin.site) alice = self.backend.register(_mock_request(), username='alice', email='alice@example.com', password1='swordfish') admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend. RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED) admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated. Site._meta.installed = True
Example #16
Source File: backends.py From anytask with MIT License | 6 votes |
def test_registration_no_sites(self): """ Test that registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ Site._meta.installed = False new_user = self.backend.register(_mock_request(), username='bob', email='bob@example.com', password1='secret') self.assertEqual(new_user.username, 'bob') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, 'bob@example.com') self.failIf(new_user.is_active) self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1) Site.meta.installed = True
Example #17
Source File: backends.py From anytask with MIT License | 6 votes |
def test_registration(self): """ Test the registration process: registration creates a new inactive account and a new profile with activation key, populates the correct account data and sends an activation email. """ new_user = self.backend.register(_mock_request(), username='bob', email='bob@example.com', password1='secret') # Details of the returned user must match what went in. self.assertEqual(new_user.username, 'bob') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, 'bob@example.com') # New user must not be active. self.failIf(new_user.is_active) # A registration profile was created, and an activation email # was sent. self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
Example #18
Source File: test_admin.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_admin_add_user_auto_email(self): admin = self._create_admin() self.client.force_login(admin) params = dict( username='testadd', email='test@testadd.com', password1='tester', password2='tester', ) params.update(self.add_user_inline_params) params.update(self._additional_params_add()) self.client.post(reverse(f'admin:{self.app_label}_user_add'), params) queryset = User.objects.filter(username='testadd') self.assertEqual(queryset.count(), 1) user = queryset.first() self.assertEqual(user.emailaddress_set.count(), 1) emailaddress = user.emailaddress_set.first() self.assertEqual(emailaddress.email, 'test@testadd.com') self.assertEqual(len(mail.outbox), 1)
Example #19
Source File: backends.py From anytask with MIT License | 6 votes |
def test_email_send_action_no_sites(self): """ Test re-sending of activation emails via admin action when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ Site._meta.installed = False admin_class = RegistrationAdmin(RegistrationProfile, admin.site) alice = self.backend.register(_mock_request(), username='alice', email='alice@example.com', password1='swordfish') admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend. RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED) admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated. Site._meta.installed = True
Example #20
Source File: backends.py From anytask with MIT License | 6 votes |
def test_email_send_action(self): """ Test re-sending of activation emails via admin action. """ admin_class = RegistrationAdmin(RegistrationProfile, admin.site) alice = self.backend.register(_mock_request(), username='alice', email='alice@example.com', password1='swordfish') admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend. RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED) admin_class.resend_activation_email(_mock_request(), RegistrationProfile.objects.all()) self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated.
Example #21
Source File: backends.py From anytask with MIT License | 6 votes |
def test_registration_no_sites(self): """ Test that registration still functions properly when ``django.contrib.sites`` is not installed; the fallback will be a ``RequestSite`` instance. """ Site._meta.installed = False new_user = self.backend.register(_mock_request(), username='bob', email='bob@example.com', password1='secret') self.assertEqual(new_user.username, 'bob') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, 'bob@example.com') self.failIf(new_user.is_active) self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1) Site.meta.installed = True
Example #22
Source File: backends.py From anytask with MIT License | 6 votes |
def test_registration(self): """ Test the registration process: registration creates a new inactive account and a new profile with activation key, populates the correct account data and sends an activation email. """ new_user = self.backend.register(_mock_request(), username='bob', email='bob@example.com', password1='secret') # Details of the returned user must match what went in. self.assertEqual(new_user.username, 'bob') self.failUnless(new_user.check_password('secret')) self.assertEqual(new_user.email, 'bob@example.com') # New user must not be active. self.failIf(new_user.is_active) # A registration profile was created, and an activation email # was sent. self.assertEqual(RegistrationProfile.objects.count(), 1) self.assertEqual(len(mail.outbox), 1)
Example #23
Source File: test_trust.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def test_newcomer_becomes_editor(self): editor = UserFactory() newcomer = UserFactory() group = GroupFactory(members=[editor], newcomers=[newcomer]) two_days_ago = timezone.now() - relativedelta(days=2) GroupMembership.objects.filter(group=group).update(created_at=two_days_ago) mail.outbox = [] membership = GroupMembership.objects.get(user=newcomer, group=group) Trust.objects.create(membership=membership, given_by=editor) self.assertTrue(group.is_editor(newcomer)) self.assertEqual(len(mail.outbox), 1) self.assertIn('You gained editing permissions', mail.outbox[0].subject) self.assertEqual(History.objects.filter(typus=HistoryTypus.MEMBER_BECAME_EDITOR).count(), 1)
Example #24
Source File: test_domains.py From desec-stack with MIT License | 6 votes |
def test_create_domains(self): self.owner.limit_domains = 100 self.owner.save() for name in [ '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', 'very.long.domain.name.' + self.random_domain_name(), self.random_domain_name(), ]: with self.assertPdnsRequests(self.requests_desec_domain_creation(name)): response = self.client.post(self.reverse('v1:domain-list'), {'name': name}) self.assertStatus(response, status.HTTP_201_CREATED) self.assertTrue(all(field in response.data for field in ['created', 'published', 'name', 'keys', 'minimum_ttl', 'touched'])) self.assertEqual(len(mail.outbox), 0) self.assertTrue(isinstance(response.data['keys'], list)) with self.assertPdnsRequests(self.request_pdns_zone_retrieve_crypto_keys(name)): self.assertStatus( self.client.get(self.reverse('v1:domain-detail', name=name), {'name': name}), status.HTTP_200_OK ) response = self.client.get_rr_sets(name, type='NS', subname='') self.assertStatus(response, status.HTTP_200_OK) self.assertContainsRRSets(response.data, [dict(subname='', records=settings.DEFAULT_NS, type='NS')])
Example #25
Source File: testcases.py From bioforum with MIT License | 5 votes |
def _pre_setup(self): """ Perform pre-test setup: * Create a test client. * Clear the mail test outbox. """ self.client = self.client_class() mail.outbox = []
Example #26
Source File: utils.py From bioforum with MIT License | 5 votes |
def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, 'saved_data'): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG saved_data = SimpleNamespace() _TestState.saved_data = saved_data saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver'] saved_data.debug = settings.DEBUG settings.DEBUG = debug saved_data.email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' saved_data.template_render = Template._render Template._render = instrumented_test_render mail.outbox = [] deactivate()
Example #27
Source File: test_notifications.py From linkedevents with MIT License | 5 votes |
def test_draft_event_deleted(event_deleted_notification_template, user, event): event.created_by = user event.publication_status = PublicationStatus.DRAFT event.save() event.soft_delete() strings = [ "event deleted body, event name: %s!" % event.name, ] html_body = "event deleted <b>HTML</b> body, event name: %s!" % event.name assert len(mail.outbox) == 1 check_received_mail_exists( "event deleted subject, event name: %s!" % event.name, user.email, strings, html_body=html_body)
Example #28
Source File: test_notifications.py From linkedevents with MIT License | 5 votes |
def test_public_event_deleted_doesnt_trigger_notification(event_deleted_notification_template, user, event): event.created_by = user event.save() event.soft_delete() assert len(mail.outbox) == 0
Example #29
Source File: test_api.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def test_member_replies_in_conversation(self): self.client.force_login(user=self.member) chat_message = faker.sentence() with execute_scheduled_tasks_immediately(): response = self.client.post( '/api/messages/', { 'conversation': self.conversation.id, 'content': chat_message, } ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) notification = mail.outbox[0] self.assertEqual(notification.to[0], self.applicant.email) self.assertIn('New message in', notification.subject) self.assertIn(chat_message, notification.body)
Example #30
Source File: utils.py From linkedevents with MIT License | 5 votes |
def check_received_mail_exists(subject, to, strings, clear_outbox=True, html_body=None): if not (isinstance(strings, list) or isinstance(strings, tuple)): strings = (strings,) assert len(mail.outbox) >= 1, "No mails sent" assert _mail_exists(subject, to, strings, html_body) if clear_outbox: mail.outbox = []