def ValidateStatement(statement): """Validate Statement object. Args: statement: dict Statement object. """ SanityCheck.ValidateTypes(((statement, dict), )) for key in statement: if statement[key] == 'None': continue if key in ('params', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'params\' must contain a single element in the list.' ) raise ValidationError(msg) for param in statement[key]: ValidateString_ParamMapEntry(param) elif key in ('values', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'values\' must contain a single element in the list.' ) raise ValidationError(msg) for value in statement[key]: ValidateString_ValueMapEntry(value) else: SanityCheck.ValidateTypes(((statement[key], (str, unicode)), )) return statement
def NewSanityCheck(wsdl_types, obj, xsi_type): """Validates any given object against its WSDL definition. This method considers None and the empty string to be a valid representation of any type. Args: wsdl_types: dict WSDL-defined types in the same service as the given type. obj: object Object to be validated. Depending on the WSDL-defined type this is representing, the data type will vary. It should always be either a dictionary, list, or string no matter what WSDL-defined type it is. xsi_type: str The type name defined in the WSDL. Raises: ValidationError: The given WSDL-defined type has no definition in the WSDL types map. """ if obj in (None, ''): return if not xsi_type in wsdl_types: raise ValidationError('This type is not defined in the WSDL: %s.' % xsi_type) if wsdl_types[xsi_type]['soap_type'] == 'simple': _SanityCheckSimpleType(wsdl_types, obj, xsi_type) elif wsdl_types[xsi_type]['soap_type'] == 'complex': _SanityCheckComplexType(wsdl_types, obj, xsi_type) elif wsdl_types[xsi_type]['soap_type'] == 'array': _SanityCheckArray(wsdl_types, obj, xsi_type) else: raise ValidationError( 'Error in autogenerated WSDL definitions - Unknown ' 'parameter type: %s' % wsdl_types[xsi_type]['soap_type'])
def ValidateServer(server, version): """Sanity check for API server. Args: server: str API server to access for this API call. version: str API version being used to access the server. Raises: ValidationError: if the given API server or version is not valid. """ # Map of supported API servers and versions. servers = {'v201203': 'https://www.google.com', 'v201204': 'https://www.google.com', 'v201206': 'https://www.google.com', 'v201208': 'https://www.google.com', 'v201211': 'https://www.google.com', 'v201302': 'https://www.google.com', 'v201306': 'https://www.google.com'} if server not in servers.values(): msg = ('Given API server, \'%s\', is not valid. Expecting ' '\'https://www.google.com\'.' % server) raise ValidationError(msg) if version not in servers.keys(): msg = ('Given API version, \'%s\', is not valid. Expecting one of %s.' % (version, sorted(set(servers.keys())))) raise ValidationError(msg) if server != servers[version]: msg = ('Given API version, \'%s\', is not compatible with given server, ' '\'%s\'.' % (version, server)) raise ValidationError(msg)
def ValidateService(service, version): """Checks if this service is available in the requested version. Args: service: str Service being requested. version: str Version being requested. """ if service in DEPRECATED_IN and version in DEPRECATED_IN[service]: raise ValidationError('%s is not available in %s' % (service, version)) if service in DEPRECATED_AFTER and version > DEPRECATED_AFTER[service]: raise ValidationError('%s is not available in %s' % (service, version))
def __init__(self, headers, config, op_config, url, import_chain, lock, logger): """Inits ApiService. Args: headers: dict Dictionary object with populated authentication credentials. config: dict Dictionary object with populated configuration values. op_config: dict Dictionary object with additional configuration values for this operation. url: str URL for the web service. import_chain: str Import chain of the wrapper for web service. lock: thread.lock Thread lock logger: Logger Instance of Logger """ ToolkitSanityCheck = None API_VERSIONS = [] self._config = config self._op_config = op_config if config['soap_lib'] == SOAPPY: from adspygoogle.common.soappy import MessageHandler exec('from %s.soappy import SanityCheck as ToolkitSanityCheck' % import_chain) self._web_services = None self._message_handler = MessageHandler elif config['soap_lib'] == ZSI: exec 'from %s import API_VERSIONS' % import_chain exec 'from %s.zsi import SanityCheck as ToolkitSanityCheck' % import_chain if op_config['version'] in API_VERSIONS: module = '%s_services' % self.__class__.__name__ try: version = op_config['version'] if version.find('.') > -1: version = version.replace('.', '_') web_services = __import__( '%s.zsi.%s.%s' % (import_chain, version, module), globals(), locals(), ['']) except ImportError, e: # If one of library's required modules is missing, re raise exception. if str(e).find(module) < 0: raise ImportError(e) msg = ( 'The version \'%s\' is not compatible with \'%s\'.' % (op_config['version'], self.__class__.__name__)) raise ValidationError(msg) else: msg = 'Invalid API version, not one of %s.' % str( list(API_VERSIONS)) raise ValidationError(msg) self._web_services = web_services self._loc = eval('web_services.%sLocator()' % self.__class__.__name__)
def SoappySanityCheck(soappy_service, obj, ns, obj_type, max_occurs='1'): """Validates any given object against its WSDL definition. This method considers None and the empty string to be a valid representation of any type. Args: soappy_service: SOAPpy.WSDL.Proxy An object encapsulating a SOAP service. obj: Object to be validated. Depending on the WSDL-defined type this object represents, the data type will vary. It should always be either a dictionary, list, or string no matter what WSDL-defined type it is. ns: string The namespace the given type belongs to. obj_type: A string specifying the type name defined in the WSDL. max_occurs: string The maxOccurs attribute for this object. Raises: ValidationError: The given type has no definition in the WSDL or the given object is not a valid representation of the type defined in the WSDL. """ if obj in (None, ''): return elif Utils.IsBaseSoapType(obj_type): try: ValidateTypes(((obj, (str, unicode)), )) except ValidationError: raise ValidationError( 'Objects of type \'%s\' should be a string but ' 'value \'%s\' is a \'%s\' instead.' % (obj_type, obj, type(obj))) else: try: soap_type = soappy_service.wsdl.types[ns].types[obj_type].tag if soap_type == 'simpleType': _SoappySanityCheckSimpleType(obj, obj_type) elif soap_type == 'complexType': if (SoappyUtils.IsAnArrayType(obj_type, ns, soappy_service) or not max_occurs.isdigit() or int(max_occurs) > 1): _SoappySanityCheckArray(soappy_service, obj, ns, obj_type) else: _SoappySanityCheckComplexType(soappy_service, obj, ns, obj_type) else: raise ValidationError( 'Unrecognized type definition tag in WSDL: \'%s\'' % soap_type) except KeyError: raise ValidationError( 'This type is not defined in the WSDL: \'%s\'' % obj_type)
def ValidateRequiredHeaders(headers, required_headers): """Sanity check for required authentication elements. The required headers may contain several possible header combinations, only one of which must be satisfied to make successful API request. In order for any single combination to be satisfied, all of the headers it specifies must exist as keys within the headers dict and each entry must contain data. Args: headers: A dict containing authentication headers. required_headers: A tuple containing valid combinations of headers. Each combination of headers is represented as a tuple of strings. e.g. (('Name', 'Password'), ('Name', 'Token')) Raises: ValidationError: The given authentication headers are not sufficient to make requests against this API. """ is_valid = False for headers_set in required_headers: is_valid_set = True for key in headers_set: if key not in headers or not headers[key]: is_valid_set = False if is_valid_set: is_valid = True break if not is_valid: msg = ('Required authentication header is missing. Valid options for ' 'headers are %s.' % str(required_headers)) raise ValidationError(msg)
def ValidateCustomCriteriaSet(criteria_set): """Validate CustomCriteriaSet object. Args: criteria_set: dict CustomCriteriaSet object. Returns: CustomCriteriaSet instance. """ SanityCheck.ValidateTypes(((criteria_set, dict), )) for key in criteria_set: if key in ('children', ): SanityCheck.ValidateTypes(((criteria_set[key], list), )) children = [] for item in criteria_set[key]: if 'xsi_type' in item: if item['xsi_type'] in ('FreeFormCustomCriteria', 'PredefinedCustomCriteria'): children.append(ValidateCustomCriteria(item)) else: children.append(ValidateCustomCriteriaSet(item)) else: msg = 'The \'xsi_type\' of node is missing.' raise ValidationError(msg) else: SanityCheck.ValidateTypes(((criteria_set[key], (str, unicode)), ))
def ValidateString_ParamMapEntry(param, web_services): """Validate String_ParamMapEntry object. Args: param: dict Param object. web_services: module Web services. Returns: String_ParamMapEntry instance. """ if ZsiSanityCheck.IsPyClass(param): return param SanityCheck.ValidateTypes(((param, dict), )) new_param = ZsiSanityCheck.GetPyClass('String_ParamMapEntry', web_services) for key in param: SanityCheck.ValidateTypes(((param[key], (str, unicode)), )) if key in ('value', ): if 'xsi_type' in param: value = ZsiSanityCheck.GetPyClass(param['xsi_type'], web_services) elif 'type' in param: value = ZsiSanityCheck.GetPyClass(param['type'], web_services) else: msg = ('The type of the param is missing.') raise ValidationError(msg) value.__dict__.__setitem__('_%s' % key, param[key]) data = value else: data = param[key] new_param.__dict__.__setitem__('_%s' % key, data) return new_param
def ValidateRequiredHeaders(headers, required_headers): """Sanity check for required authentication elements. All required authentication headers have to be set in order to make successful API request. Args: headers: dict Authentication headers. required_headers: tuple Valid combinations of headers. Raises: ValidationError: The given authentication headers are not sufficient to make requests agaisnt this API. """ is_valid = True for headers_set in required_headers: is_valid_set = True for key in headers_set: if key not in headers or not headers[key]: is_valid_set = False if not is_valid_set: is_valid = False else: is_valid = True break if not is_valid: msg = ('Required authentication header is missing. Valid options for ' 'headers are %s.' % str(required_headers)) raise ValidationError(msg)
def ValidateAction(action, web_services): """Validate Action object. Args: action: dict Action to perform. web_services: module Web services. Returns: Action instance. """ if ZsiSanityCheck.IsPyClass(action): return action SanityCheck.ValidateTypes(((action, dict), )) if 'xsi_type' in action: new_action = ZsiSanityCheck.GetPyClass(action['xsi_type'], web_services) elif 'type' in action: new_action = ZsiSanityCheck.GetPyClass(action['type'], web_services) else: msg = 'The type of the action is missing.' raise ValidationError(msg) for key in action: SanityCheck.ValidateTypes(((action[key], (str, unicode)), )) new_action.__dict__.__setitem__('_%s' % key, action[key]) return new_action
def ValidateString_ValueMapEntry(value, web_services): """Validate String_ValueMapEntry object. Args: value: dict Value object. web_services: module Web services. Returns: String_ValueMapEntry instance. """ if ZsiSanityCheck.IsPyClass(value): return value SanityCheck.ValidateTypes(((value, dict), )) new_value = ZsiSanityCheck.GetPyClass('String_ValueMapEntry', web_services) for key in value: if key in ('value', ): SanityCheck.ValidateTypes(((value[key], dict), )) if 'xsi_type' in value[key]: value_obj = ZsiSanityCheck.GetPyClass(value[key]['xsi_type'], web_services) else: msg = ('The \'xsi_type\' of the value is missing.') raise ValidationError(msg) for sub_key in value[key]: value_obj.__dict__.__setitem__('_%s' % sub_key, value[key][sub_key]) data = value_obj else: SanityCheck.ValidateTypes(((value[key], (str, unicode)), )) data = value[key] new_value.__dict__.__setitem__('_%s' % key, data) return new_value
def _LoadAuthCredentials(self): """Load existing authentication credentials from auth.pkl. Returns: dict Dictionary object with populated authentication credentials. Raises: ValidationError: if authentication data is missing. """ auth = {} if os.path.exists(self.__class__.auth_pkl): fh = open(self.__class__.auth_pkl, 'r') try: auth = pickle.load(fh) finally: fh.close() if not auth: msg = 'Authentication data is missing.' raise ValidationError(msg) if _OAUTH_2_AUTH_KEYS.issubset(set(auth.keys())): from oauth2client.client import OAuth2Credentials auth['oauth2credentials'] = OAuth2Credentials( None, auth['clientId'], auth['clientSecret'], auth['refreshToken'], datetime.datetime(1980, 1, 1, 12), _GOOGLE_OAUTH2_ENDPOINT, 'Google Ads* Python Client Library') for auth_key in _OAUTH_2_AUTH_KEYS: del auth[auth_key] return auth
def GetAllEntitiesByStatementWithService(service, query='', page_size=500, bind_vars=None): """Get all existing entities by statement. All existing entities are retrieved for a given statement and page size. The retrieval of entities works across all services. Thus, the same method can be used to fetch companies, creatives, ad units, line items, etc. The results, even if they span multiple pages, are grouped into a single list of entities. Args: service: ApiService an instance of the service to use. [optional] query: str a statement filter to apply, if any. The default is empty string. page_size: int size of the page to use. If page size is less than 0 or greater than 500, defaults to 500. bind_vars: list Key value pairs of bind variables to use with query. Returns: list a list of existing entities. """ service_name = service._service_name[0:service._service_name. rfind('Service')] if service_name == 'Inventory': service_name = 'AdUnit' if service_name[-1] == 'y': method_name = service_name[:-1] + 'ies' else: method_name = service_name + 's' if service_name == 'Content': method_name = service_name method_name = 'Get%sByStatement' % method_name if page_size <= 0 or page_size > 500: page_size = 500 if (query and (query.upper().find('LIMIT') > -1 or query.upper().find('OFFSET') > -1)): raise ValidationError('The filter query contains an option that is ' 'incompatible with this method.') offset = 0 all_entities = [] while True: filter_statement = { 'query': '%s LIMIT %s OFFSET %s' % (query, page_size, offset), 'values': bind_vars } entities = eval('service.%s(filter_statement)[0].get(\'results\')' % method_name) if not entities: break all_entities.extend(entities) if len(entities) < page_size: break offset += page_size return all_entities
def GetAllEntitiesByStatement(client, service_name, query='', page_size=500, server='https://sandbox.google.com', version=MIN_API_VERSION, http_proxy=None): """Get all existing entities by statement. All existing entities are retrived for a given statement and page size. The retrieval of entities works across all services. Thus, the same method can be used to fetch companies, creatives, ad units, line items, etc. The results, even if they span multiple pages, are grouped into a single list of entities. Args: client: Client an instance of Client. service_name: str name of the service to use. [optional] query: str a statement filter to apply, if any. The default is empty string. page_size: int size of the page to use. If page size is less than 0 or greater than 500, defaults to 500. server: str API server to access for this API call. Possible values are: 'https://www.google.com' for live site and 'https://sandbox.google.com' for sandbox. The default behavior is to access sandbox site. version: str API version to use. http_proxy: str HTTP proxy to use. Returns: list a list of existing entities. """ service = eval('client.Get%sService(server, version, http_proxy)' % service_name) if service_name == 'Inventory': service_name = 'AdUnit' if service_name[-1] == 'y': method_name = service_name[:-1] + 'ies' else: method_name = service_name + 's' method_name = 'Get%sByStatement' % method_name if page_size <= 0 or page_size > 500: page_size = 500 if (query and (query.upper().find('LIMIT') > -1 or query.upper().find('OFFSET') > -1)): raise ValidationError('The filter query contains an option that is ' 'incompatible with this method.') offset = 0 all_entities = [] while True: filter_statement = {'query': '%s LIMIT %s OFFSET %s' % (query, page_size, offset)} entities = eval('service.%s(filter_statement)[0][\'results\']' % method_name) if not entities: break all_entities.extend(entities) if len(entities) < page_size: break offset += page_size return all_entities
def ValidateStatement(statement, web_services): """Validate Statement object. Args: statement: dict Statement object. web_services: module Web services. Returns: Statement instance. """ if ZsiSanityCheck.IsPyClass(statement): return statement SanityCheck.ValidateTypes(((statement, dict), )) new_statement = ZsiSanityCheck.GetPyClass('Statement', web_services) for key in statement: if key in ('params', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'params\' must contain a single element in the list.' ) raise ValidationError(msg) params = [] for param in statement[key]: params.append(ValidateString_ParamMapEntry( param, web_services)) data = params elif key in ('values', ): SanityCheck.ValidateTypes(((statement[key], list), )) if len(statement[key]) > 1: msg = ( 'Map \'values\' must contain a single element in the list.' ) raise ValidationError(msg) values = [] for value in statement[key]: values.append(ValidateString_ValueMapEntry( value, web_services)) data = values else: SanityCheck.ValidateTypes(((statement[key], (str, unicode)), )) data = statement[key] new_statement.__dict__.__setitem__('_%s' % key, data) return new_statement
def ValidateServer(server, version): """Sanity check for API server. Args: server: str API server to access for this API call. version: str API version being used to access the server. Raises: ValidationError: if the given API server or version is not valid. """ if version not in _VERSION_SERVER_MAP: raise ValidationError( 'Given API version, \'%s\', is not valid. Expecting one of %s.' % (version, sorted(_VERSION_SERVER_MAP.keys()))) if server not in _VERSION_SERVER_MAP[version]: raise ValidationError( 'Given API server, \'%s\', is not a valid server for version \'%s\'. ' 'Expecting one of %s.' % (server, version, sorted(_VERSION_SERVER_MAP[version])))
def ValidateHeadersForServer(headers, server): """Check if provided headers match the ones expected on the provided server. The SOAP headers on Sandbox server are different from production. See http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html. """ fits_sandbox = False # The clientEmail SOAP header in Sandbox has to be of specific format, with # "client_" prepended (e.g., [email protected]). if ('clientEmail' in headers and headers['clientEmail'] and headers['clientEmail'].find('client_', 0, 7) > -1): fits_sandbox = True # The developerToken SOAP header in Sandbox has to be same as email SOAP # header with appended "++" and the currency code. if ('email' in headers and headers['email'] and headers['developerToken'].find('%s++' % headers['email'], 0, len(headers['email']) + 2) > -1): fits_sandbox = True elif ('authToken' in headers and headers['authToken'] and headers['developerToken'].find('++') == len(headers['developerToken']) - 5): fits_sandbox = True else: fits_sandbox = False # Sandbox server is identifying by the "sandbox" part in the URL (e.g., # https://sandbox.google.com or https://adwords-sandbox.google.com). if server.find('sandbox') > -1: if not fits_sandbox: msg = ( 'Invalid credentials for \'%s\', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders.' % server) raise ValidationError(msg) elif server.find('sandbox') < 0: if fits_sandbox: msg = ( 'Invalid credentials for \'%s\', see http://code.google.com/apis/adwords/docs/developer/index.html#adwords_api_intro_request.' % server) raise ValidationError(msg)
def ValidateAction(action): """Validate Action object. Args: action: dict Action to perform. """ SanityCheck.ValidateTypes(((action, dict), )) if 'type' not in action: msg = 'The \'type\' of the action is missing.' raise ValidationError(msg) for key in action: SanityCheck.ValidateTypes(((action[key], (str, unicode)), ))
def ValidateConfigXmlParser(xml_parser): """Sanity check for XML parser. Args: xml_parser: str XML parser to use. """ if (not isinstance(xml_parser, str) or not IsConfigUserInputValid(xml_parser, [PYXML, ETREE])): msg = ( 'Invalid input for %s \'%s\', expecting %s or %s of type <str>.' % (type(xml_parser), xml_parser, PYXML, ETREE)) raise ValidationError(msg)
def ValidateConfigSoapLib(soap_lib): """Sanity check for SOAP library. Args: soap_lib: str SOAP library to use. """ if (not isinstance(soap_lib, str) or not IsConfigUserInputValid(soap_lib, [SOAPPY, ZSI])): msg = ( 'Invalid input for %s \'%s\', expecting %s or %s of type <str>.' % (type(soap_lib), soap_lib, SOAPPY, ZSI)) raise ValidationError(msg)
def _SanityCheckComplexType(wsdl_types, obj, xsi_type): """Validates a dict representing a complex type against its WSDL definition. Args: wsdl_types: dict WSDL-defined types in the same service as the given type. obj: dict Object that should represent an instance of the given type. xsi_type: str The complex type name defined in the WSDL. Raises: ValidationError: The given object is not an acceptable representation of the given WSDL-defined complex type. """ ValidateTypes(((obj, dict), )) obj_contained_type, contained_type_key = Utils.GetExplicitType( wsdl_types, obj, xsi_type) if obj_contained_type and not obj_contained_type == xsi_type: if not IsSuperType(wsdl_types, obj_contained_type, xsi_type): raise ValidationError( 'Expecting type of \'%s\' but given type of class ' '\'%s\'.' % (xsi_type, obj_contained_type)) xsi_type = obj_contained_type parameters = Utils.GenParamOrder(wsdl_types, xsi_type) for key in obj: if obj[key] is None or (obj_contained_type and key == contained_type_key): continue found = False for parameter, param_type in parameters: if parameter == key: found = True if Utils.IsXsdOrSoapenc(param_type): ValidateTypes(((obj[key], (str, unicode)), )) else: NewSanityCheck(wsdl_types, obj[key], param_type) break if not found: raise ValidationError('Field \'%s\' is not in type \'%s\'.' % (key, xsi_type))
def _SoappySanityCheckArray(soappy_service, obj, ns, type_name): """Validates a list representing an array type against its WSDL definition. Args: soappy_service: SOAPpy.WSDL.Proxy The SOAPpy service object containing the descriptions of all WSDL-defined types. obj: Object to be validated. Depending on the WSDL-defined type this object represents, the data type will vary. It should always be either a dictionary, list, or string no matter what WSDL-defined type it is. ns: string The namespace the given type belongs to. type_name: A string specifying the type name defined in the WSDL. Raises: ValidationError if the given object is not a valid representation of the given list type. """ try: ValidateTypes(((obj, list), )) except ValidationError: raise ValidationError('Type \'%s\' should be a list but value ' '\'%s\' is a \'%s\' instead.' % (type_name, obj, type(obj))) if Utils.IsBaseSoapType(type_name): for item in obj: if item is None: continue try: ValidateTypes(((item, (str, unicode)), )) except ValidationError: raise ValidationError( 'The items in array \'%s\' must all be strings. ' 'Value \'%s\' is of type \'%s\'.' % (type_name, item, type(item))) else: for item in obj: if item is None: continue SoappySanityCheck( soappy_service, item, ns, SoappyUtils.GetArrayItemTypeName(type_name, ns, soappy_service))
def ValidateServer(server, version): """Sanity check for API server. Args: server: str API server to access for this API call. version: str API version being used to access the server. """ # Map of supported API servers and versions. prod = { 'v13': 'https://adwords.google.com', 'v200909': 'https://adwords.google.com', 'v201003': 'https://adwords.google.com', 'v201008': 'https://adwords.google.com', 'v201101': 'https://adwords.google.com' } sandbox = { 'v13': 'https://sandbox.google.com', 'v200909': 'https://adwords-sandbox.google.com', 'v201003': 'https://adwords-sandbox.google.com', 'v201008': 'https://adwords-sandbox.google.com', 'v201101': 'https://adwords-sandbox.google.com' } if server not in prod.values() and server not in sandbox.values(): msg = ('Given API server, \'%s\', is not valid. Expecting one of %s.' % (server, sorted(prod.values() + sandbox.values())[1:])) raise ValidationError(msg) if version not in prod.keys() and version not in sandbox.keys(): msg = ( 'Given API version, \'%s\', is not valid. Expecting one of %s.' % (version, sorted(set(prod.keys() + sandbox.keys())))) raise ValidationError(msg) if server != prod[version] and server != sandbox[version]: msg = ( 'Given API version, \'%s\', is not compatible with given server, ' '\'%s\'.' % (version, server)) raise ValidationError(msg)
def ValidateString_ParamMapEntry(param): """Validate String_ParamMapEntry object. Args: param: dict Param object. """ SanityCheck.ValidateTypes(((param, dict), )) for key in param: if param[key] == 'None': continue SanityCheck.ValidateTypes(((param[key], (str, unicode)), )) if key in ('value', ): if 'type' not in param: msg = ('The \'type\' of the param is missing.') raise ValidationError(msg)
def AssignCreativeXsi(creative): """Assigns an xsi type to a creative object if one is not present. Args: creative: dict CreativeBase object. Raises: ValidationError: The creative object is lacking enough information to determine what concrete class it represents. """ if 'xsi_type' not in creative: if 'typeId' in creative: creative['xsi_type'] = GetCreativeXsiTypes()[creative['typeId']] else: raise ValidationError('The type of the creative is missing.')
def AssignAdXsi(ad): """Assigns an xsi type to an Ad object if one is not present. Args: ad: dict Ad object. Raises: ValidationError: The ad object is lacking enough information to determine what concrete class it represents. """ if 'xsi_type' not in ad: if 'typeId' in ad: ad['xsi_type'] = GetAdXsiTypes()[ad['typeId']] else: raise ValidationError('The type of the ad is missing.')
def ValidateServer(server, version): """Sanity check for API server. Args: server: str API server to access for this API call. version: str API version being used to access the server. Raises: ValidationError: if the given API server or version is not valid. """ # Map of supported API servers and versions. prod = {'v1.19': 'https://advertisersapi.doubleclick.net', 'v1.20': 'https://advertisersapi.doubleclick.net'} beta = {'v1.19': 'https://betaadvertisersapi.doubleclick.net', 'v1.20': 'https://betaadvertisersapi.doubleclick.net'} test = {'v1.19': 'https://advertisersapitest.doubleclick.net', 'v1.20': 'https://advertisersapitest.doubleclick.net'} if (server not in prod.values() and server not in beta.values() and server not in test.values()): msg = ('Given API server, \'%s\', is not valid. Expecting one of %s.' % (server, sorted(prod.values() + beta.values() + test.values())[1:])) raise ValidationError(msg) if (version not in prod.keys() and version not in beta.keys() and version not in test.keys()): msg = ('Given API version, \'%s\', is not valid. Expecting one of %s.' % (version, sorted(set(prod.keys() + beta.keys() + test.keys())))) raise ValidationError(msg) if (server != prod[version] and server != beta[version] and server != test[version]): msg = ('Given API version, \'%s\', is not compatible with given server, ' '\'%s\'.' % (version, server)) raise ValidationError(msg)
def ValidateConfigXmlParser(xml_parser): """Checks that the XML parser set in the configuration is a valid choice. Args: xml_parser: A string specifying which XML parser to use. Raises: ValidationError: The given XML parser is not supported by this library. """ if (not isinstance(xml_parser, basestring) or not IsConfigUserInputValid(xml_parser, [PYXML, ETREE])): msg = ( 'Invalid input for %s \'%s\', expecting %s or %s of type <str>.' % (type(xml_parser), xml_parser, PYXML, ETREE)) raise ValidationError(msg)
def ValidateTypes(vars_tpl): """Check types for a set of variables. Args: vars_tpl: tuple Set of variables to check. """ for var, var_types in vars_tpl: if not isinstance(var_types, tuple): var_types = (var_types, ) for var_type in var_types: if IsType(var, var_type): return msg = ('The \'%s\' is of type %s, expecting one of %s.' % (var, type(var), var_types)) raise ValidationError(msg)