class TestAccountsSessions(unittest.TestCase): def setUp(self): self.connection, self.db = pp_tests.connect_to_mongo() self.account_data = { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', } self.account = Accounts(self.db, self.account_data) self.account.insert() self.account_session = AccountsSessions(self.db, {'account_id':self.account.id}) self.account_session.insert() def tearDown(self): pp_tests.tear_down(self.db) self.connection.close() def test_create_session_setup_default_elements(self): self.assertTrue(self.account_session.expires) self.assertTrue(self.account_session.account_id) self.assertTrue(self.account_session.id) self.assertTrue(self.account_session.session_id) def test_get_account_from_session(self): account = Accounts.get_from_session(self.db, id = self.account_session.session_id) self.assertEqual(self.account.id, account.id)
class TestStartPayment(unittest.TestCase): def setUp(self): self.app = pp_tests.get_app() self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', }) self.account.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token']) def tearDown(self): self.db.accounts.drop() self.db.messages.drop() self.db.accounts_sessions.drop() self.app.get('/logout') def test_redirect(self): self.assertEqual(302, self.redirect.status_int) self.assertEqual('https://api.twitter.com/oauth/authorize?oauth_token=', self.redirect.location[0:52])
class TestFinishPayment(unittest.TestCase): @classmethod def setUpClass(self): self.app = pp_tests.get_app() self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', 'notification_url': 'http://www.epistemonikos.org', }) self.account.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token']) print "\n", self.redirect.location url = raw_input("Final url? ") query_string = urlparse(url).query self.finish_response = self.app.get('/parrots/finish?%s' % (query_string)) @classmethod def tearDownClass(self): pp_tests.tear_down(self.db) def test_status_code(self): self.assertEqual(302, self.finish_response.status_int) def test_location(self): self.assertEqual('http://www.epistemonikos.org', self.finish_response.location)
def create_account(db): params = request.json account = Accounts(db,request.json) account._data['password'] = sha1(account.salt+params.get('password')).hexdigest() account.insert() response.status = 201 return {'id': str(account.id)}
def callback(db): params = {'startup':'','name':'','email':'','password':''} params.update(request.forms) account = Accounts.findOne(db, {'email': params.get("email","")}) status = False if not account: new_account = Accounts(db, params) new_account._data['password'] = sha1(new_account.salt+params.get('password')).hexdigest() new_account.insert() status = True params['status'] = status return template('signedup',params)
def get_from_token(db): token = request.query.get('token') if token: account = Accounts.findOne(db, {'credentials.private_token': token}) if account: request.account = account return True
def setUpClass(self): self.app = pp_tests.get_app() self.connection, self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', 'notification_url': 'http://www.epistemonikos.org', }) self.account.insert() self.message = Messages(self.db, { 'account_id': self.account.id, 'text': 'Hola Mundo %s' % randint(0, 100000), 'url': 'http://es.wikipedia.org/wiki/Hola_mundo', 'status': True, 'active': True }) self.message.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token']) print "\n", self.redirect.location url = raw_input("Final url? ") query_string = urlparse(url).query self.finish_response = self.app.get('/parrots/finish?%s' % (query_string))
def test_return_json(self): account = Accounts(self.db, self.account_data) account.insert() expected_json = { "id": str(account.id), "email": "*****@*****.**", "name": "Daniel", "startup": "Payparrot", "url": "http://payparrot.com/", "callback_url": "http://demo.payparrot.com", "notification_url": "http://demo.payparrot.com/notifications", "notification_active": False, "stats": {}, } received_json = account.JSON() self.assertEqual(expected_json, received_json)
def get_credentials(account_id, db, secure=True): account = Accounts.findOne(db, account_id) if account: return account.credentials else: response.status = 404 return {}
def login(db): account_by_email = Accounts.findOne(db, { 'email': request.forms.get('email'), }) if account_by_email: account = Accounts.findOne(db, { 'email': request.forms.get('email'), 'password': sha1(account_by_email.salt+request.forms.get('password')).hexdigest() }) if account: account_session = AccountsSessions(db, {'account_id': account.id}) account_session.insert() response.set_cookie('sid', account_session.session_id, path='/', expires = account_session.expires) redirect('/logged') return raise UnauthorizeException()
def callback(account_id, db, secure=True): new_plan = Plans.findOne(db, {'name':request.json.get("name")}) if new_plan: #Verify payment method account = Accounts.findOne(db, account_id) new_account_plan = change_plan(db,new_plan,account) if new_account_plan: return {"id":str(new_account_plan.id)}
def get_account(account_id, db, secure=True): account = Accounts.findOne(db, account_id) if account: account.update(request.json) return account.JSON() else: response.status = 404 return {}
def get_valid_parrot(db, account_id, parrot_id): account = Accounts.findOne(db,account_id) if account: subscription = Subscriptions.findOne(db, {'parrot_id': ObjectId(parrot_id), 'account_id': ObjectId(account_id)}) if subscription: parrot = Parrots.findOne(db, parrot_id) if parrot: return parrot
def create_account_and_login(app, db, account_data): response = app.post_json('/accounts', account_data ) app.post('/login', {'email': account_data['email'], 'password': account_data['password']} ) account = Accounts.findOne(db, response.json.get('id')) return account
def test_cron4_no_subscription(self): account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', 'notification_url': 'http://www.epistemonikos.org', }) account.insert() parrot = Parrots(self.db, { 'twitter_id': '123123123', 'oauth_token': 'asd', 'oauth_token_secret': 'asdf', 'twitter_info': {}, 'payments': [], 'twitter_info': { 'screen_name': 'danielgua' } }) parrot.insert() subscription = Subscriptions(self.db, {'account_id': account.id, 'active': False, 'parrot_id': parrot.id, 'twitter_screen_name': parrot.twitter_info.get("screen_name")}) subscription.insert() last_date = datetime.now(); next_action_date = last_date; next_payment = NextPayments(self.db, { 'account_id': account.id, 'parrot_id': parrot.id, 'action_date': next_action_date }); next_payment.insert() from payparrot_scripts.crons.cron4 import main as cron4 cron4() message = Queue.get_message('payments') self.assertFalse(message) self.assertEqual(0, self.db.next_payments.find({'_id': next_payment.id}).count())
def parrots_finish(db): if request.query.denied: redirect('/twitter_denied.html') session = Sessions.findOne(db, {'oauth_token': request.query.oauth_token}) if session: account = Accounts.findOne(db, session.account_id) if not account: response.status = 404 return {'error': 'Invalid token'} twitter = Twitter() try: access_tokens = twitter.get_access_tokens(request.query.oauth_verifier,{'oauth_token': session.oauth_token, 'oauth_token_secret': session.oauth_token_secret}) twitter.create_client(access_tokens.get('oauth_token'),access_tokens.get('oauth_token_secret')) headers, body = twitter.get('https://api.twitter.com/1/account/verify_credentials.json') except: redirect('/twitter_auth_problem.html') return if headers.status == 200: body = json.loads(body) parrot = Parrots.findOne(db, {'twitter_id': body.get('id')}) if not parrot: new_parrot = Parrots(db, { 'twitter_info': body, 'twitter_id': body.get('id'), 'oauth_token': access_tokens.get('oauth_token'), 'oauth_token_secret': access_tokens.get('oauth_token_secret') }) new_parrot.insert() parrot = new_parrot else: parrot.update({ 'oauth_token': access_tokens.get('oauth_token'), 'oauth_token_secret': access_tokens.get('oauth_token_secret') }) subscription = Subscriptions.findOne(db, {'account_id': account.id, 'parrot_id': parrot.id}) subscription_parameters = { 'parrot_id': parrot.id, 'account_id': account.id, 'active': True, 'external_id': session.external_id, 'twitter_screen_name': body.get("screen_name") } if not subscription: subscription = Subscriptions(db, subscription_parameters) subscription.insert() else: subscription.update(subscription_parameters) notification_id = _create_notification(db, account, parrot, subscription) if notification_id: redirect_url = generate_redirect_url(account.callback_url, session.external_id, subscription.id, notification_id) redirect(redirect_url) else: response.status = 404 return {'error': 'Expired token'}
def setUp(self): self.app = pp_tests.get_app() self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', }) self.account.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token'])
def send_notification(db, payment, notification_type): subscription = Subscriptions.findOne(db, {'account_id': payment.account_id, 'parrot_id': payment.parrot_id}) if subscription: account = Accounts.findOne(db, payment.account_id) if account: notification = Notifications(db, { 'account_id': payment.account_id, 'parrot_id': payment.parrot_id, 'type': notification_type, 'subscription_id': subscription.id, 'external_id': subscription.external_id, 'request_url': account.notification_url }) notification.insert()
def setUp(self): self.connection, self.db = pp_tests.connect_to_mongo() self.account_data = { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', } self.account = Accounts(self.db, self.account_data) self.account.insert() self.account_session = AccountsSessions(self.db, {'account_id':self.account.id}) self.account_session.insert()
def notify(db, notification_raw, notification_message): notification = Notifications.findOne(db, notification_message.get('notification_id')) account = Accounts.findOne(db, notification.account_id) if notification: log('cron3', 'Notifying remote customer', notification_message.get('subscription_id')) if not notification_message.get('type') in VALID_NOTIFICATIONS: log('cron3', 'ERROR: Unknown notification', notification_message.get('subscription_id')) # TODO: Check what to do in this case return if notification.request_url: query_data = { 'subscription_id': str(notification.subscription_id), 'account_id': str(notification.account_id), 'parrot_id': str(notification.parrot_id), 'type': notification_message.get('type'), 'external_id': str(notification.external_id), 'notification_id': str(notification.id), } log('cron3', 'Notification URL: %s' % notification.request_url, notification_message.get('subscription_id')) utf8_query_data = dict([(key,val.encode('utf-8')) for key, val in query_data.items() if isinstance(val, basestring)]) delete_message = False try: if account.notification_active: http_client = Http() headers, body = http_client.request(uri = notification.request_url, body = urlencode(utf8_query_data), method = 'POST') if int(headers.status) >= 200 and int(headers.status) < 300: notification.update({ 'response_status': headers.status, 'response_headers': headers, 'response_body': body, 'status': 'sent' }) log('cron3', 'Remote notification succeded', notification_message.get('subscription_id')) else: log('cron3', "Failed. Notification response not 2XX (received %s) from url %s" % ( headers.status, notification.request_url ), notification_message.get('subscription_id')) else: delete_message = True notification.update({ 'status': 'off' }) if delete_message: Queue.delete_message('notifications', notification_raw) except Exception, e: log('cron3', "Failed. Exception %specified" % e) else: log('cron3', 'ERROR: No remote url specified', notification_message.get('subscription_id'))
def setUpClass(self): self.app = pp_tests.get_app() self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', 'notification_url': 'http://www.epistemonikos.org', }) self.account.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token']) print "\n", self.redirect.location url = raw_input("Final url? ") query_string = urlparse(url).query self.finish_response = self.app.get('/parrots/finish?%s' % (query_string))
def parrots_start(db): account = Accounts.findOne(db,{'credentials.public_token': request.query.get("token")}) if account: twitter = Twitter() client = twitter.create_session() try: tokens = twitter.get_request_token(client) except: redirect('/twitter_down.html') return session = Sessions(db, {'account_id': account.id, 'oauth_token': tokens['oauth_token'], 'oauth_token_secret': tokens['oauth_token_secret'], 'external_id': request.query.external_id}) session.insert() redirect_url = twitter.redirect_url(tokens) redirect(redirect_url) else: print "Noooo ---" response.status = 404 return {}
def get_account(account_id,db, secure = True): if account_id == 'me': account_id = request.account.id account = Accounts.findOne(db, account_id) filter_parrots = {'account_id': ObjectId(account_id), 'active': True} account._data['stats']['parrots_total'] = db.subscriptions.find(filter_parrots).count() from_ = datetime.today() from_ = datetime(from_.year, from_.month, from_.day) to_ = from_ + relativedelta(days=+1) filter_parrots['created_at'] = {'$gte': from_, '$lt': to_} account._data['stats']['parrots_today'] = db.subscriptions.find(filter_parrots).count() account._data['stats']['payments_total'] = db.payments.find({'account_id': ObjectId(account_id), 'success': True}).count() filter_payments = {'account_id': ObjectId(account_id), 'success': True} filter_payments['created_at'] = {'$gte': from_, '$lt': to_} account._data['stats']['payments_today'] = db.payments.find(filter_payments).count() # 'payments_total': 0, # 'payments_today': 0 if account: return account.JSON() else: response.status = 404 return {}
def test_update_document(self): account = Accounts(self.db, self.account_data) account.insert() account.update({"name": "Felipe"}) self.assertEqual("Felipe", account.name)
def test_create_credentials(self): account = Accounts(self.db, self.account_data) account.insert() self.assertTrue(account.credentials.get("private_token")) self.assertTrue(account.credentials.get("public_token"))
class TestCronsIntegration(unittest.TestCase): @classmethod def setUpClass(self): self.app = pp_tests.get_app() self.connection, self.db = pp_tests.connect_to_mongo() self.account = Accounts(self.db, { 'email': '*****@*****.**', 'password': '******', 'name': 'Daniel', 'startup': 'Payparrot', 'url': 'http://payparrot.com/', 'callback_url': 'http://www.epistemonikos.org', 'notification_url': 'http://www.epistemonikos.org', }) self.account.insert() self.message = Messages(self.db, { 'account_id': self.account.id, 'text': 'Hola Mundo %s' % randint(0, 100000), 'url': 'http://es.wikipedia.org/wiki/Hola_mundo', 'status': True, 'active': True }) self.message.insert() self.redirect = self.app.get('/parrots/start?external_id=1&token=%s' % self.account.credentials['public_token']) print "\n", self.redirect.location url = raw_input("Final url? ") query_string = urlparse(url).query self.finish_response = self.app.get('/parrots/finish?%s' % (query_string)) @classmethod def tearDownClass(self): pp_tests.tear_down(self.db, queue = True) self.connection.close() # def test_cron1(self): # from payparrot_scripts.crons.cron1 import main as cron1 # cron1() # # subscription = Subscriptions.findOne(self.db, {}) # self.assertTrue(subscription.first_tweet) # # self.assertEqual(1, Queue.get_queue('payments').count()) # # message = Queue.get_message('payments', visibility_timeout=1) # self.assertEqual({ # 'subscription_id': str(subscription.id), # 'account_id': str(subscription.account_id), # 'parrot_id': str(subscription.parrot_id) # }, json.loads(message.get_body())) def test_crons(self): from payparrot_scripts.crons.cron1 import main as cron1 cron1() from payparrot_scripts.crons.cron2 import main as cron2 cron2() sleep(2) parrot = Parrots.findOne(self.db, {}) twitter = Twitter() twitter.create_client(parrot.oauth_token, parrot.oauth_token_secret) headers, body = twitter.get("http://api.twitter.com/1/statuses/user_timeline.json?user_id=%s&include_rts=false&count=1" % parrot.twitter_info.get('screen_name')) json_twitter_status = json.loads(body) message_start = self.message.text received_message = json_twitter_status[0].get('text') self.assertEqual(self.message.text, received_message[0:len(message_start)]) queue = Queue.get_queue('payments') self.assertEqual(0, queue.count()) from payparrot_scripts.crons.cron3 import main as cron3 cron3() raw_input("Check? ")
def test_save_should_generate_an_id(self): account = Accounts(self.db, self.account_data) account.insert() self.assertTrue(account.id)
def get_from_session(db): session_id = get_session_id() request.account = None if session_id: request.account = Accounts.get_from_session(db, session_id)
def test_get_account_from_session(self): account = Accounts.get_from_session(self.db, id = self.account_session.session_id) self.assertEqual(self.account.id, account.id)