Skip to content

Instantly share code, notes, and snippets.

@toastdriven
Created October 9, 2009 20:21
Show Gist options
  • Save toastdriven/206341 to your computer and use it in GitHub Desktop.
Save toastdriven/206341 to your computer and use it in GitHub Desktop.
import unittest
# Fake the env.
class ValidationError(Exception): pass
self = type('Test', (object,), {"error_messages": {'invalid': 'ERROR'}})
def is_email(email):
email_bits = email.split('@')
if len(email_bits) != 2:
raise ValidationError(self.error_messages['invalid'])
if len(email_bits[0]) < 1:
raise ValidationError(self.error_messages['invalid'])
domain_bits = email_bits[1].split('.')
if len(domain_bits) < 2:
raise ValidationError(self.error_messages['invalid'])
if not len(domain_bits[-1]) > 2:
raise ValidationError(self.error_messages['invalid'])
for bit in domain_bits:
if len(bit) < 1:
raise ValidationError(self.error_messages['invalid'])
if not bit[0].isalnum() or not bit[-1].isalnum():
raise ValidationError(self.error_messages['invalid'])
return email
class EmailTestCase(unittest.TestCase):
def test_valid_addresses(self):
addresses = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
]
for addy in addresses:
self.assertEqual(is_email(addy), addy)
def test_invalid_addresses(self):
addresses = [
'daniel',
'daniel@',
'@local.com',
'[email protected]',
'[email protected]',
'',
'foo@bar',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
]
for addy in addresses:
try:
is_email(addy)
self.fail(addy)
except ValidationError:
# Supposed to fail.
pass
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment