class ErrorsTest(unittest.TestCase): """Unittest suite for Errors.""" TRIGGER_MSG1 = 'The developer token is invalid.' TRIGGER_CODE1 = 42 TRIGGER_STR = """faultcode: soapenv:Server.userException faultstring: The developer token is invalid. trigger: xxxxxx++USD message: The developer token is invalid. code: 42""" TRIGGER_MSG2 = 'An internal error has occurred. Please retry your request.' TRIGGER_CODE2 = 0 TRIGGER_MSG3 = 'Fault occurred while processing.' TRIGGER_MSG4 = 'One or more input elements failed validation.' TRIGGER_CODE4 = 122 XML_RESPONSE_FAULT1 = Utils.ReadFile( os.path.join('data', 'response_fault_stacktrace.xml')) XML_RESPONSE_FAULT2 = Utils.ReadFile( os.path.join('data', 'response_fault.xml')) XML_RESPONSE_FAULT3 = Utils.ReadFile( os.path.join('data', 'response_fault_errors.xml')) def setUp(self): """Prepare unittest.""" print self.id() def testApiAsStrError(self): """Tests whether we can catch an Errors.ApiAsStrError exception.""" try: raise ApiAsStrError(self.__class__.TRIGGER_STR) except ApiAsStrError, e: self.assertEqual(e.msg, self.__class__.TRIGGER_MSG1) self.assertEqual(int(e.code), self.__class__.TRIGGER_CODE1)
def testUpperStackLogging(self): """Tests whether we can define logger at client level and log before and after the API request is made.""" logger = logging.getLogger('LoggerTest') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(self.__class__.TMP_LOG) fh.setLevel(logging.DEBUG) logger.addHandler(fh) # Clean up temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) logger.debug(self.__class__.DEBUG_MSG1) account_service = client.GetAccountService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) account_service.GetAccountInfo() logger.debug(self.__class__.DEBUG_MSG2) data = Utils.ReadFile(self.__class__.TMP_LOG) self.assertEqual(data.find(self.__class__.DEBUG_MSG1), 0) self.assertEqual(data.find(self.__class__.DEBUG_MSG2), len(self.__class__.DEBUG_MSG1) + 1) # Clean up and remove temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) os.remove(self.__class__.TMP_LOG)
def testCallRawMethod(self): """Test whether we can call an API method by posting SOAP XML message.""" soap_message = Utils.ReadFile( os.path.join('data', 'request_getaccountinfo.xml')) url = '/api/adwords/v13/AccountService' http_proxy = None self.failUnlessRaises(ApiError, client.CallRawMethod, soap_message, url, http_proxy)
def testDownloadCsvReportNonAscii(self): """Test whether we can download a csv report that includes non-ASCII data using.""" xml = Utils.ReadFile(os.path.join('data', 'report_non_ascii.xml')) self.assert_( isinstance( self.__class__.service.DownloadCsvReport( self.__class__.COMPLETED_REPORT_JOB_ID, xml), (str, unicode)))
class MediaServiceTestV201003(unittest.TestCase): """Unittest suite for MediaService using v201003.""" SERVER = SERVER_V201003 VERSION = VERSION_V201003 IMAGE_DATA = Utils.ReadFile(os.path.join('data', 'image.jpg')) if client.soap_lib == SOAPPY: IMAGE_DATA = base64.encodestring(IMAGE_DATA) client.debug = False service = None def setUp(self): """Prepare unittest.""" print self.id() if not self.__class__.service: self.__class__.service = client.GetMediaService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) def testGetAllImageMedia(self): """Test whether we can fetch all existing image media.""" selector = { 'mediaType': 'IMAGE' } self.assert_(isinstance(self.__class__.service.Get(selector), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'get', client.GetLastOperations(), True), client.GetLastUnits()) def testUploadImageMedia(self): """Test whether we can upload new image media.""" media = [{ 'type': 'Image', 'data': self.__class__.IMAGE_DATA, 'mediaTypeDb': 'IMAGE', 'name': 'Sample Image' }] self.assert_(isinstance(self.__class__.service.Upload(media), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'upload', client.GetLastOperations(), True), client.GetLastUnits())
def testError502(self): """Test whether we can handle and report 502 errors.""" # Temporarily redirect STDOUT into a buffer. buf = SoapBuffer() sys.stdout = buf html_code = Utils.ReadFile(os.path.join('data', 'http_error_502.html')) print html_code # Restore STDOUT. sys.stdout = sys.__stdout__ if not buf.IsHandshakeComplete(): data = buf.GetBufferAsStr() else: data = '' self.assertEqual(Utils.GetErrorFromHtml(data), self.__class__.TRIGGER_MSG)
from aw_api import MIN_API_VERSION from aw_api import Utils from aw_api.Client import Client from aw_api.Errors import ApiError # Initialize Client object. The "path" parameter should point to the location of # pickles, which get generated after execution of "aw_api_config.py" script. The # same location is used for the "logs/" directory, if logging is enabled. client = Client(path='../..') # Temporarily disable debugging. If enabled, the debugging data will be send to # STDOUT. client.debug = False # Construct SOAP message by loading XML from existing data file. soap_message = Utils.ReadFile( os.path.join(LIB_HOME, 'data', 'request_getaccountinfo.xml')) url = '/api/adwords/%s/AccountService' % MIN_API_VERSION http_proxy = None try: response = client.CallRawMethod(soap_message, url, http_proxy)[0] # Display results. print 'Response:\n%s' % response except ApiError, e: print 'Note: this should fail, unless you provide valid authentication data.' print raise e print print('Usage: %s units, %s operations' %
class AdGroupAdServiceTestV200909(unittest.TestCase): """Unittest suite for AdGroupAdService using v200909.""" SERVER = SERVER_V200909 VERSION = VERSION_V200909 IMAGE_DATA = Utils.ReadFile(os.path.join('data', 'image.jpg')) MOBILE_IMAGE_DATA = Utils.ReadFile(os.path.join('data', 'image_192x53.jpg')) if client.soap_lib == SOAPPY: IMAGE_DATA = base64.encodestring(IMAGE_DATA) MOBILE_IMAGE_DATA = base64.encodestring(MOBILE_IMAGE_DATA) client.debug = False service = None campaign_id = '0' ad_group_id = '0' ad = None def setUp(self): """Prepare unittest.""" print self.id() if not self.__class__.service: self.__class__.service = client.GetAdGroupAdService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) if self.__class__.campaign_id is '0' or self.__class__.ad_group_id is '0': campaign_service = client.GetCampaignService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) operations = [{ 'operator': 'ADD', 'operand': { 'name': 'Campaign #%s' % Utils.GetUniqueName(), 'status': 'PAUSED', 'biddingStrategy': { 'type': 'ManualCPC' }, 'budget': { 'period': 'DAILY', 'amount': { 'microAmount': '1000000' }, 'deliveryMethod': 'STANDARD' } } }] self.__class__.campaign_id = \ campaign_service.Mutate(operations)[0]['value'][0]['id'] ad_group_service = client.GetAdGroupService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) operations = [{ 'operator': 'ADD', 'operand': { 'campaignId': self.__class__.campaign_id, 'name': 'AdGroup #%s' % Utils.GetUniqueName(), 'status': 'ENABLED', 'bids': { 'type': 'ManualCPCAdGroupBids', 'keywordMaxCpc': { 'amount': { 'microAmount': '1000000' } } } } }] self.__class__.ad_group_id = ad_group_service.Mutate( operations)[0]['value'][0]['id'] def testAddTextAd(self): """Test whether we can add a text ad.""" operations = [{ 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': self.__class__.ad_group_id, 'ad': { 'type': 'TextAd', 'url': 'http://www.example.com', 'displayUrl': 'example.com', 'status': 'ENABLED', 'description1': 'Visit the Red Planet in style.', 'description2': 'Low-gravity fun for everyone!', 'headline': 'Luxury Cruise to Mars' } } }] ads = self.__class__.service.Mutate(operations) self.__class__.ad = ads[0]['value'][0] self.assert_(isinstance(ads, tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'mutate.ADD', client.GetLastOperations(), True), client.GetLastUnits()) def testAddTextAdWithExemptionRequests(self): """Test whether we can add a text ad with exemption requests.""" operations = [{ 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': self.__class__.ad_group_id, 'ad': { 'type': 'TextAd', 'url': 'http://www.example.com', 'displayUrl': 'example.com', 'status': 'ENABLED', 'description1': 'Visit the Red Planet in style.', 'description2': 'Low-gravity fun for everyone!!!', 'headline': 'Luxury Cruise to Mars' } }, 'exemptionRequests': [{ 'key': { 'policyName': 'nonstandard_punctuation', 'violatingText': 'everyone!!!' } }, { 'key': { 'policyName': 'nonstandard_punctuation', 'violatingText': '!!!' } }] }] self.assert_( isinstance(self.__class__.service.Mutate(operations), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'mutate.ADD', client.GetLastOperations(), True), client.GetLastUnits()) def testAddImageAd(self): """Test whether we can add an image ad.""" operations = [{ 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': self.__class__.ad_group_id, 'ad': { 'type': 'ImageAd', 'image': { 'dimensions': [{ 'key': 'FULL', 'value': { 'width': '300', 'height': '250' } }], 'name': 'image.jpg', 'data': self.__class__.IMAGE_DATA }, 'name': 'Test image', 'url': 'http://www.example.com', 'displayUrl': 'www.example.com' } } }] self.assert_( isinstance(self.__class__.service.Mutate(operations), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'mutate.ADD', client.GetLastOperations(), True), client.GetLastUnits()) def testAddMobileImageAd(self): """Test whether we can add a mobile image ad.""" operations = [{ 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': self.__class__.ad_group_id, 'ad': { 'type': 'MobileImageAd', 'markupLanguages': ['HTML'], 'mobileCarriers': ['T-Mobile@US', 'Verizon@US'], 'image': { 'dimensions': [{ 'key': 'SHRUNKEN', 'value': { 'width': '192', 'height': '53' } }], 'name': 'image_192x53.jpg', 'data': self.__class__.MOBILE_IMAGE_DATA }, 'url': 'http://www.example.com', 'displayUrl': 'www.example.com' } } }] self.assert_( isinstance(self.__class__.service.Mutate(operations), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'mutate.ADD', client.GetLastOperations(), True), client.GetLastUnits()) def testGetAllAdsFromCampaign(self): """Test whether we can fetch all ads from given campaign.""" selector = {'campaignIds': [self.__class__.campaign_id]} self.assert_(isinstance(self.__class__.service.Get(selector), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'get', client.GetLastOperations(), True), client.GetLastUnits()) def testGetAd(self): """Test whether we can fetch an ad.""" if self.__class__.ad == None: self.testAddTextAd() selector = { 'adGroupIds': [self.__class__.ad['adGroupId']], 'adIds': [self.__class__.ad['ad']['id']] } self.assert_(isinstance(self.__class__.service.Get(selector), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'get', client.GetLastOperations(), True), client.GetLastUnits()) def testUpdateAd(self): """Test whether we can update an ad.""" if self.__class__.ad == None: self.testAddTextAd() operations = [{ 'operator': 'SET', 'operand': { 'type': 'AdGroupAd', 'adGroupId': self.__class__.ad['adGroupId'], 'ad': { 'id': self.__class__.ad['ad']['id'], }, 'status': 'PAUSED' } }] self.assert_( isinstance(self.__class__.service.Mutate(operations), tuple)) self.assertEqual( Utils.GetMethodCost(self.__class__.VERSION, self.__class__.service.__class__.__name__, 'mutate.SET', client.GetLastOperations(), True), client.GetLastUnits())
# Import appropriate classes from the client library. from aw_api import SOAPPY from aw_api import Utils from aw_api.Client import Client # Initialize client object. client = Client(path='../..') # Initialize appropriate service. ad_group_ad_service = client.GetAdGroupAdService( 'https://adwords-sandbox.google.com', 'v201003') ad_group_id = 'INSERT_AD_GROUP_ID_HERE' video_media_id = 'INSERT_VIDEO_MEDIA_ID' image_data = Utils.ReadFile('INSERT_IMAGE_PATH_HERE') if client.soap_lib == SOAPPY: image_data = base64.encodestring(image_data) # Construct operations and add ads. operations = [{ 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { 'type': 'TextAd', 'url': 'http://www.example.com', 'displayUrl': 'example.com', 'status': 'ENABLED', 'description1': 'Visit the Red Planet in style.',
} }, { 'operator': 'ADD', 'operand': { 'type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { 'type': 'ImageAd', 'image': { 'dimensions': [{ 'key': 'FULL', 'value': {'width': '300', 'height': '250'} }], 'name': 'image.jpg', 'data': Utils.ReadFile(os.path.join('..', '..', 'tests', 'data', 'image.jpg')) }, 'name': 'Cruise to mars image ad #%s' % Utils.GetUniqueName(), 'url': 'http://www.example.com', 'displayUrl': 'www.example.com' } } } ] ads = ad_group_ad_service.Mutate(operations)[0] # Display results. for ad in ads['value']: print ('Ad with id \'%s\' and of type \'%s\' was added.' % (ad['ad']['id'], ad['ad']['Ad_Type']))