## $Id: tests.py 17586 2023-09-19 06:27:35Z henrik $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
import os
import random
from datetime import datetime, timedelta, date
from zope.component import createObject, getUtility
from zope.catalog.interfaces import ICatalog
from xml.dom.minidom import parseString
from hurry.workflow.interfaces import IWorkflowState
from waeup.kofa.students.tests.test_browser import StudentsFullSetup
from waeup.kofa.applicants.tests.test_browser import ApplicantsFullSetup
from waeup.kofa.configuration import SessionConfiguration
from waeup.kofa.students.payments import StudentOnlinePayment
from waeup.kofa.browser.tests.test_pdf import samples_dir
from kofacustom.nigeria.interswitch.helpers import (
query_interswitch, get_SOAP_response_paydirect, SOAP_post,
create_paydirect_booking,
confirm_transaction
)
from kofacustom.nigeria.testing import FunctionalLayer
# Also run tests that send requests to external servers?
# If you enable this, please make sure the external services
# do exist really and are not bothered by being spammed by a test programme.
EXTERNAL_TESTS_1 = False
EXTERNAL_TESTS_2 = False
EXTERNAL_TESTS_3 = False
PAYDIRECT_HOST = 'sandbox.interswitchng.com'
PAYDIRECT_URL = '/bookonhold/bookonhold.asmx'
MERCHANT_ID = '6033'
def external_test_1(func):
if not EXTERNAL_TESTS_1:
myself = __file__
if myself.endswith('.pyc'):
myself = myself[:-1]
print "WARNING: external tests are skipped!"
print "WARNING: edit %s to enable them." % myself
return
return func
def external_test_2(func):
if not EXTERNAL_TESTS_2:
myself = __file__
if myself.endswith('.pyc'):
myself = myself[:-1]
print "WARNING: external tests are skipped!"
print "WARNING: edit %s to enable them." % myself
return
return func
def external_test_3(func):
if not EXTERNAL_TESTS_3:
myself = __file__
if myself.endswith('.pyc'):
myself = myself[:-1]
print "WARNING: external tests are skipped!"
print "WARNING: edit %s to enable them." % myself
return
return func
class InterswitchTestsStudents(StudentsFullSetup):
"""Tests for the Interswitch payment gateway.
"""
layer = FunctionalLayer
def setUp(self):
super(InterswitchTestsStudents, self).setUp()
self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
self.browser.open(self.payments_path)
IWorkflowState(self.student).setState('cleared')
self.student.nationality = u'NG'
self.browser.open(self.payments_path + '/addop')
self.browser.getControl(name="form.p_category").value = ['schoolfee']
self.browser.getControl("Create ticket").click()
self.assertMatches('...ticket created...',
self.browser.contents)
self.browser.open(self.payments_path)
ctrl = self.browser.getControl(name='val_id')
self.value = ctrl.options[0]
self.browser.getLink(self.value).click()
self.assertMatches('...Amount Authorized...',
self.browser.contents)
self.assertTrue('40000.0', self.browser.contents)
self.payment_url = self.browser.url
self.payment = self.student['payments'][self.value]
def test_interswitch_form(self):
# Manager can access InterswitchForm
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
self.assertMatches('......',
self.browser.contents)
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
self.assertEqual(self.student.current_mode, 'ug_ft')
self.assertMatches(
'......',
self.browser.contents)
# Create school fee ticket for returning students. Payment is made
# for next session.
current_payment_key = self.student['payments'].keys()[0]
self.certificate.study_mode = u'ug_pt'
IWorkflowState(self.student).setState('returning')
configuration = createObject('waeup.SessionConfiguration')
configuration.academic_session = 2005
self.app['configuration'].addSessionConfiguration(configuration)
self.browser.open(self.payments_path + '/addop')
self.browser.getControl(name="form.p_category").value = ['schoolfee']
self.browser.getControl("Create ticket").click()
self.browser.open(self.payments_path)
ctrl = self.browser.getControl(name='val_id')
value = ctrl.options[1]
self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
self.browser.getLink(value).click()
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
# Split amounts have been set.
self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
self.assertMatches('......',
self.browser.contents)
self.assertTrue(
'' in
self.browser.contents)
def test_interswitch_form_ticket_expired(self):
# Manager can access InterswitchForm
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
self.assertMatches('......',
self.browser.contents)
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
self.assertEqual(self.student.current_mode, 'ug_ft')
self.assertTrue(
'' in
self.browser.contents)
delta = timedelta(days=8)
self.payment.creation_date -= delta
self.browser.open(self.payment_url)
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
self.assertMatches(
'...This payment ticket is too old. Please create a new ticket...',
self.browser.contents)
delta = timedelta(days=2)
self.payment.creation_date += delta
self.browser.open(self.payment_url)
self.browser.getLink("Pay via Interswitch CollegePAY").click()
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
def test_interswitch_form_ticket_expired_tz(self):
# The form copes with timezones when calculating expirements.
# We should not have TZ data in timestamps processed, but it looks
# like we get some with imports :-/
#self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
delta = timedelta(days=9) # In European summertime, 8 days is not enough
self.payment.creation_date -= delta
from pytz import timezone
self.payment.creation_date = timezone("Europe/Berlin").localize(
self.payment.creation_date)
self.browser.open(self.payment_url)
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
self.assertMatches(
'...This payment ticket is too old. Please create a new ticket...',
self.browser.contents)
delta = timedelta(days=2)
self.payment.creation_date += delta
self.browser.open(self.payment_url)
self.browser.getLink("Pay via Interswitch CollegePAY").click()
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
@external_test_1
def test_query_interswitch_SOAP(self):
host = 'webpay.interswitchng.com'
url = '/paydirect/services/TransactionQueryWs.asmx'
https = True
mac = None
product_id = '5845' # AAUE regular
payment = StudentOnlinePayment()
payment.p_id ='p4465649308559'
payment.amount_auth = 60250.0
success, msg, log = query_interswitch(
payment, product_id, host, url, https, mac, False)
self.assertEqual('Successful callback received.', msg)
self.assertTrue(success)
self.assertTrue(
'00:Approved Successful:6025000:3154:p4465649308559:'
'ZIB|WEB|ABAL|3-11-2015|021336:000457580882' in log)
@external_test_1
def test_query_interswitch_JSON(self):
host = 'webpay.interswitchng.com'
url = '/paydirect/api/v1/gettransaction.json'
mac = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
https = True
product_id = '5845' # AAUE regular
payment = StudentOnlinePayment()
payment.p_id ='p4465649308559'
payment.amount_auth = 1.0
success, msg, log = query_interswitch(
payment, product_id, host, url, https, mac, False)
self.assertFalse(success)
self.assertTrue('Unsuccessful callback:' in msg)
self.assertTrue('Amount Inconsistency' in log)
payment.amount_auth = 60250.0
success, msg, log = query_interswitch(
payment, product_id, host, url, https, mac, False)
self.assertEqual('Successful callback received', msg)
self.assertTrue(success)
self.assertTrue(
"{u'SplitAccounts': [], "
"u'MerchantReference': u'p4465649308559', "
"u'PaymentReference': u'ZIB|WEB|ABAL|3-11-2015|021336', "
"u'TransactionDate': u'2015-11-03T16:40:54.487', "
"u'RetrievalReferenceNumber': u'000457580882', "
"u'ResponseDescription': u'Approved Successful', "
"u'Amount': 6025000, "
"u'CardNumber': u'3154', "
"u'ResponseCode': u'00', "
"u'LeadBankCbnCode': None, "
"u'LeadBankName': None}" in log)
# PAYDirect tests
@external_test_2
def test_SOAP_paydirect(self):
payment = createObject('waeup.StudentOnlinePayment')
payment.p_category = u'schoolfee'
payment.p_session = self.student.current_session
payment.p_item = u'My Certificate'
payment.p_id = 'p' + str(random.randint(10000000000, 90000000000))
payment.amount_auth = 1000.0
item_code = '01'
self.student['payments'][payment.p_id] = payment
result_xml = create_paydirect_booking(
MERCHANT_ID, payment, item_code, PAYDIRECT_HOST, PAYDIRECT_URL, True)
result_xml = get_SOAP_response_paydirect(
MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
doc=parseString(result_xml)
status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
amount=doc.getElementsByTagName('Amount')[0].firstChild
self.assertEqual(status, 'Pending')
self.assertEqual(amount, None)
p_id = 'p5812734587097'
result_xml = get_SOAP_response_paydirect(MERCHANT_ID, p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
doc=parseString(result_xml)
self.assertEqual(doc.getElementsByTagName('PaymentStatus'), [])
@external_test_2
def test_paydirect_pending(self):
# Manager can access InterswitchForm
self.browser.getLink("Pay via Interswitch PAYDirect").click()
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
self.assertEqual(self.student.current_mode, 'ug_ft')
# Create school fee ticket for returning students. Payment is made
# for next session.
current_payment_key = self.student['payments'].keys()[0]
self.certificate.study_mode = u'ug_pt'
IWorkflowState(self.student).setState('returning')
configuration = createObject('waeup.SessionConfiguration')
configuration.academic_session = 2005
self.app['configuration'].addSessionConfiguration(configuration)
self.browser.open(self.payments_path + '/addop')
self.browser.getControl(name="form.p_category").value = ['schoolfee']
self.browser.getControl("Create ticket").click()
self.browser.open(self.payments_path)
ctrl = self.browser.getControl(name='val_id')
value = ctrl.options[1]
self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
self.browser.getLink(value).click()
self.browser.getLink("Pay via Interswitch PAYDirect").click()
# Split amounts have been set.
self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
ref_number = '%s%s' % (MERCHANT_ID,value[1:])
self.assertTrue(ref_number in self.browser.contents)
self.assertEqual(self.student['payments'][value].r_pay_reference, None)
self.browser.getControl("Requery").click()
self.assertTrue('pending' in self.browser.contents)
# Reference number has been saved
self.assertEqual(self.student['payments'][value].r_pay_reference, ref_number)
# Students can download reference number slip
self.browser.getLink("Pay via Interswitch PAYDirect").click()
self.browser.getLink("Download reference number slip").click()
self.assertEqual(self.browser.headers['Status'], '200 Ok')
self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
path = os.path.join(samples_dir(), 'refnumberslip.pdf')
open(path, 'wb').write(self.browser.contents)
print "Sample PDF refnumberslip.pdf written to %s" % path
@external_test_2
def test_paydirect_completed(self):
payment = createObject('waeup.StudentOnlinePayment')
payment.p_category = u'schoolfee'
payment.p_session = self.student.current_session
payment.p_item = u'My Certificate'
# p6214352306153 has been manually set completed by Interswitch
payment.p_id = u'p6214352306153'
payment.amount_auth = 10.0 # 300 will be added
self.student['payments'][payment.p_id] = payment
result_xml = get_SOAP_response_paydirect(
MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
doc=parseString(result_xml)
status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
refnumber=doc.getElementsByTagName('ReferenceNumber')[0].firstChild.data
amount=float(doc.getElementsByTagName('Amount')[0].firstChild.data)
self.assertEqual(status, 'Completed')
self.assertEqual(amount, 1000)
self.assertEqual(refnumber, '60336214352306153')
# Now we login and check what will happen with the student after payment
self.browser.open(self.payments_path)
self.browser.getLink(payment.p_id).click()
self.browser.getLink("Pay via Interswitch PAYDirect").click()
# 300 has been added
self.assertEqual(payment.amount_auth, 310)
self.assertEqual(payment.net_amt, 10)
# Unfortunately the payment 60336214352306153 was done without surcharge.
# Therefore we have to deduct 300 again in this test.
payment.amount_auth = 10.0
# Reference number has been saved
self.browser.getControl("Requery").click()
self.assertEqual(
self.student['payments'][payment.p_id].r_pay_reference, '60336214352306153')
# Payment is made
self.assertEqual(
self.student['payments'][payment.p_id].p_state, 'paid')
# Rubbish has been stored too
self.assertTrue(
self.student['payments'][payment.p_id].r_desc.startswith('Channel Name: Bank Branc'))
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'students.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
'- K1000000 - valid callback for schoolfee payment %s: Completed' % payment.p_id in logcontent)
self.assertTrue(
'zope.mgr - K1000000 - First school fee payment made' in logcontent)
self.assertTrue(
'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
'- K1000000 - successful schoolfee payment: %s' % payment.p_id in logcontent)
class InterswitchTestsApplicants(ApplicantsFullSetup):
"""Tests for the Interswitch payment gateway.
"""
layer = FunctionalLayer
def setUp(self):
super(InterswitchTestsApplicants, self).setUp()
configuration = SessionConfiguration()
configuration.academic_session = datetime.now().year - 2
self.app['configuration'].addSessionConfiguration(configuration)
self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
self.browser.open(self.manage_path)
#IWorkflowState(self.student).setState('started')
super(InterswitchTestsApplicants, self).fill_correct_values()
self.applicantscontainer.application_fee = 1000.0
self.browser.getControl(name="form.nationality").value = ['NG']
self.browser.getControl(name="transition").value = ['start']
self.browser.getControl("Save").click()
self.browser.getControl("Add online").click()
self.assertMatches('...ticket created...',
self.browser.contents)
self.payment = self.applicant.values()[0]
self.payment_url = self.browser.url
def test_interswitch_form(self):
self.assertMatches('...Amount Authorized...',
self.browser.contents)
self.assertMatches(
'...1000.0...',
self.browser.contents)
# Manager can access InterswitchForm
self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
self.assertMatches(
'......',
self.browser.contents)
delta = timedelta(days=8)
self.payment.creation_date -= delta
self.browser.open(self.payment_url)
self.browser.getLink("Pay via Interswitch", index=0).click()
self.assertMatches(
'...This payment ticket is too old. Please create a new ticket...',
self.browser.contents)
delta = timedelta(days=2)
self.payment.creation_date += delta
self.browser.getLink("Pay via Interswitch", index=0).click()
self.assertMatches('...Total Amount Authorized:...',
self.browser.contents)
# WebCheckout tests
# https://webpay.interswitchng.com/collections/api/v1/gettransaction.json?merchantcode=MX76823&transactionreference=p6709347986663&amount=100
mac = "uS6U18pC6GFKCpJoZH6J6jlOmR81FSrHkjBRpMaaydNQtywuG0hdB02J56MCqLV8rmzeAkhiaQR2nNcX3EPJePl5ppidImeKSzdunhddQh61UGpZPiS2CxMdAem8ueA1"
@external_test_3
def test_confirm_transaction(self):
host = 'webpay.interswitchng.com'
url = '/collections/api/v1/gettransaction.json'
https = True
merchant_code = 'MX76823'
payment = StudentOnlinePayment()
payment.p_id ='p4465649308559'
payment.amount_auth = 100000.0
success, msg, log = confirm_transaction(
payment, merchant_code, host, url, https, self.mac)
self.assertFalse(success)
self.assertTrue('Unsuccessful callback:' in msg)
self.assertTrue('Transaction not Found' in log)
payment.p_id ='p6709347986663'
payment.amount_auth = 1.0
success, msg, log = confirm_transaction(
payment, merchant_code, host, url, https, self.mac)
self.assertTrue('Amount Inconsistency' in log)
payment.amount_auth = 100.0
success, msg, log = confirm_transaction(
payment, merchant_code, host, url, https, self.mac)
self.assertEqual('Successful callback received', msg)
self.assertTrue(success)
self.assertTrue(
"{u'SplitAccounts': [], "
"u'RemittanceAmount': 0, "
"u'MerchantReference': u'p6709347986663', "
"u'PaymentReference': u'FBN|WEB|MX76823|13-12-2022|935097929|608001', "
"u'TransactionDate': u'2022-12-13T01:34:21', "
"u'RetrievalReferenceNumber': u'814212374638', "
"u'ResponseDescription': u'Approved by Financial Institution', "
"u'Amount': 10000, "
"u'CardNumber': u'', "
"u'ResponseCode': u'00', "
"u'BankCode': u'011'}" in log)