Skip to content

Commit

Permalink
Envia email a partir de um scheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
rhenanbartels committed Apr 22, 2021
1 parent 0cfdf4f commit 8c5313d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 17 deletions.
13 changes: 10 additions & 3 deletions brasilio_auth/management/commands/send_bulk_emails.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import django_rq
from datetime import timedelta

import rows
from django.conf import settings
from django.core.management.base import BaseCommand
from django.template import Context, Template
from rq import Queue
from redis import Redis
from tqdm import tqdm

from core.email import send_email
Expand All @@ -22,11 +25,13 @@ def print_email_metadata(self, metadata):
def add_arguments(self, parser):
parser.add_argument("--sender", default=settings.DEFAULT_FROM_EMAIL)
parser.add_argument("--dry-run", default=False, action="store_true")
parser.add_argument("--wait-time", default=15)
parser.add_argument("--wait-time", default=15, type=int)
parser.add_argument("input_filename")
parser.add_argument("template_filename")

def handle(self, *args, **kwargs):
queue = Queue(name=settings.DEFAULT_QUEUE_NAME, connection=Redis())

This comment has been minimized.

Copy link
@turicas

turicas Apr 23, 2021

Owner

Creio que a conexão com o Redis está incorreta (deveria buscar a URI do settings), algo como (não testei):

        redis_conn = Redis.from_url(settings.RQ_QUEUES[settings.DEFAULT_QUEUE_NAME]["URL"])
        queue = Queue(name=settings.DEFAULT_QUEUE_NAME, connection=redis_conn)

input_filename = kwargs["input_filename"]
table = rows.import_from_csv(input_filename)
error_msg = "Arquivo CSV deve conter campos 'to_email' e 'subject'"
Expand All @@ -36,6 +41,7 @@ def handle(self, *args, **kwargs):
wait_time = kwargs["wait_time"]
from_email = kwargs["sender"]

time_offset = 0
for row in tqdm(table):
context = Context(row._asdict())
rendered_template = template_obj.render(context=context)
Expand All @@ -46,6 +52,7 @@ def handle(self, *args, **kwargs):
"to": [row.to_email],
}
if not kwargs["dry_run"]:
django_rq.enqueue(send_email, **email_kwargs)
queue.enqueue_in(timedelta(seconds=time_offset), send_email, **email_kwargs)
time_offset += wait_time
else:
self.print_email_metadata(email_kwargs)
52 changes: 38 additions & 14 deletions brasilio_auth/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
from datetime import timedelta
from tempfile import NamedTemporaryFile
from unittest import mock

import pytest
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.test import TestCase

from core.email import send_email


class TestSendBulkEmails(TestCase):
def setUp(self):
self.p_queue_cls = mock.patch("brasilio_auth.management.commands.send_bulk_emails.Queue")
self.m_queue_cls = self.p_queue_cls.start()
self.m_queue = mock.Mock()
self.m_queue_cls.return_value = self.m_queue

self.input_file = NamedTemporaryFile(suffix=".csv")
self.email_template = NamedTemporaryFile(suffix=".txt")

Expand Down Expand Up @@ -38,27 +46,32 @@ def setUp(self):
},
]

def assert_sent_email_metadata(self, email, metadata):
for key, value in metadata.items():
assert email.__getattribute__(key) == value
def tearDown(self):
self.p_queue_cls.stop()

def test_send_bulk_emails(self):
call_command("send_bulk_emails", self.input_file.name, self.email_template.name)

assert len(mail.outbox) == 2
self.assert_sent_email_metadata(mail.outbox[0], self.expexted_send_email[0])
self.assert_sent_email_metadata(mail.outbox[1], self.expexted_send_email[1])
self.m_queue.enqueue_in.assert_has_calls(
[
mock.call(timedelta(seconds=0), send_email, **self.expexted_send_email[0]),
mock.call(timedelta(seconds=15), send_email, **self.expexted_send_email[1]),
]
)

def test_send_email_custom_from_email(self):
kwargs = {"from": "Example Email <[email protected]>"}
kwargs = {"sender": "Example Email <[email protected]>"}
call_command("send_bulk_emails", self.input_file.name, self.email_template.name, **kwargs)

self.expexted_send_email[0]["from_email"] = kwargs["from"]
self.expexted_send_email[1]["from_email"] = kwargs["from"]
self.expexted_send_email[0]["from_email"] = kwargs["sender"]
self.expexted_send_email[1]["from_email"] = kwargs["sender"]

assert len(mail.outbox) == 2
self.assert_sent_email_metadata(mail.outbox[0], self.expexted_send_email[0])
self.assert_sent_email_metadata(mail.outbox[1], self.expexted_send_email[1])
self.m_queue.enqueue_in.assert_has_calls(
[
mock.call(timedelta(seconds=0), send_email, **self.expexted_send_email[0]),
mock.call(timedelta(seconds=15), send_email, **self.expexted_send_email[1]),
]
)

def test_assert_mandatory_fields(self):
with open(self.input_file.name, "w") as fobj:
Expand All @@ -71,4 +84,15 @@ def test_assert_mandatory_fields(self):
def test_do_not_send_mail(self):
call_command("send_bulk_emails", self.input_file.name, self.email_template.name, "--dry-run")

assert len(mail.outbox) == 0
self.m_queue.assert_not_called()

def test_send_bulk_emails_schedule_with_wait_time(self):
kwargs = {"wait_time": 30}
call_command("send_bulk_emails", self.input_file.name, self.email_template.name, **kwargs)

self.m_queue.enqueue_in.assert_has_calls(
[
mock.call(timedelta(seconds=0), send_email, **self.expexted_send_email[0]),
mock.call(timedelta(seconds=30), send_email, **self.expexted_send_email[1]),
]
)

0 comments on commit 8c5313d

Please sign in to comment.