def testAuthorize(request): p = PaymentManager() if 'campaign' in request.GET.keys(): campaign_id = request.GET['campaign'] else: campaign_id = None if 'amount' in request.GET.keys(): amount = float(request.GET['amount']) else: return HttpResponse("Error, no amount in request") # Note, set this to 1-5 different receivers with absolute amounts for each receiver_list = [{ 'email': TEST_RECEIVERS[0], 'amount': 20.00 }, { 'email': TEST_RECEIVERS[1], 'amount': 10.00 }] if campaign_id: campaign = Campaign.objects.get(id=int(campaign_id)) t, url = p.authorize('USD', TARGET_TYPE_CAMPAIGN, amount, campaign=campaign, return_url=None, list=None, user=None) else: t, url = p.authorize('USD', TARGET_TYPE_NONE, amount, campaign=None, return_url=None, list=None, user=None) if url: logger.info("testAuthorize: " + url) return HttpResponseRedirect(url) else: response = t.error logger.info("testAuthorize: Error " + str(t.error)) return HttpResponse(response)
def testRefund(request): if "transaction" not in request.GET.keys(): return HttpResponse("No Transaction in Request") t = Transaction.objects.get(id=int(request.GET['transaction'])) p = PaymentManager() if p.refund_transaction(t): return HttpResponse("Success") else: if t.error: message = "Error: " + t.error else: message = "Error" return HttpResponse(message)
def test_paymentmanager_charge(self): """ test regluit.payment.manager.PaymentManager.charge trying to simulate the conditions of having a bare transaction setup before we try to do an instant charge. """ user = User.objects.create_user('pm_charge', '*****@*****.**', 'payment_test') # need to create an Account to associate with user from regluit.payment.stripelib import StripeClient, card, Processor sc = StripeClient() # valid card and Account card0 = card() stripe_processor = Processor() account = stripe_processor.make_account(user=user, token=card0) w = Work() w.save() c = Campaign(target=D('1000.00'), deadline=now() + timedelta(days=180), work=w) c.save() t = Transaction(host='stripelib') t.max_amount = D('12.34') t.type = PAYMENT_TYPE_NONE t.status = TRANSACTION_STATUS_NONE t.campaign = c t.approved = False t.user = user t.save() pm = PaymentManager() response = pm.charge(t) self.assertEqual(t.status, TRANSACTION_STATUS_COMPLETE) self.assertEqual(t.type, EXECUTE_TYPE_CHAINED_INSTANT) self.assertEqual(t.amount, D('12.34'))
def recharge_failed_transactions(self): """When a new Account is saved, check whether this is the new active account for a user. If so, recharge any outstanding failed transactions """ transactions_to_recharge = self.user.transaction_set.filter( (Q(status=TRANSACTION_STATUS_FAILED) | Q(status=TRANSACTION_STATUS_ERROR)) & Q(campaign__status='SUCCESSFUL')).all() if transactions_to_recharge: from regluit.payment.manager import PaymentManager pm = PaymentManager() for transaction in transactions_to_recharge: # check whether we are still within the window to recharge if (now() - transaction.deadline_or_now) < datetime.timedelta( settings.RECHARGE_WINDOW): logger.info( "Recharging transaction {0} w/ status {1}".format( transaction.id, transaction.status)) pm.execute_transaction(transaction, [])
def test_authorize(self): print "RUNNING TEST: test_authorize" p = PaymentManager() # Note, set this to 1-5 different receivers with absolute amounts for each t, url = p.authorize(t) self.validateRedirect(t, url) loginSandbox(self.selenium) paySandbox(self, self.selenium, url, authorize=True) # stick in a getStatus to update statuses in the absence of IPNs p.checkStatus() t = Transaction.objects.get(id=t.id) self.assertEqual(t.status, IPN_PREAPPROVAL_STATUS_ACTIVE)
def testExecute(request): p = PaymentManager() if 'campaign' in request.GET.keys(): campaign_id = request.GET['campaign'] campaign = Campaign.objects.get(id=int(campaign_id)) else: campaign = None output = '' if campaign: result = p.execute_campaign(campaign) for t in result: output += str(t) logger.info(str(t)) else: transactions = Transaction.objects.filter( status=TRANSACTION_STATUS_ACTIVE) for t in transactions: # Note, set this to 1-5 different receivers with absolute amounts for each receiver_list = [{ 'email': TEST_RECEIVERS[0], 'amount': float(t.amount) * 0.80 }, { 'email': TEST_RECEIVERS[1], 'amount': float(t.amount) * 0.20 }] p.execute_transaction(t, receiver_list) output += str(t) logger.info(str(t)) return HttpResponse(output)
def testModify(request): if "transaction" not in request.GET.keys(): return HttpResponse("No Transaction in Request") if "amount" in request.GET.keys(): amount = float(request.GET['amount']) else: amount = 200.0 t = Transaction.objects.get(id=int(request.GET['transaction'])) p = PaymentManager() status, url = p.modify_transaction(t, amount, return_url=None) if url: logger.info("testModify: " + url) return HttpResponseRedirect(url) if status: return HttpResponse("Success") else: return HttpResponse("Error")
def checkStatus(request): # Check the status of all PAY transactions and flag any errors p = PaymentManager() error_data = p.checkStatus() return HttpResponse(error_data, mimetype="text/xml")
def handleIPN(request, module): # Handler for IPN /webhook notifications p = PaymentManager() logger.info(str(request.POST)) return p.processIPN(request, module)
def test_relaunch(unglue_it_url = settings.LIVE_SERVER_TEST_URL, do_local=True, backend='amazon', browser='firefox'): # django.db.transaction.enter_transaction_management() UNGLUE_IT_URL = unglue_it_url USER = settings.UNGLUEIT_TEST_USER PASSWORD = settings.UNGLUEIT_TEST_PASSWORD setup_selenium() sel = selenium_driver(browser=browser) time.sleep(5) print("now opening unglue.it") #sel.get("http://www.google.com") sel.get(UNGLUE_IT_URL) # long wait because sel is slow after PayPal sign_in_link = WebDriverWait(sel, 100).until(lambda d : d.find_element_by_xpath("//span[contains(text(),'Sign In')]/..")) sign_in_link.click() # enter unglue.it login info input_username = WebDriverWait(sel,20).until(lambda d : d.find_element_by_css_selector("input#id_username")) input_username.send_keys(USER) sel.find_element_by_css_selector("input#id_password").send_keys(PASSWORD) sel.find_element_by_css_selector("input[value*='Sign in with Password']").click() # click on biggest campaign list # I have no idea why selenium thinks a is not displayed....so that's why I'm going up one element. # https://stackoverflow.com/a/6141678/7782 #biggest_campaign_link = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("li > a[href*='/campaigns/ending']")) #biggest_campaign_link.click() #time.sleep(1) yield sel # jump to /campaigns/ending#2 p = list(urlparse(UNGLUE_IT_URL)); p[2] = '/campaigns/ending#2' sel.get(urlunparse(p)) time.sleep(1) # pull up one of the campaigns to pledge to # for now, take the first book and click on the link to get to the work page work_links = WebDriverWait(sel,10).until(lambda d: d.find_elements_by_css_selector("div.book-list div.title a")) time.sleep(2) work_links[0].click() time.sleep(2) support_button = WebDriverWait(sel,10).until(lambda d: d.find_element_by_css_selector("input[value*='Pledge']")) support_button.click() # just click Pledge button without filling out amount -- should have the form validation spot the error pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Pledge']")) pledge_button.click() # check to see whether there is an error error_messages = WebDriverWait(sel,20).until(lambda d: d.find_elements_by_css_selector("ul.errorlist")) if len(error_messages): print("yes: Error in just hitting pledge button as expected") else: print("ooops: there should be an error message when pledge button hit") print("making $10 pledge") # now we have to replace the current preapproval amount with 10 sel.execute_script("""document.getElementById("id_preapproval_amount").value="10";""") support_button = WebDriverWait(sel,10).until(lambda d: d.find_element_by_css_selector("input[value*='Pledge Now']")) support_button.click() ## now fill out the credit card ## CVC should fail but doesn't for now -- hmmm. # #sel.execute_script("""document.getElementById("card_Number").value={0};""".format(stripelib.ERROR_TESTING['CVC_CHECK_FAIL'][0])) #sel.execute_script("""document.getElementById("card_ExpiryMonth").value="01";""") #sel.execute_script("""document.getElementById("card_ExpiryYear").value="14";""") #sel.execute_script("""document.getElementById("card_CVC").value="123";""") # #verify_cc_button = WebDriverWait(sel,10).until(lambda d: d.find_element_by_css_selector("input[value*='Complete Pledge']")) #verify_cc_button.click() # #yield sel # let's put in a Luhn-invalid # e.g., 4242424242424241 sel.execute_script("""document.getElementById("card_Number").value="4242424242424241";""") sel.execute_script("""document.getElementById("card_ExpiryMonth").value="01";""") sel.execute_script("""document.getElementById("card_ExpiryYear").value="18";""") sel.execute_script("""document.getElementById("card_CVC").value="321";""") verify_cc_button = WebDriverWait(sel,10).until(lambda d: d.find_element_by_css_selector("input[value*='Complete Pledge']")) verify_cc_button.click() # should do a check for "Your card number is incorrect" -- but this doesn't stall -- so we're ok time.sleep(2) # should succeed sel.execute_script("""document.getElementById("card_Number").value={0};""".format(stripelib.TEST_CARDS[0][0])) sel.execute_script("""document.getElementById("card_ExpiryMonth").value="01";""") sel.execute_script("""document.getElementById("card_ExpiryYear").value="18";""") sel.execute_script("""document.getElementById("card_CVC").value="321";""") time.sleep(2) verify_cc_button = WebDriverWait(sel,10).until(lambda d: d.find_element_by_css_selector("input[value*='Complete Pledge']")) verify_cc_button.click() # verify that we are at pledge_complete # sleep a bit to give enough time for redirecto pledge_complete to finish time.sleep(3) # should be back on a pledge complete page print(sel.current_url, re.search(r"/pledge/complete", sel.current_url)) # need to pick out the actual work pledged. work_url = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector('p.pledge_complete a[href*="/work/"]')) work_url.click() # change_pledge print("clicking Modify Pledge button") change_pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Modify Pledge']")) change_pledge_button.click() # enter a new pledge, which is less than the previous amount print("changing pledge to $5 -- should not need to go to Stripe") sel.execute_script("""document.getElementById("id_preapproval_amount").value="5";""") pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Modify Pledge']")) pledge_button.click() # return to the Work page again work_url = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector('p.pledge_complete a[href*="/work/"]')) work_url.click() change_pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Modify Pledge']")) change_pledge_button.click() # modify pledge to $25 sel.execute_script("""document.getElementById("id_preapproval_amount").value="25";""") pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Modify Pledge']")) pledge_button.click() # now cancel transaction # now go back to the work page, hit modify pledge, and then the cancel link work_url = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector('p.pledge_complete a[href*="/work/"]')) work_url.click() change_pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Modify Pledge']")) change_pledge_button.click() cancel_url = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector('a[href*="/pledge/cancel"]')) cancel_url.click() # hit the confirm cancellation button cancel_pledge_button = WebDriverWait(sel,20).until(lambda d: d.find_element_by_css_selector("input[value*='Confirm Pledge Cancellation']")) cancel_pledge_button.click() time.sleep(10) django.db.transaction.commit() yield sel # now use the transaction manager to make the charge w = models.Work.objects.get(id=48) c = w.campaigns.all()[0] pm = PaymentManager() result = pm.execute_campaign(c) # should have a Complete transaction print(result) yield sel
""" A google example using WebDriver """ testcases = [GoogleWebDriverTest] suites = unittest.TestSuite([unittest.TestLoader().loadTestsFromTestCase(testcase) for testcase in testcases]) unittest.TextTestRunner().run(suites) # from selenium import webdriver # driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS) # driver.get("http://google.com") pm = PaymentManager() def campaign_display(): campaigns_with_active_transactions = models.Campaign.objects.filter(transaction__status=IPN_PREAPPROVAL_STATUS_ACTIVE) campaigns_with_incomplete_transactions = models.Campaign.objects.filter(transaction__status=IPN_PAY_STATUS_INCOMPLETE) campaigns_with_completed_transactions = models.Campaign.objects.filter(transaction__status=IPN_PAY_STATUS_COMPLETED) print("campaigns with active transactions", campaigns_with_active_transactions) print("campaigns with incomplete transactions", campaigns_with_incomplete_transactions) print("campaigns with completed transactions", campaigns_with_completed_transactions) def campaigns_active(): return models.Campaign.objects.filter(transaction__status=IPN_PREAPPROVAL_STATUS_ACTIVE) def campaigns_incomplete():
def pledge_to_work_with_cc(self, username, password, work_id, card, preapproval_amount='10', premium_id='150'): # how much of test.campaigntest.test_relaunch can be done here? self.assertTrue(self.client.login(username=username, password=password)) # Pro Web 2.0 Mashups self.work = Work.objects.get(id=work_id) r = self.client.get("/work/%s/" % (self.work.id)) r = self.client.get("/work/%s/" % self.work.id) self.assertEqual(r.status_code, 200) # go to pledge page r = self.client.get("/pledge/%s" % self.work.id, data={}, follow=True) self.assertEqual(r.status_code, 200) # submit to pledge page r = self.client.post("/pledge/%s/" % self.work.id, data={ 'preapproval_amount': preapproval_amount, 'premium_id': premium_id }, follow=True) self.assertEqual(r.status_code, 200) # Should now be on the fund page pledge_fund_path = r.request.get('PATH_INFO') self.assertTrue(pledge_fund_path.startswith('/payment/fund')) # pull out the transaction info t_id = int(pledge_fund_path.replace('/payment/fund/', '')) # r.content holds the page content # create a stripe token to submit to form sc = StripeClient() stripe_token = sc.create_token(card=card) # track start time and end time of these stipe interactions so that we can limit the window of Events to look for # time0 = time.time() <--- this method was brittle because of clock skew and latency time0 = stripe_token['created'] r = self.client.post(pledge_fund_path, data={'stripe_token': stripe_token.id}, follow=True) # where are we now? self.assertEqual(r.request.get('PATH_INFO'), '/fund/complete/') self.assertEqual(r.status_code, 200) # dig up the transaction and charge it pm = PaymentManager() transaction = Transaction.objects.get(id=t_id) # catch any exception and pass it along try: self.assertTrue(pm.execute_transaction(transaction, ())) except Exception, charge_exception: pass