source: main/kofacustom.nigeria/trunk/src/kofacustom/nigeria/interswitch/tests.py @ 16827

Last change on this file since 16827 was 16587, checked in by Henrik Bettermann, 3 years ago

Set constant item_code.

  • Property svn:keywords set to Id
File size: 18.9 KB
RevLine 
[11640]1## $Id: tests.py 16587 2021-08-31 06:28:35Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18import os
[16487]19import random
[12973]20from datetime import datetime, timedelta, date
[11640]21from zope.component import createObject, getUtility
22from zope.catalog.interfaces import ICatalog
[16484]23from xml.dom.minidom import parseString
[11640]24from hurry.workflow.interfaces import IWorkflowState
25from waeup.kofa.students.tests.test_browser import StudentsFullSetup
26from waeup.kofa.applicants.tests.test_browser import ApplicantsFullSetup
27from waeup.kofa.configuration import SessionConfiguration
[13386]28from waeup.kofa.students.payments import StudentOnlinePayment
[16484]29from waeup.kofa.browser.tests.test_pdf import samples_dir
30from kofacustom.nigeria.interswitch.helpers import (
[16487]31    query_interswitch, get_SOAP_response_paydirect, SOAP_post,
32    create_paydirect_booking
33    )
[11640]34from kofacustom.nigeria.testing import FunctionalLayer
35
[13386]36# Also run tests that send requests to external servers?
37#   If you enable this, please make sure the external services
38#   do exist really and are not bothered by being spammed by a test programme.
[16484]39EXTERNAL_TESTS_1 = True
40EXTERNAL_TESTS_2 = True
[13386]41
[16484]42PAYDIRECT_HOST = 'sandbox.interswitchng.com'
43PAYDIRECT_URL = '/bookonhold/bookonhold.asmx'
44MERCHANT_ID = '6033'
45
46def external_test_1(func):
47    if not EXTERNAL_TESTS_1:
[13386]48        myself = __file__
49        if myself.endswith('.pyc'):
[14737]50            myself = myself[:-1]
[13386]51        print "WARNING: external tests are skipped!"
52        print "WARNING: edit %s to enable them." % myself
53        return
54    return func
55
[16484]56def external_test_2(func):
57    if not EXTERNAL_TESTS_2:
58        myself = __file__
59        if myself.endswith('.pyc'):
60            myself = myself[:-1]
61        print "WARNING: external tests are skipped!"
62        print "WARNING: edit %s to enable them." % myself
63        return
64    return func
65
[11640]66class InterswitchTestsStudents(StudentsFullSetup):
67    """Tests for the Interswitch payment gateway.
68    """
69
70    layer = FunctionalLayer
71
72    def setUp(self):
73        super(InterswitchTestsStudents, self).setUp()
74        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
75        self.browser.open(self.payments_path)
76        IWorkflowState(self.student).setState('cleared')
77        self.student.nationality = u'NG'
78        self.browser.open(self.payments_path + '/addop')
79        self.browser.getControl(name="form.p_category").value = ['schoolfee']
80        self.browser.getControl("Create ticket").click()
81        self.assertMatches('...ticket created...',
82                           self.browser.contents)
[16378]83        self.browser.open(self.payments_path)
[11640]84        ctrl = self.browser.getControl(name='val_id')
85        self.value = ctrl.options[0]
86        self.browser.getLink(self.value).click()
87        self.assertMatches('...Amount Authorized...',
88                           self.browser.contents)
[13386]89        self.assertTrue('<span>40000.0</span>', self.browser.contents)
[11640]90        self.payment_url = self.browser.url
[12973]91        self.payment = self.student['payments'][self.value]
[11640]92
93    def test_interswitch_form(self):
94        # Manager can access InterswitchForm
[16484]95        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[11640]96        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
97                           self.browser.contents)
98        self.assertMatches('...Total Amount Authorized:...',
99                           self.browser.contents)
100        self.assertEqual(self.student.current_mode, 'ug_ft')
101        self.assertMatches(
[11767]102            '...<input type="hidden" name="amount" value="4000000" />...',
[11640]103            self.browser.contents)
104
105        # Create school fee ticket for returning students. Payment is made
106        # for next session.
107        current_payment_key = self.student['payments'].keys()[0]
108        self.certificate.study_mode = u'ug_pt'
109        IWorkflowState(self.student).setState('returning')
110        configuration = createObject('waeup.SessionConfiguration')
111        configuration.academic_session = 2005
112        self.app['configuration'].addSessionConfiguration(configuration)
113        self.browser.open(self.payments_path + '/addop')
114        self.browser.getControl(name="form.p_category").value = ['schoolfee']
115        self.browser.getControl("Create ticket").click()
[16378]116        self.browser.open(self.payments_path)
[11640]117        ctrl = self.browser.getControl(name='val_id')
118        value = ctrl.options[1]
119        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
120        self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
121        self.browser.getLink(value).click()
[16484]122        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[11640]123        # Split amounts have been set.
124        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
[15755]125        self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
[11640]126        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
127                           self.browser.contents)
[15755]128        self.assertTrue(
129            '<input type="hidden" name="amount" value="2030000" />' in
[11640]130            self.browser.contents)
131
[12973]132    def test_interswitch_form_ticket_expired(self):
133        # Manager can access InterswitchForm
[16484]134        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[12973]135        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
136                           self.browser.contents)
137        self.assertMatches('...Total Amount Authorized:...',
138                           self.browser.contents)
139        self.assertEqual(self.student.current_mode, 'ug_ft')
[15755]140        self.assertTrue(
141            '<input type="hidden" name="amount" value="4030000" />' in
[12973]142            self.browser.contents)
[13015]143        delta = timedelta(days=8)
[12973]144        self.payment.creation_date -= delta
145        self.browser.open(self.payment_url)
[16484]146        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[12973]147        self.assertMatches(
148            '...This payment ticket is too old. Please create a new ticket...',
149            self.browser.contents)
[13015]150        delta = timedelta(days=2)
[12973]151        self.payment.creation_date += delta
152        self.browser.open(self.payment_url)
[16484]153        self.browser.getLink("Pay via Interswitch CollegePAY").click()
[12973]154        self.assertMatches('...Total Amount Authorized:...',
155                           self.browser.contents)
156
[13477]157    def test_interswitch_form_ticket_expired_tz(self):
158        # The form copes with timezones when calculating expirements.
159        # We should not have TZ data in timestamps processed, but it looks
160        # like we get some with imports :-/
[16484]161        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[13477]162        delta = timedelta(days=8)
163        self.payment.creation_date -= delta
164        from pytz import timezone
165        self.payment.creation_date = timezone("Europe/Berlin").localize(
166            self.payment.creation_date)
167        self.browser.open(self.payment_url)
[16484]168        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[13477]169        self.assertMatches(
170            '...This payment ticket is too old. Please create a new ticket...',
171            self.browser.contents)
172        delta = timedelta(days=2)
173        self.payment.creation_date += delta
174        self.browser.open(self.payment_url)
[16484]175        self.browser.getLink("Pay via Interswitch CollegePAY").click()
[13477]176        self.assertMatches('...Total Amount Authorized:...',
177                           self.browser.contents)
178
[16484]179    @external_test_1
[13387]180    def test_query_interswitch_SOAP(self):
[13386]181        host = 'webpay.interswitchng.com'
182        url = '/paydirect/services/TransactionQueryWs.asmx'
183        https = True
[13387]184        mac = None
[13386]185        product_id = '5845' # AAUE regular
186        payment = StudentOnlinePayment()
187        payment.p_id ='p4465649308559'
188        payment.amount_auth = 60250.0
189        success, msg, log = query_interswitch(
[16115]190            payment, product_id, host, url, https, mac, False)
191        self.assertEqual('Successful callback received.', msg)
[13386]192        self.assertTrue(success)
193        self.assertTrue(
194            '00:Approved Successful:6025000:3154:p4465649308559:'
195            'ZIB|WEB|ABAL|3-11-2015|021336:000457580882' in log)
196
[16484]197    @external_test_1
[13387]198    def test_query_interswitch_JSON(self):
199        host = 'webpay.interswitchng.com'
200        url = '/paydirect/api/v1/gettransaction.json'
201        mac = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
202        https = True
203        product_id = '5845' # AAUE regular
204        payment = StudentOnlinePayment()
205        payment.p_id ='p4465649308559'
206        payment.amount_auth = 1.0
207        success, msg, log = query_interswitch(
[16115]208            payment, product_id, host, url, https, mac, False)
[13387]209        self.assertFalse(success)
210        self.assertTrue('Unsuccessful callback:' in msg)
211        self.assertTrue('Amount Inconsistency' in log)
212        payment.amount_auth = 60250.0
213        success, msg, log = query_interswitch(
[16115]214            payment, product_id, host, url, https, mac, False)
[13387]215        self.assertEqual('Successful callback received', msg)
216        self.assertTrue(success)
217        self.assertTrue(
218            "{u'SplitAccounts': [], "
219            "u'MerchantReference': u'p4465649308559', "
220            "u'PaymentReference': u'ZIB|WEB|ABAL|3-11-2015|021336', "
221            "u'TransactionDate': u'2015-11-03T16:40:54.487', "
222            "u'RetrievalReferenceNumber': u'000457580882', "
223            "u'ResponseDescription': u'Approved Successful', "
224            "u'Amount': 6025000, "
225            "u'CardNumber': u'3154', "
226            "u'ResponseCode': u'00', "
227            "u'LeadBankCbnCode': None, "
228            "u'LeadBankName': None}" in log)
229
[16484]230# PAYDirect tests
231
232    @external_test_2
[16487]233    def test_SOAP_paydirect(self):
234        payment = createObject('waeup.StudentOnlinePayment')
235        payment.p_category = u'schoolfee'
236        payment.p_session = self.student.current_session
237        payment.p_item = u'My Certificate'
238        payment.p_id = 'p' + str(random.randint(10000000000, 90000000000))
239        payment.amount_auth = 1000.0
[16587]240        item_code = '01'
[16487]241        self.student['payments'][payment.p_id] = payment
242        result_xml = create_paydirect_booking(
[16587]243            MERCHANT_ID, payment, item_code, PAYDIRECT_HOST, PAYDIRECT_URL, True)
[16484]244        result_xml = get_SOAP_response_paydirect(
[16487]245            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
[16484]246        doc=parseString(result_xml)
247        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
248        amount=doc.getElementsByTagName('Amount')[0].firstChild
249        self.assertEqual(status, 'Pending')
250        self.assertEqual(amount, None)
251        p_id = 'p5812734587097'
252        result_xml = get_SOAP_response_paydirect(MERCHANT_ID, p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
253        doc=parseString(result_xml)
254        self.assertEqual(doc.getElementsByTagName('PaymentStatus'), [])
255
256    @external_test_2
[16488]257    def test_paydirect_pending(self):
[16484]258        # Manager can access InterswitchForm
259        self.browser.getLink("Pay via Interswitch PAYDirect").click()
260        self.assertMatches('...Total Amount Authorized:...',
261                           self.browser.contents)
262        self.assertEqual(self.student.current_mode, 'ug_ft')
263        # Create school fee ticket for returning students. Payment is made
264        # for next session.
265        current_payment_key = self.student['payments'].keys()[0]
266        self.certificate.study_mode = u'ug_pt'
267        IWorkflowState(self.student).setState('returning')
268        configuration = createObject('waeup.SessionConfiguration')
269        configuration.academic_session = 2005
270        self.app['configuration'].addSessionConfiguration(configuration)
271        self.browser.open(self.payments_path + '/addop')
272        self.browser.getControl(name="form.p_category").value = ['schoolfee']
273        self.browser.getControl("Create ticket").click()
274        self.browser.open(self.payments_path)
275        ctrl = self.browser.getControl(name='val_id')
276        value = ctrl.options[1]
277        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
278        self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
279        self.browser.getLink(value).click()
280        self.browser.getLink("Pay via Interswitch PAYDirect").click()
281        # Split amounts have been set.
282        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
283        self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
284        ref_number = '%s%s' % (MERCHANT_ID,value[1:])
285        self.assertTrue(ref_number in self.browser.contents)
[16514]286        self.assertEqual(self.student['payments'][value].r_pay_reference, None)
[16484]287        self.browser.getControl("Requery").click()
288        self.assertTrue('pending' in self.browser.contents)
[16514]289        # Reference number has been saved
290        self.assertEqual(self.student['payments'][value].r_pay_reference, ref_number)
[16484]291        # Students can download reference number slip
292        self.browser.getLink("Pay via Interswitch PAYDirect").click()
293        self.browser.getLink("Download reference number slip").click()
294        self.assertEqual(self.browser.headers['Status'], '200 Ok')
295        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
296        path = os.path.join(samples_dir(), 'refnumberslip.pdf')
297        open(path, 'wb').write(self.browser.contents)
298        print "Sample PDF refnumberslip.pdf written to %s" % path
299
[16488]300    @external_test_2
301    def test_paydirect_completed(self):
302        payment = createObject('waeup.StudentOnlinePayment')
303        payment.p_category = u'schoolfee'
304        payment.p_session = self.student.current_session
305        payment.p_item = u'My Certificate'
[16528]306        # p6214352306153 has been manually set completed by Interswitch
[16488]307        payment.p_id = u'p6214352306153'
[16528]308        payment.amount_auth = 10.0 # 300 will be added
[16488]309        self.student['payments'][payment.p_id] = payment
310        result_xml = get_SOAP_response_paydirect(
311            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
312        doc=parseString(result_xml)
313        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
314        refnumber=doc.getElementsByTagName('ReferenceNumber')[0].firstChild.data
315        amount=float(doc.getElementsByTagName('Amount')[0].firstChild.data)
316        self.assertEqual(status, 'Completed')
[16528]317        self.assertEqual(amount, 1000)
[16488]318        self.assertEqual(refnumber, '60336214352306153')
319        # Now we login and check what will happen with the student after payment
320        self.browser.open(self.payments_path)
321        self.browser.getLink(payment.p_id).click()
322        self.browser.getLink("Pay via Interswitch PAYDirect").click()
323        # 300 has been added
[16528]324        self.assertEqual(payment.amount_auth, 310)
325        self.assertEqual(payment.net_amt, 10)
[16587]326
327        # Unfortunately the payment 60336214352306153 was done without surcharge.
328        # Therefore we have to deduct 300 again in this test.
329        payment.amount_auth = 10.0
330
[16488]331        # Reference number has been saved
332        self.browser.getControl("Requery").click()
333        self.assertEqual(
334            self.student['payments'][payment.p_id].r_pay_reference, '60336214352306153')
335        # Payment is made
336        self.assertEqual(
337            self.student['payments'][payment.p_id].p_state, 'paid')
338        # Rubbish has been stored too
339        self.assertTrue(
340            self.student['payments'][payment.p_id].r_desc.startswith('Channel Name: Bank Branc'))
341        logfile = os.path.join(
342            self.app['datacenter'].storage, 'logs', 'students.log')
343        logcontent = open(logfile).read()
344        self.assertTrue(
345            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
346            '- K1000000 - valid callback for schoolfee payment %s: Completed' % payment.p_id in logcontent)
347        self.assertTrue(
348            'zope.mgr - K1000000 - First school fee payment made' in logcontent)
349        self.assertTrue(
350            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
351            '- K1000000 - successful schoolfee payment: %s' % payment.p_id in logcontent)
352
[11640]353class InterswitchTestsApplicants(ApplicantsFullSetup):
354    """Tests for the Interswitch payment gateway.
355    """
356
357    layer = FunctionalLayer
358
359    def setUp(self):
360        super(InterswitchTestsApplicants, self).setUp()
361        configuration = SessionConfiguration()
362        configuration.academic_session = datetime.now().year - 2
363        self.app['configuration'].addSessionConfiguration(configuration)
364        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
365        self.browser.open(self.manage_path)
366        #IWorkflowState(self.student).setState('started')
367        super(InterswitchTestsApplicants, self).fill_correct_values()
368        self.applicantscontainer.application_fee = 1000.0
369        self.browser.getControl(name="form.nationality").value = ['NG']
370        self.browser.getControl(name="transition").value = ['start']
371        self.browser.getControl("Save").click()
372        self.browser.getControl("Add online").click()
373        self.assertMatches('...ticket created...',
374                           self.browser.contents)
[12973]375        self.payment = self.applicant.values()[0]
[11640]376        self.payment_url = self.browser.url
377
378    def test_interswitch_form(self):
379        self.assertMatches('...Amount Authorized...',
380                           self.browser.contents)
381        self.assertMatches(
382            '...<span>1000.0</span>...',
383            self.browser.contents)
384        # Manager can access InterswitchForm
[16484]385        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
[11640]386        self.assertMatches('...Total Amount Authorized:...',
387                           self.browser.contents)
388        self.assertMatches(
[11767]389            '...<input type="hidden" name="amount" value="100000" />...',
[11640]390            self.browser.contents)
[13015]391        delta = timedelta(days=8)
[12973]392        self.payment.creation_date -= delta
393        self.browser.open(self.payment_url)
[15702]394        self.browser.getLink("Pay via Interswitch", index=0).click()
[12973]395        self.assertMatches(
396            '...This payment ticket is too old. Please create a new ticket...',
397            self.browser.contents)
[13015]398        delta = timedelta(days=2)
[12973]399        self.payment.creation_date += delta
[15702]400        self.browser.getLink("Pay via Interswitch", index=0).click()
[12973]401        self.assertMatches('...Total Amount Authorized:...',
402                           self.browser.contents)
Note: See TracBrowser for help on using the repository browser.