class TestValidEmail(unittest.TestCase): """Lightly test email address ("addr-spec") validation against RFC 2822. http://www.faqs.org/rfcs/rfc2822.html """ def setUp(self): # Reset the validator state and errors before every test. self.validator = ValidEmail() c.errors = ErrorSet() def test_valid_emails(self): def test(email): result = self.validator.run(email) self.assertEqual(result, email) self.assertFalse(self.validator.has_errors) self.assertEqual(len(c.errors), 0) test('*****@*****.**') test('*****@*****.**') test('*****@*****.**') def _test_failure(self, email, error=errors.BAD_EMAIL): """Helper for testing bad emails.""" result = self.validator.run(email) self.assertEqual(result, None) self.assertTrue(self.validator.has_errors) self.assertTrue(c.errors.get((error, None))) def test_blank_email(self): self._test_failure('', errors.NO_EMAIL) self.setUp() self._test_failure(' ', errors.NO_EMAIL) def test_no_whitespace(self): self._test_failure('test @example.com') self.setUp() self._test_failure('test@ example.com') self.setUp() self._test_failure('test@example. com') self.setUp() self._test_failure("test@\texample.com") def test_no_hostname(self): self._test_failure('example') self.setUp() self._test_failure('example@') def test_no_username(self): self._test_failure('example.com') self.setUp() self._test_failure('@example.com') def test_two_hostnames(self): self._test_failure('[email protected]@example.com')
class APIv1LoginController(RedditController): def pre(self): super(APIv1LoginController, self).pre() c.extension = "json" set_extension(request.environ, "json") @csrf_exempt @json_validate( VCaptcha(), VRatelimit(rate_ip=True, prefix="rate_register_"), signature=VSigned(), name=VUname(['user']), email=ValidEmail("email"), password=VPasswordChange(['passwd', 'passwd2']), ) def POST_register(self, responder, name, email, password, **kwargs): kwargs.update( dict( controller=self, form=responder("noop"), responder=responder, name=name, email=email, password=password, )) return handle_register(**kwargs) @csrf_exempt @json_validate( signature=VSigned(), user=VThrottledLogin(['user', 'passwd']), ) def POST_login(self, responder, user, **kwargs): kwargs.update( dict( controller=self, form=responder("noop"), responder=responder, user=user, )) return handle_login(**kwargs) def _login(self, responder, user, rem=None): """Login the user. AJAX login handler, used by both login and register to set the user cookie and send back a redirect. """ c.user = user c.user_is_loggedin = True self.login(user, rem=rem) responder._send_data(modhash=generate_modhash()) responder._send_data(cookie=user.make_cookie())
def setUp(self): # Reset the validator state and errors before every test. self.validator = ValidEmail() c.errors = ErrorSet()
class SponsorController(PromoteController): @validate(VSponsorAdmin()) def GET_roadblock(self): return PromotePage(title=_("manage roadblocks"), content=Roadblocks()).render() @validate(VSponsorAdminOrAdminSecret('secret'), start=VDate('startdate'), end=VDate('enddate'), link_text=nop('link_text'), owner=VAccountByName('owner'), grouping=VOneOf("grouping", ("total", "day"), default="total")) def GET_report(self, start, end, grouping, link_text=None, owner=None): now = datetime.now(g.tz).replace(hour=0, minute=0, second=0, microsecond=0) if not start or not end: start = promote.promo_datetime_now(offset=1).date() end = promote.promo_datetime_now(offset=8).date() c.errors.remove((errors.BAD_DATE, 'startdate')) c.errors.remove((errors.BAD_DATE, 'enddate')) end = end or now - timedelta(days=1) start = start or end - timedelta(days=7) links = [] bad_links = [] owner_name = owner.name if owner else '' if owner: campaign_ids = PromotionWeights.get_campaign_ids( start, end, author_id=owner._id) campaigns = PromoCampaign._byID(campaign_ids, data=True) link_ids = {camp.link_id for camp in campaigns.itervalues()} links.extend(Link._byID(link_ids, data=True, return_dict=False)) if link_text is not None: id36s = link_text.replace(',', ' ').split() try: links_from_text = Link._byID36(id36s, data=True) except NotFound: links_from_text = {} bad_links = [id36 for id36 in id36s if id36 not in links_from_text] links.extend(links_from_text.values()) content = PromoteReport(links, link_text, owner_name, bad_links, start, end, group_by_date=grouping == "day") if c.render_style == 'csv': return content.as_csv() else: return PromotePage(title=_("sponsored link report"), content=content).render() @validate( VSponsorAdmin(), start=VDate('startdate'), end=VDate('enddate'), sr_name=nop('sr_name'), collection_name=nop('collection_name'), ) def GET_promote_inventory(self, start, end, sr_name, collection_name): if not start or not end: start = promote.promo_datetime_now(offset=1).date() end = promote.promo_datetime_now(offset=8).date() c.errors.remove((errors.BAD_DATE, 'startdate')) c.errors.remove((errors.BAD_DATE, 'enddate')) target = Target(Frontpage.name) if sr_name: try: sr = Subreddit._by_name(sr_name) target = Target(sr.name) except NotFound: c.errors.add(errors.SUBREDDIT_NOEXIST, field='sr_name') elif collection_name: collection = Collection.by_name(collection_name) if not collection: c.errors.add(errors.COLLECTION_NOEXIST, field='collection_name') else: target = Target(collection) content = PromoteInventory(start, end, target) if c.render_style == 'csv': return content.as_csv() else: return PromotePage(title=_("sponsored link inventory"), content=content).render() @validate( VSponsorAdmin(), id_user=VByName('name', thing_cls=Account), email=ValidEmail("email"), ) def GET_lookup_user(self, id_user, email): email_users = AccountsByCanonicalEmail.get_accounts(email) content = SponsorLookupUser(id_user=id_user, email=email, email_users=email_users) return PromotePage(title="look up user", content=content).render()