Skip to content

Commit b2ca1f4

Browse files
authored
feat: Add equality to Email (#739)
Email objects are defined as equal iff they have the same email and the same name. This is useful for unit tests where we want to verify that the Email objects generated are as expected.
1 parent ea90f7c commit b2ca1f4

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

sendgrid/helpers/mail/email.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,27 @@ def __init__(self,
7373
if p is not None:
7474
self.personalization = p
7575

76+
def __eq__(self, other):
77+
"""Email objects are equal if they have the same email and the same name
78+
79+
:param other: object to compare with
80+
:type other: any
81+
"""
82+
if isinstance(other, Email):
83+
return self.email == other.email and self.name == other.name
84+
return NotImplemented
85+
86+
def __ne__(self, other):
87+
"""Inverse of __eq__ (required for Python 2)
88+
89+
:param other: object to compare with
90+
:type other: any
91+
"""
92+
x = self.__eq__(other)
93+
if x is not NotImplemented:
94+
return not x
95+
return NotImplemented
96+
7697
@property
7798
def name(self):
7899
"""Name associated with this email.

test/test_email.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,51 @@ def test_add_unicode_name_with_comma(self):
8080
email.name = name
8181

8282
self.assertEqual(email.name, u'"' + name + u'"')
83+
84+
def test_equality_email_name(self):
85+
address = "test@example.com"
86+
name = "SomeName"
87+
email1 = Email(address, name)
88+
email2 = Email(address, name)
89+
90+
self.assertEqual(email1, email2)
91+
92+
def test_equality_email(self):
93+
address = "test@example.com"
94+
email1 = Email(address)
95+
email2 = Email(address)
96+
97+
self.assertEqual(email1, email2)
98+
99+
def test_equality_name(self):
100+
name = "SomeName"
101+
email1 = Email()
102+
email1.name = name
103+
email2 = Email()
104+
email2.name = name
105+
106+
self.assertEqual(email1, email2)
107+
108+
def test_equality_different_emails(self):
109+
address1 = "test1@example.com"
110+
email1 = Email(address1)
111+
address2 = "test2@example.com"
112+
email2 = Email(address2)
113+
114+
self.assertNotEqual(email1, email2)
115+
116+
def test_equality_different_name(self):
117+
name1 = "SomeName1"
118+
email1 = Email()
119+
email1.name = name1
120+
name2 = "SomeName2"
121+
email2 = Email()
122+
email2.name = name2
123+
124+
self.assertNotEqual(email1, email2)
125+
126+
def test_equality_non_email(self):
127+
address = "test@example.com"
128+
email = Email(address)
129+
130+
self.assertNotEqual(email, address)

0 commit comments

Comments
 (0)