Skip to content

Commit 55dd715

Browse files
committed
Merge pull request AuthorizeNet#13 from krgupta1/master
Modification to properties - Thanks Kriti
2 parents 44c2903 + 55dbed3 commit 55dd715

File tree

5 files changed

+188
-76
lines changed

5 files changed

+188
-76
lines changed

authorizenet/apicontrollersbase.py

Lines changed: 84 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@
55
'''
66
import abc
77
import logging
8-
import os
9-
from os.path import expanduser
10-
11-
import sys
128
import xml.dom.minidom
13-
9+
import ConfigParser
10+
from ConfigParser import SafeConfigParser
1411
from pip._vendor import requests
1512
from _pyio import __metaclass__
16-
from ConfigParser import SafeConfigParser
17-
import ConfigParser
1813

1914
from authorizenet.constants import constants
2015
from authorizenet import apicontractsv1
21-
16+
from authorizenet import utility
17+
'''
18+
from authorizenet.apicontractsv1 import merchantAuthenticationType
19+
from authorizenet.apicontractsv1 import ANetApiRequest
20+
from authorizenet.apicontractsv1 import ANetApiResponse
21+
'''
2222
class APIOperationBaseInterface(object):
2323

2424
__metaclass__ = abc.ABCMeta
@@ -68,49 +68,38 @@ def beforeexecute(self):
6868

6969
class APIOperationBase(APIOperationBaseInterface):
7070
__metaclass__ = abc.ABCMeta
71-
72-
parser = SafeConfigParser({"http":"","https":"","ftp":""})
73-
74-
75-
try:
76-
home = os.path.expanduser("~")
77-
homedirpropertiesfilename = os.path.join(home, "anet_python_sdk_properties.ini")
78-
79-
currdir = os.getcwd()
80-
currdirpropertiesfilename = os.path.join(currdir, "anet_python_sdk_properties.ini")
8171

82-
if (os.path.exists(homedirpropertiesfilename)):
83-
parser.read(homedirpropertiesfilename)
84-
elif (os.path.exists(currdirpropertiesfilename)):
85-
parser.read(currdirpropertiesfilename)
86-
else :
87-
print "you do not have anet_python_sdk_properties.ini file neither in home nor in current working directory"
88-
except IOError, error:
89-
sys.exit( error)
90-
else:
91-
logFile = parser.get("properties", "logfilename")
92-
#TODO format and level in config file
93-
logging.basicConfig(filename=logFile, level=logging.DEBUG, format='%(asctime)s %(message)s')
94-
endpoint = constants.SANDBOX_TESTMODE
72+
__initialized = "False"
73+
__merchantauthentication = "null"
74+
75+
@staticmethod
76+
def __classinitialized():
77+
return APIOperationBase.__initialized
9578

9679
@abc.abstractmethod
9780
def validaterequest(self):
9881
return
9982

10083
def validate(self):
101-
#add validation on merchant authentication #TODO
102-
#if ( "null" != authorizenet.apicontractsv1.merchantAuthenticationType.sessionToken)
103-
# raise ValueError("SessionToken needs to be null")
104-
'''
105-
if ( "null" != apicontractsv1.merchantAuthenticationType.__password.value)
106-
raise ValueError('Password needs to be null')
107-
if ( null != merchantAuthenticationType.getMobileDeviceId())
108-
throw new IllegalArgumentException("MobileDeviceId needs to be null");
109-
ImpersonationAuthenticationType impersonationAuthenticationType = merchantAuthenticationType.getImpersonationAuthentication();
110-
if ( null != impersonationAuthenticationType)
111-
throw new IllegalArgumentException("ImpersonationAuthenticationType needs to be null");
84+
anetapirequest = self._getrequest()
85+
86+
#self.validateandsetmerchantauthentication()
11287
'''
113-
self.validaterequest()
88+
# make sure proper authentication elements are present and no extra elements are present
89+
merchantauthenticationtype = anetapirequest.merchantauthentication()
90+
if (merchantauthenticationtype.sessionToken != "null"):
91+
raise ValueError('sessionToken needs to be null')
92+
if (merchantauthenticationtype.password != "null"):
93+
raise ValueError('Password needs to be null')
94+
if (merchantauthenticationtype.mobileDeviceId != "null"):
95+
raise ValueError('MobileDeviceId needs to be null')
96+
97+
impersonationauthenticationtype = merchantauthenticationtype.impersonationAuthentication
98+
if (impersonationauthenticationtype != "null"):
99+
raise ValueError('ImpersonationAuthenticationType needs to be null')
100+
'''
101+
self.validaterequest()
102+
114103
return
115104

116105
def _getrequest(self): #protected method
@@ -134,15 +123,17 @@ def getprettyxmlrequest(self):
134123
return requestDom
135124

136125
def execute(self):
126+
self.endpoint = constants.SANDBOX_TESTMODE
137127
logging.debug('Executing http post to url: %s', self.endpoint)
138128

139129
self.beforeexecute()
140-
141-
proxyDictionary = {'http' : self.parser.get("properties", "http"),
142-
'https' : self.parser.get("properties" , "https"),
143-
'ftp' : self.parser.get("properties", "ftp")}
144130

131+
proxyDictionary = {'http' : utility.helper.getproperty("http"),
132+
'https' : utility.helper.getproperty("https"),
133+
'ftp' : utility.helper.getproperty("ftp")}
134+
145135
#requests is http request
136+
146137
try:
147138
xmlRequest = self.buildrequest()
148139
self._httpResponse = requests.post(self.endpoint, data=xmlRequest, headers=constants.headers, proxies=proxyDictionary)
@@ -172,24 +163,47 @@ def execute(self):
172163
logging.debug('Error retrieving response for request: %s' % self._request)
173164
else:
174165
print "Did not receive http response"
166+
return
175167

176168
def getresponse(self):
177169
return self._response
178170

179171
def getresultcode(self):
172+
resultcode = 'null'
180173
if self._response:
181-
return self._response.resultCode
174+
resultcode = self._response.resultCode
175+
return resultcode
182176

183177
def getmessagetype(self):
178+
message = 'null'
184179
if self._response:
185-
return self._response.message
180+
message = self._response.message
181+
return message
186182

187183
def afterexecute(self ):
188184
return
189185

190186
def beforeexecute(self):
191187
return
192-
188+
189+
@staticmethod
190+
def getmerchantauthentication(self):
191+
return self.__merchantauthentication
192+
193+
@staticmethod
194+
def setmerchantauthentication(merchantauthentication):
195+
APIOperationBase.__merchantauthentication = merchantauthentication
196+
return
197+
198+
def validateandsetmerchantauthentication(self):
199+
anetapirequest = apicontractsv1.ANetApiRequest()
200+
if (anetapirequest.getmerchantauthentication() == "null"):
201+
if (self.getmerchantauthentication() != "null"):
202+
anetapirequest.setmerchantauthentication(self.getmerchantauthentication())
203+
else:
204+
raise ValueError('Merchant Authentication can not be null')
205+
return
206+
193207
def __init__(self, apiRequest):
194208
self._httpResponse = "null"
195209
self._request = "null"
@@ -198,9 +212,27 @@ def __init__(self, apiRequest):
198212

199213
if "null" == apiRequest:
200214
raise ValueError('Input request cannot be null')
201-
#TOdo null check for types
202-
215+
203216
self._request = apiRequest
217+
__merchantauthentication = apicontractsv1.merchantAuthenticationType()
218+
219+
APIOperationBase.setmerchantauthentication(__merchantauthentication)
220+
221+
if ( 'False' == APIOperationBase.__classinitialized()):
222+
loggingfilename = utility.helper.getpropertyfile()
223+
logginglevel = utility.helper.getproperty("executionlogginglevel")
224+
225+
#print ("logging level %s" %logginglevel)
226+
227+
228+
if ("null" == loggingfilename):
229+
loggingfilename = constants.defaultLogFileName
230+
if ("null" == logginglevel):
231+
logginglevel = constants.defaultLoggingLevel
232+
233+
logging.basicConfig(filename=loggingfilename, level=logginglevel, format=constants.defaultlogformat)
234+
__initialized = "True"
235+
204236
self.validate()
205237

206238
return

authorizenet/constants.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
44
@author: egodolja
55
'''
6+
import logging
7+
68
class constants(object):
79
"""All the constants are defined here
810
Define all your constants instead of using magic numbers in the
@@ -40,3 +42,15 @@ class constants(object):
4042

4143
'''ns namespace 2'''
4244
nsNamespace2 = ':ns1'
45+
46+
'''default log file name'''
47+
defaultLogFileName = "anetsdk.log"
48+
49+
'''default logging level'''
50+
#defaultLoggingLevel = logging.WARNING
51+
defaultLoggingLevel = logging.DEBUG
52+
53+
'''default log format'''
54+
defaultlogformat = '%(asctime)s %(message)s'
55+
56+
'''eof'''

authorizenet/utility.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'''
2+
Created on Nov 4, 2015
3+
4+
@author: krgupta
5+
'''
6+
7+
from ConfigParser import SafeConfigParser
8+
'''import ConfigParser'''
9+
import os
10+
'''import logging'''
11+
#from authorizenet.constants import constants
12+
13+
class helper():
14+
__parser = SafeConfigParser({"http":"","https":"","ftp":""})
15+
__propertyfilename = "null"
16+
17+
__initialized = 'False'
18+
19+
@staticmethod
20+
def getpropertyfile():
21+
return helper.__propertyfilename
22+
23+
@staticmethod
24+
def getparser():
25+
return helper.__parser
26+
27+
@staticmethod
28+
def setpropertyfile(propertyfilename):
29+
if (propertyfilename == 'null' or os.path.isfile(propertyfilename) == 'False'):
30+
raise ValueError('properties '%propertyfilename%' file not found')
31+
32+
helper.__propertyfilename = propertyfilename
33+
return
34+
35+
@staticmethod
36+
def __classinitialized():
37+
return helper.__initialized
38+
39+
@staticmethod
40+
def getproperty(propertyname):
41+
42+
if ( 'False' == helper.__classinitialized()):
43+
helper.getparser().read(helper.__propertyfilename)
44+
__initialized = 'True'
45+
46+
stringvalue = "null"
47+
if ("null" != helper.getparser()):
48+
stringvalue = helper.getparser().get("properties", propertyname)
49+
else :
50+
print (" property file does not exist, will read from environment")
51+
stringvalue = os.getenv[propertyname]
52+
53+
return stringvalue
54+
55+
@staticmethod
56+
def setproperty(propertyname):
57+
helper.getparser().add_option("properties", propertyname)
58+
return

tests/anet_python_sdk_properties.ini

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[properties]
2+
3+
#sandbox cradentials
4+
api.login.id : 6rF76h2U93AL
5+
transaction.key : 7jh86zEUhy7228FG
6+
md5.hash.key : MD5_HASH_KEY
7+
8+
#log
9+
logfilename : logFile.log
10+
11+
#proxy setup
12+
http://internet.visa.com:80
13+
https://internet.visa.com:443
14+
15+
#environments
16+
sandbox : https://apitest.authorize.net/xml/v1/request.api
17+
production : https://api.authorize.net/xml/v1/request.api
18+
19+
#level
20+
executionlogginglevel : WARNING

tests/apitestbase.py

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,41 +5,29 @@
55
'''
66

77
import unittest
8-
import os
9-
from ConfigParser import SafeConfigParser
10-
from authorizenet import apicontractsv1
11-
from authorizenet.apicontractsv1 import CTD_ANON
128
import datetime
139
from decimal import *
1410
import random
1511
import test
1612

13+
from ConfigParser import SafeConfigParser
14+
from authorizenet import apicontractsv1, apicontrollersbase
15+
from authorizenet.utility import *
16+
from authorizenet.apicontractsv1 import CTD_ANON
17+
from authorizenet import utility
18+
1719
class ApiTestBase(unittest.TestCase):
1820

1921
def setUp(self):
20-
self.amount = str(round(random.random()*100, 2))
21-
parser = SafeConfigParser()
22-
home = os.path.expanduser("~")
23-
homedirpropertiesfilename = os.path.join(home, "anet_python_sdk_properties.ini")
22+
utility.helper.setpropertyfile( 'anet_python_sdk_properties.ini')
2423

25-
currdir = os.getcwd()
26-
currdirpropertiesfilename = os.path.join(currdir, "anet_python_sdk_properties.ini")
27-
28-
if (os.path.exists(homedirpropertiesfilename)):
29-
parser.read(homedirpropertiesfilename)
30-
elif (os.path.exists(currdirpropertiesfilename)):
31-
parser.read(currdirpropertiesfilename)
32-
else :
33-
print "you do not have anet_python_sdk_properties.ini file neither in home nor in current working directory"
34-
35-
self.api_login_id = parser.get("properties", "api.login.id")
36-
self.transaction_key = parser.get("properties", "transaction.key")
24+
self.amount = str(round(random.random()*100, 2))
25+
26+
self.merchantAuthentication = apicontractsv1.merchantAuthenticationType()
27+
self.merchantAuthentication.name = helper.getproperty('api.login.id')
28+
self.merchantAuthentication.transactionKey = helper.getproperty('transaction.key')
3729
self.ref_id = 'Sample'
3830

39-
self.merchantAuthentication = apicontractsv1.merchantAuthenticationType()
40-
self.merchantAuthentication.name = self.api_login_id
41-
self.merchantAuthentication.transactionKey = self.transaction_key
42-
4331
self.dateOne = datetime.date(2020, 8, 30)
4432
self.interval = CTD_ANON()
4533
self.interval.length = 1

0 commit comments

Comments
 (0)