## $Id: tests.py 14781 2017-08-09 08:49:45Z henrik $
##
## Copyright (C) 2017 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 unittest
import random
import json
from datetime import datetime, timedelta, date
from zope.component import createObject, getUtility
from zope.catalog.interfaces import ICatalog
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 kofacustom.nigeria.students.payments import NigeriaStudentOnlinePayment
from kofacustom.nigeria.testing import FunctionalLayer
from kofacustom.nigeria.remita.helpers import (
get_JSON_POST_response, get_payment_status_via_rrr, query_remita)
# 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 = True
def external_test(func):
if not EXTERNAL_TESTS:
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 HelperTests(unittest.TestCase):
merchantId = '2547916'
serviceTypeId = '4430731'
api_key = '1946'
responseurl = 'http://xxxx'
host = 'www.remitademo.net'
url = '/remita/ecomm/split/init.reg' # /remita/ecomm/v2/init.reg
lineitems = (
{"lineItemsId":"itemid1","beneficiaryName":"Oshadami Mike",
"beneficiaryAccount":"6020067886","bankCode":"011",
"beneficiaryAmount":"500","deductFeeFrom":"1"},
{"lineItemsId":"itemid2","beneficiaryName":"Ogunseye Mujib",
"beneficiaryAccount":"0360883515","bankCode":"050",
"beneficiaryAmount":"500","deductFeeFrom":"0"}
)
amount = 1000.0
def _get_transaction_data(self):
self.orderId = str(random.randint(100000000, 999999999))
resp = get_JSON_POST_response(
merchantId=self.merchantId, serviceTypeId=self.serviceTypeId,
api_key=self.api_key, orderId=self.orderId,
amount=self.amount, responseurl=self.responseurl,
host=self.host, url=self.url, https=False,
fullname='Anton Meier', email='am@xxx.de',
lineitems=self.lineitems)
self.rrr = resp['RRR'].rstrip()
@external_test
def test_get_JSON_POST_response(self):
self._get_transaction_data()
resp = get_JSON_POST_response(
merchantId=self.merchantId, serviceTypeId=self.serviceTypeId,
api_key=self.api_key, orderId=self.orderId,
amount=self.amount, responseurl=self.responseurl,
host=self.host, url=self.url, https=False,
fullname='Anton Meier', email='am@xxx.de',
lineitems=self.lineitems)
assert resp == {
u'status': u'RRR Already Exist for the orderId',
u'orderID': self.orderId,
u'RRR': self.rrr + ' ', # strange trailing whitespace which
# obviously does not belong to the RRR
u'statuscode': u'055'}
resp = get_payment_status_via_rrr(
merchantId=self.merchantId,
api_key=self.api_key,
RRR=self.rrr,
host=self.host,
https=False,
)
assert resp['orderId'] == self.orderId
assert resp['status'] == '021'
assert resp['amount'] == self.amount
assert resp['lineitems'] == [
{u'status': u'021', u'lineItemsId': u'itemid1'},
{u'status': u'021', u'lineItemsId': u'itemid2'}]
assert resp['RRR'] == self.rrr
assert resp['message'] == u'Transaction Pending'
class RemitaTestsStudents(StudentsFullSetup):
"""Tests for the Remita payment gateway.
"""
layer = FunctionalLayer
merchantId = '2547916'
serviceTypeId = '4430731'
api_key = '1946'
responseurl = 'http://xxxx'
host = 'www.remitademo.net'
# successful transaction
# (hopefully this transaction remains in the Remita database)
orderId = '3456346346'
rrr = u'280007640804'
amount = 1000.0
# pending transaction
#orderId_p = '987698769876'
rrr_p = u'320007640976'
def setUp(self):
super(RemitaTestsStudents, self).setUp()
self.app['configuration']['2004'].remita_enabled = True
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)
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]
@external_test
def test_query_remita(self):
#requery pending transaction
qr = query_remita(
self.payment,
merchantId=self.merchantId,
api_key=self.api_key,
RRR=self.rrr_p,
host=self.host,
https=False,
verify=False)
assert qr == (
False,
u'Unsuccessful callback: ${a}',
u'unsuccessful callback for schoolfee payment %s: Transaction Pending'
% self.payment.p_id)
#requery successful transaction
self.payment.amount_auth = 1000.0
self.payment.p_id = self.orderId
qr = query_remita(
self.payment,
merchantId=self.merchantId,
api_key=self.api_key,
RRR=self.rrr,
host=self.host,
https=False,
verify=False)
assert qr[0] == True
assert qr[1] == u'Successful callback received'
@external_test
def test_student_remita_form(self):
# Manager can access Remita form
self.browser.getLink("Pay via Remita").click()
# The RRR has been retrieved
self.assertTrue('' % self.rrr
in self.browser.contents)
self.assertEqual(self.payment.r_pay_reference, self.rrr)
self.assertEqual(self.payment.r_company, 'remita')
# Retrieval has been logged
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'students.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.mgr - kofacustom.nigeria.remita.studentsbrowser.RemitaPageStudent'
' - K1000000 - RRR retrieved: %s' % self.rrr in logcontent)
# Means of testing end here.
return
@external_test
def test_requery_verify_payment_status(self):
# Manager can access Remita form
self.browser.getLink("Requery Remita Payment Status").click()
self.assertTrue('Remita Retrieval Reference not found.'
in self.browser.contents)
self.payment.r_pay_reference = self.rrr
self.browser.getLink("Requery Remita Payment Status").click()
self.assertTrue('Callback amount does not match.'
in self.browser.contents)
self.payment.amount_auth = self.amount
self.browser.getLink("Requery Remita Payment Status").click()
self.assertTrue('Callback order id does not match.'
in self.browser.contents)
self.payment.p_id = self.orderId
self.browser.getLink("Requery Remita Payment Status").click()
self.assertTrue('Successful payment' in self.browser.contents)
self.assertEqual(self.payment.r_desc, 'Approved')
self.assertEqual(self.payment.r_amount_approved , 1000.0)
self.assertEqual(self.payment.r_code, '01')
self.browser.getLink("Verify Remita Payment Status").click()
self.assertTrue('Successful callback received' in self.browser.contents)
return
class RemitaTestsWebserviceStudent(StudentsFullSetup):
"""Tests for the Remita payment gateway.
"""
layer = FunctionalLayer
merchantId = '2547916'
serviceTypeId = '4430731'
api_key = '1946'
responseurl = 'http://xxxx'
host = 'www.remitademo.net'
# successful transaction
# (hopefully this transaction remains in the Remita database)
orderId = '3456346346'
rrr = u'280007640804'
amount = 1000.0
@external_test
def test_payment_notification_listener_student(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 = self.orderId
self.student['payments']['anykey'] = payment
data = [{'orderRef': self.orderId, 'rrr': self.rrr},]
# Send POST request with wrong payment amount
payment.amount_auth = 2000.0
self.browser.post('http://localhost/app/paymentnotificationlistener',
json.dumps(data), 'application/json; charset=utf-8')
self.assertEqual('0 (1)', self.browser.contents)
# Send POST request with correct payment amount
payment.amount_auth = self.amount
self.browser.post('http://localhost/app/paymentnotificationlistener',
json.dumps(data), 'application/json; charset=utf-8')
self.assertEqual('1 (1)', self.browser.contents)
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'students.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
' - K1000000 - valid callback for schoolfee payment %s: '
% self.orderId in logcontent)
self.assertTrue(
'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
' - K1000000 - successful schoolfee payment: %s'
% self.orderId in logcontent)
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'main.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.anybody - PaymentNotificationListenerWebservice called: '
'[{"rrr": "%s", "orderRef": "%s"}]'
% (self.rrr, self.orderId) in logcontent)
return
class RemitaTestsWebserviceApplicant(ApplicantsFullSetup):
"""Tests for the Remita payment gateway.
"""
layer = FunctionalLayer
merchantId = '2547916'
serviceTypeId = '4430731'
api_key = '1946'
responseurl = 'http://xxxx'
host = 'www.remitademo.net'
# successful transaction
# (hopefully this transaction remains in the Remita database)
orderId = '3456346346'
rrr = u'280007640804'
amount = 1000.0
@external_test
def test_payment_notification_listener_applicant(self):
self.applicantscontainer.application_fee = self.amount
payment = createObject('waeup.ApplicantOnlinePayment')
payment.p_category = u'application'
payment.p_session = self.applicantscontainer.year
payment.p_item = u'My Certificate'
payment.p_id = self.orderId
payment.amount_auth = self.amount
self.applicant['anykey'] = payment
IWorkflowState(self.applicant).setState('started')
# Send POST request
data = [{'orderRef': self.orderId, 'rrr': self.rrr},]
self.browser.post('http://localhost/app/paymentnotificationlistener',
json.dumps(data), 'application/json; charset=utf-8')
self.assertEqual('1 (1)', self.browser.contents)
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'applicants.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
' - %s - valid callback for application payment %s: '
% (self.applicant.applicant_id, self.orderId) in logcontent)
self.assertTrue(
'zope.anybody - kofacustom.nigeria.remita.webservices.PaymentNotificationListenerWebservice'
' - %s - successful payment: %s'
% (self.applicant.applicant_id, self.orderId) in logcontent)
return
class RemitaTestsApplicants(ApplicantsFullSetup):
"""Tests for the Remita payment gateway.
"""
layer = FunctionalLayer
# successful transaction
# (hopefully this transaction remains in the Remita database)
#orderId = '3456346346'
rrr = u'280007640804'
#amount = 1000.0
def setUp(self):
super(RemitaTestsApplicants, self).setUp()
configuration = SessionConfiguration()
configuration.academic_session = datetime.now().year - 2
configuration.remita_enabled = True
self.app['configuration'].addSessionConfiguration(configuration)
self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
self.browser.open(self.manage_path)
#IWorkflowState(self.student).setState('started')
super(RemitaTestsApplicants, 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
@external_test
def test_applicant_remita_form(self):
# Manager can access Remita form
self.browser.getLink("Pay via Remita").click()
# The RRR has been retrieved
self.assertTrue('' % self.rrr
in self.browser.contents)
self.assertEqual(self.payment.r_pay_reference, self.rrr)
self.assertEqual(self.payment.r_company, 'remita')
# Retrieval has been logged
logfile = os.path.join(
self.app['datacenter'].storage, 'logs', 'applicants.log')
logcontent = open(logfile).read()
self.assertTrue(
'zope.mgr - kofacustom.nigeria.remita.applicantsbrowser.RemitaPageApplicant'
' - %s - RRR retrieved: %s'
% (self.applicant.applicant_id, self.rrr) in logcontent)
# Means of testing end here.
return