Skip to content

Commit

Permalink
mailoutbox fixups (#427)
Browse files Browse the repository at this point in the history
Make sure `mail.outbox == foo`, `mail.outbox != bar` and `iter(mail.outbox)` raises exceptions.

This commit also improves the readability of the provided assertion message by hiding the internal traceback and showing the documentation link.
  • Loading branch information
pelme committed Nov 21, 2016
1 parent e659dcc commit 5455dca
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
14 changes: 11 additions & 3 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,9 +402,17 @@ def teardown():
class _DirectMailboxAccessProtector(list):

def _raise_assertion(*args, **kwargs):
raise AssertionError('To access mail.outbox, use the mailoutbox fixture.')

__len__ = __getitem__ = __nonzero__ = __bool__ = _raise_assertion
__tracebackhide__ = True
raise AssertionError('''To access mail.outbox, use the mailoutbox fixture.
See http://pytest-django.readthedocs.io/en/latest/helpers.html#mailoutbox for more information.''')

__len__ = _raise_assertion
__getitem__ = _raise_assertion
__nonzero__ = _raise_assertion
__bool__ = _raise_assertion
__eq__ = _raise_assertion
__ne__ = _raise_assertion
__iter__ = _raise_assertion


@pytest.fixture(autouse=True)
Expand Down
37 changes: 29 additions & 8 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,37 @@
# to do it.


def test_direct_mailbox_access_not_allowed():
with pytest.raises(AssertionError):
len(mail.outbox)
class Test_direct_mailbox_access_not_allowed():

with pytest.raises(AssertionError):
mail.outbox[0]
def test_len(self):
with pytest.raises(AssertionError):
len(mail.outbox)

with pytest.raises(AssertionError):
if mail.outbox:
pass
def test_indexing(self):
with pytest.raises(AssertionError):
mail.outbox[0]

def test_bool(self):
with pytest.raises(AssertionError):
if mail.outbox:
pass

def test_equality(self):
with pytest.raises(AssertionError):
mail.outbox == 'whatever'

def test_not_equality(self):
with pytest.raises(AssertionError):
mail.outbox != 'whatever'

def test_unpacking(self):
with pytest.raises(AssertionError):
(foo,) = mail.outbox

def test_iteration(self):
with pytest.raises(AssertionError):
for x in mail.outbox:
pass


def test_direct_mailbox_proection_should_not_break_sending_mail():
Expand Down

0 comments on commit 5455dca

Please sign in to comment.