def _by_url(cls, url, sr): from subreddit import FakeSubreddit if isinstance(sr, FakeSubreddit): sr = None try: lbu = LinksByUrl._byID(LinksByUrl._key_from_url(url)) except tdb_cassandra.NotFound: # translate the tdb_cassandra.NotFound into the NotFound # the caller is expecting raise NotFound('Link "%s"' % url) link_id36s = lbu._values() links = Link._byID36(link_id36s, data=True, return_dict=False) links = [l for l in links if not l._deleted] if links and sr: for link in links: if sr._id == link.sr_id: # n.b. returns the first one if there are multiple return link elif links: return links raise NotFound('Link "%s"' % url)
def _names_to_ids(cls, names, ignore_missing=False, allow_deleted=False, _update=False): for name in names: uid = cls._by_name_cache(name.lower(), allow_deleted, _update=_update) if not uid: if ignore_missing: continue raise NotFound('Account %s' % name) yield uid
def test_auth_transaction(self, get_ids, get_id, create_authorization_hold, request, bidding_request): """Test auth_transaction""" link = Mock(spec=Link) link._id = 99 amount = 100 payment_method_id = 50 campaign_id = 99 request.ip = bidding_request.ip = '127.0.0.1' authorize_response = Mock() authorize_response.trans_id = 123 # If get_ids is empty, assert that the proper value is returned get_ids.return_value = [] return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id) self.assertEqual(return_value, (None, 'invalid payment method')) # Make get_ids return a valid payment_method_id get_ids.return_value.append(payment_method_id) # Assign arbitrary CustomerID, which comes from Authorize get_id.return_value = 1000 create_authorization_hold.return_value = (authorize_response.trans_id, authorize_response) # Scenario: create_authorization_hold raises DuplicateTransactionError duplicate_transaction_error = DuplicateTransactionError( transaction_id=authorize_response.trans_id) create_authorization_hold.side_effect = duplicate_transaction_error # Why does patch.multiple return an AttributeError? with patch('r2.lib.authorize.interaction.Bid.one') as one: one.side_effect = NotFound() return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id) # If create_authorization_hold raises NotFound, assert return value self.assertEqual(return_value, (authorize_response.trans_id, None)) # Scenario: create_authorization_hold successfully returns with patch('r2.lib.authorize.interaction.Bid._new') as _new: return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id) self.assertTrue(_new.called) # If create_authorization_hold works, assert return value self.assertEqual(return_value, (authorize_response.trans_id, None)) # Scenario: create_authorization_hold raises TransactionError create_authorization_hold.side_effect = TransactionError('', authorize_response) return_value = auth_transaction(self.user, campaign_id, link._id, amount, payment_method_id) # If create_authorization_hold raises TransactionError, assert return self.assertEqual(return_value[0], None)
def _get_modmail_userinfo(self, conversation, sr=None): if conversation.is_internal: raise ValueError('Cannot get userinfo for internal conversations') if not sr: sr = Subreddit._by_fullname(conversation.owner_fullname) # Retrieve the participant associated with the conversation try: account = conversation.get_participant_account() if not account: raise ValueError('No account associated with convo') permatimeout = (account.in_timeout and account.days_remaining_in_timeout == 0) if account._deleted or permatimeout: raise ValueError('User info is inaccessible') except NotFound: raise NotFound('Unable to retrieve conversation participant') # Fetch the mute and ban status of the participant as it relates # to the subreddit associated with the conversation. mute_status = sr.is_muted(account) ban_status = sr.is_banned(account) # Parse the ban status and retrieve the length of the ban, # then output the data into a serialiazable dict ban_result = { 'isBanned': bool(ban_status), 'reason': '', 'endDate': None, 'isPermanent': False } if ban_status: ban_result['reason'] = getattr(ban_status, 'note', '') ban_duration = sr.get_tempbans('banned', account.name) ban_duration = ban_duration.get(account.name) if ban_duration: ban_result['endDate'] = ban_duration.isoformat() else: ban_result['isPermanent'] = True ban_result['endDate'] = None # Parse the mute status and retrieve the length of the ban, # then output the data into the serialiazable dict mute_result = { 'isMuted': bool(mute_status), 'endDate': None, 'reason': '' } if mute_status: mute_result['reason'] = getattr(mute_status, 'note', '') muted_items = sr.get_muted_items(account.name) mute_duration = muted_items.get(account.name) if mute_duration: mute_result['endDate'] = mute_duration.isoformat() # Retrieve the participants post and comment fullnames from cache post_fullnames = [] comment_fullnames = [] if not account._spam: post_fullnames = list(queries.get_submitted(account, 'new', 'all'))[:100] comment_fullnames = list( queries.get_comments(account, 'new', 'all'))[:100] # Retrieve the associated link objects for posts and comments # using the retrieve fullnames, afer the link objects are retrieved # create a serializable dict with the the necessary information from # the endpoint. lookup_fullnames = list(set(post_fullnames) | set(comment_fullnames)) posts = Thing._by_fullname(lookup_fullnames) serializable_posts = {} for fullname in post_fullnames: if len(serializable_posts) == 3: break post = posts[fullname] if post.sr_id == sr._id and not post._deleted: serializable_posts[fullname] = { 'title': post.title, 'permalink': post.make_permalink(sr, force_domain=True), 'date': post._date.isoformat(), } # Extract the users most recent comments associated with the # subreddit sr_comments = [] for fullname in comment_fullnames: if len(sr_comments) == 3: break comment = posts[fullname] if comment.sr_id == sr._id and not comment._deleted: sr_comments.append(comment) # Retrieve all associated link objects (combines lookup) comment_links = Link._byID( [sr_comment.link_id for sr_comment in sr_comments]) # Serialize all of the user's sr comments serializable_comments = {} for sr_comment in sr_comments: comment_link = comment_links[sr_comment.link_id] comment_body = sr_comment.body if len(comment_body) > 140: comment_body = '{:.140}...'.format(comment_body) serializable_comments[sr_comment._fullname] = { 'title': comment_link.title, 'comment': comment_body, 'permalink': sr_comment.make_permalink(comment_link, sr, force_domain=True), 'date': sr_comment._date.isoformat(), } return { 'id': account._fullname, 'name': account.name, 'created': account._date.isoformat(), 'banStatus': ban_result, 'isShadowBanned': account._spam, 'muteStatus': mute_result, 'recentComments': serializable_comments, 'recentPosts': serializable_posts, }