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

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

Use IPayer adapter.

  • Property svn:keywords set to Id
File size: 18.7 KB
Line 
1## $Id: tests.py 16528 2021-07-06 05:52:21Z 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
19import random
20from datetime import datetime, timedelta, date
21from zope.component import createObject, getUtility
22from zope.catalog.interfaces import ICatalog
23from xml.dom.minidom import parseString
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
28from waeup.kofa.students.payments import StudentOnlinePayment
29from waeup.kofa.browser.tests.test_pdf import samples_dir
30from kofacustom.nigeria.interswitch.helpers import (
31    query_interswitch, get_SOAP_response_paydirect, SOAP_post,
32    create_paydirect_booking
33    )
34from kofacustom.nigeria.testing import FunctionalLayer
35
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.
39EXTERNAL_TESTS_1 = True
40EXTERNAL_TESTS_2 = True
41
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:
48        myself = __file__
49        if myself.endswith('.pyc'):
50            myself = myself[:-1]
51        print "WARNING: external tests are skipped!"
52        print "WARNING: edit %s to enable them." % myself
53        return
54    return func
55
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
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)
83        self.browser.open(self.payments_path)
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)
89        self.assertTrue('<span>40000.0</span>', self.browser.contents)
90        self.payment_url = self.browser.url
91        self.payment = self.student['payments'][self.value]
92
93    def test_interswitch_form(self):
94        # Manager can access InterswitchForm
95        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
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(
102            '...<input type="hidden" name="amount" value="4000000" />...',
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()
116        self.browser.open(self.payments_path)
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()
122        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
123        # Split amounts have been set.
124        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
125        self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
126        self.assertMatches('...<input type="hidden" name="pay_item_id" />...',
127                           self.browser.contents)
128        self.assertTrue(
129            '<input type="hidden" name="amount" value="2030000" />' in
130            self.browser.contents)
131
132    def test_interswitch_form_ticket_expired(self):
133        # Manager can access InterswitchForm
134        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
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')
140        self.assertTrue(
141            '<input type="hidden" name="amount" value="4030000" />' in
142            self.browser.contents)
143        delta = timedelta(days=8)
144        self.payment.creation_date -= delta
145        self.browser.open(self.payment_url)
146        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
147        self.assertMatches(
148            '...This payment ticket is too old. Please create a new ticket...',
149            self.browser.contents)
150        delta = timedelta(days=2)
151        self.payment.creation_date += delta
152        self.browser.open(self.payment_url)
153        self.browser.getLink("Pay via Interswitch CollegePAY").click()
154        self.assertMatches('...Total Amount Authorized:...',
155                           self.browser.contents)
156
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 :-/
161        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
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)
168        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
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)
175        self.browser.getLink("Pay via Interswitch CollegePAY").click()
176        self.assertMatches('...Total Amount Authorized:...',
177                           self.browser.contents)
178
179    @external_test_1
180    def test_query_interswitch_SOAP(self):
181        host = 'webpay.interswitchng.com'
182        url = '/paydirect/services/TransactionQueryWs.asmx'
183        https = True
184        mac = None
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(
190            payment, product_id, host, url, https, mac, False)
191        self.assertEqual('Successful callback received.', msg)
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
197    @external_test_1
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(
208            payment, product_id, host, url, https, mac, False)
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(
214            payment, product_id, host, url, https, mac, False)
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
230# PAYDirect tests
231
232    @external_test_2
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
240        self.student['payments'][payment.p_id] = payment
241        result_xml = create_paydirect_booking(
242            MERCHANT_ID, payment, PAYDIRECT_HOST, PAYDIRECT_URL, True)
243        result_xml = get_SOAP_response_paydirect(
244            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
245        doc=parseString(result_xml)
246        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
247        amount=doc.getElementsByTagName('Amount')[0].firstChild
248        self.assertEqual(status, 'Pending')
249        self.assertEqual(amount, None)
250        p_id = 'p5812734587097'
251        result_xml = get_SOAP_response_paydirect(MERCHANT_ID, p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
252        doc=parseString(result_xml)
253        self.assertEqual(doc.getElementsByTagName('PaymentStatus'), [])
254
255    @external_test_2
256    def test_paydirect_pending(self):
257        # Manager can access InterswitchForm
258        self.browser.getLink("Pay via Interswitch PAYDirect").click()
259        self.assertMatches('...Total Amount Authorized:...',
260                           self.browser.contents)
261        self.assertEqual(self.student.current_mode, 'ug_ft')
262        # Create school fee ticket for returning students. Payment is made
263        # for next session.
264        current_payment_key = self.student['payments'].keys()[0]
265        self.certificate.study_mode = u'ug_pt'
266        IWorkflowState(self.student).setState('returning')
267        configuration = createObject('waeup.SessionConfiguration')
268        configuration.academic_session = 2005
269        self.app['configuration'].addSessionConfiguration(configuration)
270        self.browser.open(self.payments_path + '/addop')
271        self.browser.getControl(name="form.p_category").value = ['schoolfee']
272        self.browser.getControl("Create ticket").click()
273        self.browser.open(self.payments_path)
274        ctrl = self.browser.getControl(name='val_id')
275        value = ctrl.options[1]
276        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
277        self.assertEqual(self.student['payments'][value].gateway_amt, 0.0)
278        self.browser.getLink(value).click()
279        self.browser.getLink("Pay via Interswitch PAYDirect").click()
280        # Split amounts have been set.
281        self.assertEqual(self.student['payments'][value].provider_amt, 0.0)
282        self.assertEqual(self.student['payments'][value].gateway_amt, 300.0)
283        ref_number = '%s%s' % (MERCHANT_ID,value[1:])
284        self.assertTrue(ref_number in self.browser.contents)
285        self.assertEqual(self.student['payments'][value].r_pay_reference, None)
286        self.browser.getControl("Requery").click()
287        self.assertTrue('pending' in self.browser.contents)
288        # Reference number has been saved
289        self.assertEqual(self.student['payments'][value].r_pay_reference, ref_number)
290        # Students can download reference number slip
291        self.browser.getLink("Pay via Interswitch PAYDirect").click()
292        self.browser.getLink("Download reference number slip").click()
293        self.assertEqual(self.browser.headers['Status'], '200 Ok')
294        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
295        path = os.path.join(samples_dir(), 'refnumberslip.pdf')
296        open(path, 'wb').write(self.browser.contents)
297        print "Sample PDF refnumberslip.pdf written to %s" % path
298
299    @external_test_2
300    def test_paydirect_completed(self):
301        payment = createObject('waeup.StudentOnlinePayment')
302        payment.p_category = u'schoolfee'
303        payment.p_session = self.student.current_session
304        payment.p_item = u'My Certificate'
305        # p6214352306153 has been manually set completed by Interswitch
306        payment.p_id = u'p6214352306153'
307        payment.amount_auth = 10.0 # 300 will be added
308        self.student['payments'][payment.p_id] = payment
309        result_xml = get_SOAP_response_paydirect(
310            MERCHANT_ID, payment.p_id, PAYDIRECT_HOST, PAYDIRECT_URL, True)
311        doc=parseString(result_xml)
312        status=doc.getElementsByTagName('PaymentStatus')[0].firstChild.data
313        refnumber=doc.getElementsByTagName('ReferenceNumber')[0].firstChild.data
314        amount=float(doc.getElementsByTagName('Amount')[0].firstChild.data)
315        self.assertEqual(status, 'Completed')
316        self.assertEqual(amount, 1000)
317        self.assertEqual(refnumber, '60336214352306153')
318        # Now we login and check what will happen with the student after payment
319        self.browser.open(self.payments_path)
320        self.browser.getLink(payment.p_id).click()
321        self.browser.getLink("Pay via Interswitch PAYDirect").click()
322        # 300 has been added
323        self.assertEqual(payment.amount_auth, 310)
324        self.assertEqual(payment.net_amt, 10)
325        # Reference number has been saved
326        self.browser.getControl("Requery").click()
327        self.assertEqual(
328            self.student['payments'][payment.p_id].r_pay_reference, '60336214352306153')
329        # Payment is made
330        self.assertEqual(
331            self.student['payments'][payment.p_id].p_state, 'paid')
332        # Rubbish has been stored too
333        self.assertTrue(
334            self.student['payments'][payment.p_id].r_desc.startswith('Channel Name: Bank Branc'))
335        logfile = os.path.join(
336            self.app['datacenter'].storage, 'logs', 'students.log')
337        logcontent = open(logfile).read()
338        self.assertTrue(
339            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
340            '- K1000000 - valid callback for schoolfee payment %s: Completed' % payment.p_id in logcontent)
341        self.assertTrue(
342            'zope.mgr - K1000000 - First school fee payment made' in logcontent)
343        self.assertTrue(
344            'zope.mgr - kofacustom.nigeria.interswitch.paydirectbrowser.PAYDirectPageStudent '
345            '- K1000000 - successful schoolfee payment: %s' % payment.p_id in logcontent)
346
347class InterswitchTestsApplicants(ApplicantsFullSetup):
348    """Tests for the Interswitch payment gateway.
349    """
350
351    layer = FunctionalLayer
352
353    def setUp(self):
354        super(InterswitchTestsApplicants, self).setUp()
355        configuration = SessionConfiguration()
356        configuration.academic_session = datetime.now().year - 2
357        self.app['configuration'].addSessionConfiguration(configuration)
358        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
359        self.browser.open(self.manage_path)
360        #IWorkflowState(self.student).setState('started')
361        super(InterswitchTestsApplicants, self).fill_correct_values()
362        self.applicantscontainer.application_fee = 1000.0
363        self.browser.getControl(name="form.nationality").value = ['NG']
364        self.browser.getControl(name="transition").value = ['start']
365        self.browser.getControl("Save").click()
366        self.browser.getControl("Add online").click()
367        self.assertMatches('...ticket created...',
368                           self.browser.contents)
369        self.payment = self.applicant.values()[0]
370        self.payment_url = self.browser.url
371
372    def test_interswitch_form(self):
373        self.assertMatches('...Amount Authorized...',
374                           self.browser.contents)
375        self.assertMatches(
376            '...<span>1000.0</span>...',
377            self.browser.contents)
378        # Manager can access InterswitchForm
379        self.browser.getLink("Pay via Interswitch CollegePAY", index=0).click()
380        self.assertMatches('...Total Amount Authorized:...',
381                           self.browser.contents)
382        self.assertMatches(
383            '...<input type="hidden" name="amount" value="100000" />...',
384            self.browser.contents)
385        delta = timedelta(days=8)
386        self.payment.creation_date -= delta
387        self.browser.open(self.payment_url)
388        self.browser.getLink("Pay via Interswitch", index=0).click()
389        self.assertMatches(
390            '...This payment ticket is too old. Please create a new ticket...',
391            self.browser.contents)
392        delta = timedelta(days=2)
393        self.payment.creation_date += delta
394        self.browser.getLink("Pay via Interswitch", index=0).click()
395        self.assertMatches('...Total Amount Authorized:...',
396                           self.browser.contents)
Note: See TracBrowser for help on using the repository browser.