Skip to content

modification to properties #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 9, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 84 additions & 52 deletions authorizenet/apicontrollersbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@
'''
import abc
import logging
import os
from os.path import expanduser

import sys
import xml.dom.minidom

import ConfigParser
from ConfigParser import SafeConfigParser
from pip._vendor import requests
from _pyio import __metaclass__
from ConfigParser import SafeConfigParser
import ConfigParser

from authorizenet.constants import constants
from authorizenet import apicontractsv1

from authorizenet import utility
'''
from authorizenet.apicontractsv1 import merchantAuthenticationType
from authorizenet.apicontractsv1 import ANetApiRequest
from authorizenet.apicontractsv1 import ANetApiResponse
'''
class APIOperationBaseInterface(object):

__metaclass__ = abc.ABCMeta
Expand Down Expand Up @@ -68,49 +68,38 @@ def beforeexecute(self):

class APIOperationBase(APIOperationBaseInterface):
__metaclass__ = abc.ABCMeta

parser = SafeConfigParser({"http":"","https":"","ftp":""})


try:
home = os.path.expanduser("~")
homedirpropertiesfilename = os.path.join(home, "anet_python_sdk_properties.ini")

currdir = os.getcwd()
currdirpropertiesfilename = os.path.join(currdir, "anet_python_sdk_properties.ini")

if (os.path.exists(homedirpropertiesfilename)):
parser.read(homedirpropertiesfilename)
elif (os.path.exists(currdirpropertiesfilename)):
parser.read(currdirpropertiesfilename)
else :
print "you do not have anet_python_sdk_properties.ini file neither in home nor in current working directory"
except IOError, error:
sys.exit( error)
else:
logFile = parser.get("properties", "logfilename")
#TODO format and level in config file
logging.basicConfig(filename=logFile, level=logging.DEBUG, format='%(asctime)s %(message)s')
endpoint = constants.SANDBOX_TESTMODE
__initialized = "False"
__merchantauthentication = "null"

@staticmethod
def __classinitialized():
return APIOperationBase.__initialized

@abc.abstractmethod
def validaterequest(self):
return

def validate(self):
#add validation on merchant authentication #TODO
#if ( "null" != authorizenet.apicontractsv1.merchantAuthenticationType.sessionToken)
# raise ValueError("SessionToken needs to be null")
'''
if ( "null" != apicontractsv1.merchantAuthenticationType.__password.value)
raise ValueError('Password needs to be null')
if ( null != merchantAuthenticationType.getMobileDeviceId())
throw new IllegalArgumentException("MobileDeviceId needs to be null");
ImpersonationAuthenticationType impersonationAuthenticationType = merchantAuthenticationType.getImpersonationAuthentication();
if ( null != impersonationAuthenticationType)
throw new IllegalArgumentException("ImpersonationAuthenticationType needs to be null");
anetapirequest = self._getrequest()

#self.validateandsetmerchantauthentication()
'''
self.validaterequest()
# make sure proper authentication elements are present and no extra elements are present
merchantauthenticationtype = anetapirequest.merchantauthentication()
if (merchantauthenticationtype.sessionToken != "null"):
raise ValueError('sessionToken needs to be null')
if (merchantauthenticationtype.password != "null"):
raise ValueError('Password needs to be null')
if (merchantauthenticationtype.mobileDeviceId != "null"):
raise ValueError('MobileDeviceId needs to be null')

impersonationauthenticationtype = merchantauthenticationtype.impersonationAuthentication
if (impersonationauthenticationtype != "null"):
raise ValueError('ImpersonationAuthenticationType needs to be null')
'''
self.validaterequest()

return

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

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

self.beforeexecute()

proxyDictionary = {'http' : self.parser.get("properties", "http"),
'https' : self.parser.get("properties" , "https"),
'ftp' : self.parser.get("properties", "ftp")}

proxyDictionary = {'http' : utility.helper.getproperty("http"),
'https' : utility.helper.getproperty("https"),
'ftp' : utility.helper.getproperty("ftp")}

#requests is http request

try:
xmlRequest = self.buildrequest()
self._httpResponse = requests.post(self.endpoint, data=xmlRequest, headers=constants.headers, proxies=proxyDictionary)
Expand Down Expand Up @@ -172,24 +163,47 @@ def execute(self):
logging.debug('Error retrieving response for request: %s' % self._request)
else:
print "Did not receive http response"
return

def getresponse(self):
return self._response

def getresultcode(self):
resultcode = 'null'
if self._response:
return self._response.resultCode
resultcode = self._response.resultCode
return resultcode

def getmessagetype(self):
message = 'null'
if self._response:
return self._response.message
message = self._response.message
return message

def afterexecute(self ):
return

def beforeexecute(self):
return


@staticmethod
def getmerchantauthentication(self):
return self.__merchantauthentication

@staticmethod
def setmerchantauthentication(merchantauthentication):
APIOperationBase.__merchantauthentication = merchantauthentication
return

def validateandsetmerchantauthentication(self):
anetapirequest = apicontractsv1.ANetApiRequest()
if (anetapirequest.getmerchantauthentication() == "null"):
if (self.getmerchantauthentication() != "null"):
anetapirequest.setmerchantauthentication(self.getmerchantauthentication())
else:
raise ValueError('Merchant Authentication can not be null')
return

def __init__(self, apiRequest):
self._httpResponse = "null"
self._request = "null"
Expand All @@ -198,9 +212,27 @@ def __init__(self, apiRequest):

if "null" == apiRequest:
raise ValueError('Input request cannot be null')
#TOdo null check for types


self._request = apiRequest
__merchantauthentication = apicontractsv1.merchantAuthenticationType()

APIOperationBase.setmerchantauthentication(__merchantauthentication)

if ( 'False' == APIOperationBase.__classinitialized()):
loggingfilename = utility.helper.getpropertyfile()
logginglevel = utility.helper.getproperty("executionlogginglevel")

#print ("logging level %s" %logginglevel)


if ("null" == loggingfilename):
loggingfilename = constants.defaultLogFileName
if ("null" == logginglevel):
logginglevel = constants.defaultLoggingLevel

logging.basicConfig(filename=loggingfilename, level=logginglevel, format=constants.defaultlogformat)
__initialized = "True"

self.validate()

return
14 changes: 14 additions & 0 deletions authorizenet/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

@author: egodolja
'''
import logging

class constants(object):
"""All the constants are defined here
Define all your constants instead of using magic numbers in the
Expand Down Expand Up @@ -40,3 +42,15 @@ class constants(object):

'''ns namespace 2'''
nsNamespace2 = ':ns1'

'''default log file name'''
defaultLogFileName = "anetsdk.log"

'''default logging level'''
#defaultLoggingLevel = logging.WARNING
defaultLoggingLevel = logging.DEBUG

'''default log format'''
defaultlogformat = '%(asctime)s %(message)s'

'''eof'''
58 changes: 58 additions & 0 deletions authorizenet/utility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'''
Created on Nov 4, 2015

@author: krgupta
'''

from ConfigParser import SafeConfigParser
'''import ConfigParser'''
import os
'''import logging'''
#from authorizenet.constants import constants

class helper():
__parser = SafeConfigParser({"http":"","https":"","ftp":""})
__propertyfilename = "null"

__initialized = 'False'

@staticmethod
def getpropertyfile():
return helper.__propertyfilename

@staticmethod
def getparser():
return helper.__parser

@staticmethod
def setpropertyfile(propertyfilename):
if (propertyfilename == 'null' or os.path.isfile(propertyfilename) == 'False'):
raise ValueError('properties '%propertyfilename%' file not found')

helper.__propertyfilename = propertyfilename
return

@staticmethod
def __classinitialized():
return helper.__initialized

@staticmethod
def getproperty(propertyname):

if ( 'False' == helper.__classinitialized()):
helper.getparser().read(helper.__propertyfilename)
__initialized = 'True'

stringvalue = "null"
if ("null" != helper.getparser()):
stringvalue = helper.getparser().get("properties", propertyname)
else :
print (" property file does not exist, will read from environment")
stringvalue = os.getenv[propertyname]

return stringvalue

@staticmethod
def setproperty(propertyname):
helper.getparser().add_option("properties", propertyname)
return
20 changes: 20 additions & 0 deletions tests/anet_python_sdk_properties.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[properties]

#sandbox cradentials
api.login.id : 6rF76h2U93AL
transaction.key : 7jh86zEUhy7228FG
md5.hash.key : MD5_HASH_KEY

#log
logfilename : logFile.log

#proxy setup
http://internet.visa.com:80
https://internet.visa.com:443

#environments
sandbox : https://apitest.authorize.net/xml/v1/request.api
production : https://api.authorize.net/xml/v1/request.api

#level
executionlogginglevel : WARNING
36 changes: 12 additions & 24 deletions tests/apitestbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,29 @@
'''

import unittest
import os
from ConfigParser import SafeConfigParser
from authorizenet import apicontractsv1
from authorizenet.apicontractsv1 import CTD_ANON
import datetime
from decimal import *
import random
import test

from ConfigParser import SafeConfigParser
from authorizenet import apicontractsv1, apicontrollersbase
from authorizenet.utility import *
from authorizenet.apicontractsv1 import CTD_ANON
from authorizenet import utility

class ApiTestBase(unittest.TestCase):

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

currdir = os.getcwd()
currdirpropertiesfilename = os.path.join(currdir, "anet_python_sdk_properties.ini")

if (os.path.exists(homedirpropertiesfilename)):
parser.read(homedirpropertiesfilename)
elif (os.path.exists(currdirpropertiesfilename)):
parser.read(currdirpropertiesfilename)
else :
print "you do not have anet_python_sdk_properties.ini file neither in home nor in current working directory"

self.api_login_id = parser.get("properties", "api.login.id")
self.transaction_key = parser.get("properties", "transaction.key")
self.amount = str(round(random.random()*100, 2))

self.merchantAuthentication = apicontractsv1.merchantAuthenticationType()
self.merchantAuthentication.name = helper.getproperty('api.login.id')
self.merchantAuthentication.transactionKey = helper.getproperty('transaction.key')
self.ref_id = 'Sample'

self.merchantAuthentication = apicontractsv1.merchantAuthenticationType()
self.merchantAuthentication.name = self.api_login_id
self.merchantAuthentication.transactionKey = self.transaction_key

self.dateOne = datetime.date(2020, 8, 30)
self.interval = CTD_ANON()
self.interval.length = 1
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy