code
stringlengths
1
1.72M
language
stringclasses
1 value
"""Cryptlib 3DES implementation.""" from cryptomath import * from TripleDES import * if cryptlibpyLoaded: def new(key, mode, IV): return Cryptlib_TripleDES(key, mode, IV) class Cryptlib_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_3DES) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_CBC) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_IV, IV) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) bytes = stringToBytes(ciphertext) cryptlib_py.cryptDecrypt(self.context, bytes) return bytesToString(bytes)
Python
"""Cryptlib RC4 implementation.""" from cryptomath import * from RC4 import RC4 if cryptlibpyLoaded: def new(key): return Cryptlib_RC4(key) class Cryptlib_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_RC4) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""Toolkit for crypto and other stuff.""" __all__ = ["AES", "ASN1Parser", "cipherfactory", "codec", "Cryptlib_AES", "Cryptlib_RC4", "Cryptlib_TripleDES", "cryptomath: cryptomath module", "dateFuncs", "hmac", "JCE_RSAKey", "compat", "keyfactory", "OpenSSL_AES", "OpenSSL_RC4", "OpenSSL_RSAKey", "OpenSSL_TripleDES", "PyCrypto_AES", "PyCrypto_RC4", "PyCrypto_RSAKey", "PyCrypto_TripleDES", "Python_AES", "Python_RC4", "Python_RSAKey", "RC4", "rijndael", "RSAKey", "TripleDES", "xmltools"]
Python
"""PyCrypto 3DES implementation.""" from cryptomath import * from TripleDES import * if pycryptoLoaded: import Crypto.Cipher.DES3 def new(key, mode, IV): return PyCrypto_TripleDES(key, mode, IV) class PyCrypto_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "pycrypto") self.context = Crypto.Cipher.DES3.new(key, mode, IV) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""OpenSSL/M2Crypto AES implementation.""" from cryptomath import * from AES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_AES(key, mode, IV) class OpenSSL_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() if len(self.key)==16: cipherType = m2.aes_128_cbc() if len(self.key)==24: cipherType = m2.aes_192_cbc() if len(self.key)==32: cipherType = m2.aes_256_cbc() m2.cipher_init(context, cipherType, self.key, self.IV, encrypt) return context def encrypt(self, plaintext): AES.encrypt(self, plaintext) context = self._createContext(1) ciphertext = m2.cipher_update(context, plaintext) m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return ciphertext def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) context = self._createContext(0) #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in. #To work around this, we append sixteen zeros to the string, below: plaintext = m2.cipher_update(context, ciphertext+('\0'*16)) #If this bug is ever fixed, then plaintext will end up having a garbage #plaintext block on the end. That's okay - the below code will discard it. plaintext = plaintext[:len(ciphertext)] m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return plaintext
Python
"""Pure-Python AES implementation.""" from cryptomath import * from AES import * from rijndael import rijndael def new(key, mode, IV): return Python_AES(key, mode, IV) class Python_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "python") self.rijndael = rijndael(key, 16) self.IV = IV def encrypt(self, plaintext): AES.encrypt(self, plaintext) plaintextBytes = stringToBytes(plaintext) chainBytes = stringToBytes(self.IV) #CBC Mode: For each block... for x in range(len(plaintextBytes)/16): #XOR with the chaining block blockBytes = plaintextBytes[x*16 : (x*16)+16] for y in range(16): blockBytes[y] ^= chainBytes[y] blockString = bytesToString(blockBytes) #Encrypt it encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString)) #Overwrite the input with the output for y in range(16): plaintextBytes[(x*16)+y] = encryptedBytes[y] #Set the next chaining block chainBytes = encryptedBytes self.IV = bytesToString(chainBytes) return bytesToString(plaintextBytes) def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) ciphertextBytes = stringToBytes(ciphertext) chainBytes = stringToBytes(self.IV) #CBC Mode: For each block... for x in range(len(ciphertextBytes)/16): #Decrypt it blockBytes = ciphertextBytes[x*16 : (x*16)+16] blockString = bytesToString(blockBytes) decryptedBytes = stringToBytes(self.rijndael.decrypt(blockString)) #XOR with the chaining block and overwrite the input with output for y in range(16): decryptedBytes[y] ^= chainBytes[y] ciphertextBytes[(x*16)+y] = decryptedBytes[y] #Set the next chaining block chainBytes = blockBytes self.IV = bytesToString(chainBytes) return bytesToString(ciphertextBytes)
Python
import os #Functions for manipulating datetime objects #CCYY-MM-DDThh:mm:ssZ def parseDateClass(s): year, month, day = s.split("-") day, tail = day[:2], day[2:] hour, minute, second = tail[1:].split(":") second = second[:2] year, month, day = int(year), int(month), int(day) hour, minute, second = int(hour), int(minute), int(second) return createDateClass(year, month, day, hour, minute, second) if os.name != "java": from datetime import datetime, timedelta #Helper functions for working with a date/time class def createDateClass(year, month, day, hour, minute, second): return datetime(year, month, day, hour, minute, second) def printDateClass(d): #Split off fractional seconds, append 'Z' return d.isoformat().split(".")[0]+"Z" def getNow(): return datetime.utcnow() def getHoursFromNow(hours): return datetime.utcnow() + timedelta(hours=hours) def getMinutesFromNow(minutes): return datetime.utcnow() + timedelta(minutes=minutes) def isDateClassExpired(d): return d < datetime.utcnow() def isDateClassBefore(d1, d2): return d1 < d2 else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: import java import jarray def createDateClass(year, month, day, hour, minute, second): c = java.util.Calendar.getInstance() c.setTimeZone(java.util.TimeZone.getTimeZone("UTC")) c.set(year, month-1, day, hour, minute, second) return c def printDateClass(d): return "%04d-%02d-%02dT%02d:%02d:%02dZ" % \ (d.get(d.YEAR), d.get(d.MONTH)+1, d.get(d.DATE), \ d.get(d.HOUR_OF_DAY), d.get(d.MINUTE), d.get(d.SECOND)) def getNow(): c = java.util.Calendar.getInstance() c.setTimeZone(java.util.TimeZone.getTimeZone("UTC")) c.get(c.HOUR) #force refresh? return c def getHoursFromNow(hours): d = getNow() d.add(d.HOUR, hours) return d def isDateClassExpired(d): n = getNow() return d.before(n) def isDateClassBefore(d1, d2): return d1.before(d2)
Python
"""Miscellaneous functions to mask Python version differences.""" import sys import os if sys.version_info < (2,2): raise AssertionError("Python 2.2 or later required") if sys.version_info < (2,3): def enumerate(collection): return zip(range(len(collection)), collection) class Set: def __init__(self, seq=None): self.values = {} if seq: for e in seq: self.values[e] = None def add(self, e): self.values[e] = None def discard(self, e): if e in self.values.keys(): del(self.values[e]) def union(self, s): ret = Set() for e in self.values.keys(): ret.values[e] = None for e in s.values.keys(): ret.values[e] = None return ret def issubset(self, other): for e in self.values.keys(): if e not in other.values.keys(): return False return True def __nonzero__( self): return len(self.values.keys()) def __contains__(self, e): return e in self.values.keys() def __iter__(self): return iter(set.values.keys()) if os.name != "java": import array def createByteArraySequence(seq): return array.array('B', seq) def createByteArrayZeros(howMany): return array.array('B', [0] * howMany) def concatArrays(a1, a2): return a1+a2 def bytesToString(bytes): return bytes.tostring() def stringToBytes(s): bytes = createByteArrayZeros(0) bytes.fromstring(s) return bytes import math def numBits(n): if n==0: return 0 s = "%x" % n return ((len(s)-1)*4) + \ {'0':0, '1':1, '2':2, '3':2, '4':3, '5':3, '6':3, '7':3, '8':4, '9':4, 'a':4, 'b':4, 'c':4, 'd':4, 'e':4, 'f':4, }[s[0]] return int(math.floor(math.log(n, 2))+1) BaseException = Exception import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: #NOTE: JYTHON SUPPORT NO LONGER WORKS, DUE TO USE OF GENERATORS. #THIS CODE IS LEFT IN SO THAT ONE JYTHON UPDATES TO 2.2, IT HAS A #CHANCE OF WORKING AGAIN. import java import jarray def createByteArraySequence(seq): if isinstance(seq, type("")): #If it's a string, convert seq = [ord(c) for c in seq] return jarray.array(seq, 'h') #use short instead of bytes, cause bytes are signed def createByteArrayZeros(howMany): return jarray.zeros(howMany, 'h') #use short instead of bytes, cause bytes are signed def concatArrays(a1, a2): l = list(a1)+list(a2) return createByteArraySequence(l) #WAY TOO SLOW - MUST BE REPLACED------------ def bytesToString(bytes): return "".join([chr(b) for b in bytes]) def stringToBytes(s): bytes = createByteArrayZeros(len(s)) for count, c in enumerate(s): bytes[count] = ord(c) return bytes #WAY TOO SLOW - MUST BE REPLACED------------ def numBits(n): if n==0: return 0 n= 1L * n; #convert to long, if it isn't already return n.__tojava__(java.math.BigInteger).bitLength() #Adjust the string to an array of bytes def stringToJavaByteArray(s): bytes = jarray.zeros(len(s), 'b') for count, c in enumerate(s): x = ord(c) if x >= 128: x -= 256 bytes[count] = x return bytes BaseException = java.lang.Exception import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr
Python
"""HMAC (Keyed-Hashing for Message Authentication) Python module. Implements the HMAC algorithm as described by RFC 2104. (This file is modified from the standard library version to do faster copying) """ def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) # The size of the digests returned by HMAC depends on the underlying # hashing module used. digest_size = None class HMAC: """RFC2104 HMAC class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import md5 digestmod = md5 if key == None: #TREVNEW - for faster copying return #TREVNEW self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() self.digest_size = digestmod.digest_size blocksize = 64 ipad = "\x36" * blocksize opad = "\x5C" * blocksize if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(_strxor(key, opad)) self.inner.update(_strxor(key, ipad)) if msg is not None: self.update(msg) ## def clear(self): ## raise NotImplementedError, "clear() method not available in HMAC." def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = HMAC(None) #TREVNEW - for faster copying other.digest_size = self.digest_size #TREVNEW other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())]) def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)
Python
"""Pure-Python RSA implementation.""" from cryptomath import * import xmltools from ASN1Parser import ASN1Parser from RSAKey import * class Python_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if (n and not e) or (e and not n): raise AssertionError() self.n = n self.e = e self.d = d self.p = p self.q = q self.dP = dP self.dQ = dQ self.qInv = qInv self.blinder = 0 self.unblinder = 0 def hasPrivateKey(self): return self.d != 0 def hash(self): s = self.writeXMLPublicKey('\t\t') return hashAndBase64(s.strip()) def _rawPrivateKeyOp(self, m): #Create blinding values, on the first pass: if not self.blinder: self.unblinder = getRandomNumber(2, self.n) self.blinder = powMod(invMod(self.unblinder, self.n), self.e, self.n) #Blind the input m = (m * self.blinder) % self.n #Perform the RSA operation c = self._rawPrivateKeyOpHelper(m) #Unblind the output c = (c * self.unblinder) % self.n #Update blinding values self.blinder = (self.blinder * self.blinder) % self.n self.unblinder = (self.unblinder * self.unblinder) % self.n #Return the output return c def _rawPrivateKeyOpHelper(self, m): #Non-CRT version #c = powMod(m, self.d, self.n) #CRT version (~3x faster) s1 = powMod(m, self.dP, self.p) s2 = powMod(m, self.dQ, self.q) h = ((s1 - s2) * self.qInv) % self.p c = s2 + self.q * h return c def _rawPublicKeyOp(self, c): m = powMod(c, self.e, self.n) return m def acceptsPassword(self): return False def write(self, indent=''): if self.d: s = indent+'<privateKey xmlns="http://trevp.net/rsa">\n' else: s = indent+'<publicKey xmlns="http://trevp.net/rsa">\n' s += indent+'\t<n>%s</n>\n' % numberToBase64(self.n) s += indent+'\t<e>%s</e>\n' % numberToBase64(self.e) if self.d: s += indent+'\t<d>%s</d>\n' % numberToBase64(self.d) s += indent+'\t<p>%s</p>\n' % numberToBase64(self.p) s += indent+'\t<q>%s</q>\n' % numberToBase64(self.q) s += indent+'\t<dP>%s</dP>\n' % numberToBase64(self.dP) s += indent+'\t<dQ>%s</dQ>\n' % numberToBase64(self.dQ) s += indent+'\t<qInv>%s</qInv>\n' % numberToBase64(self.qInv) s += indent+'</privateKey>' else: s += indent+'</publicKey>' #Only add \n if part of a larger structure if indent != '': s += '\n' return s def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = Python_RSAKey() p = getRandomPrime(bits/2, False) q = getRandomPrime(bits/2, False) t = lcm(p-1, q-1) key.n = p * q key.e = 3L #Needed to be long, for Java key.d = invMod(key.e, t) key.p = p key.q = q key.dP = key.d % (p-1) key.dQ = key.d % (q-1) key.qInv = invMod(q, p) return key generate = staticmethod(generate) def parsePEM(s, passwordCallback=None): """Parse a string containing a <privateKey> or <publicKey>, or PEM-encoded key.""" start = s.find("-----BEGIN PRIVATE KEY-----") if start != -1: end = s.find("-----END PRIVATE KEY-----") if end == -1: raise SyntaxError("Missing PEM Postfix") s = s[start+len("-----BEGIN PRIVATE KEY -----") : end] bytes = base64ToBytes(s) return Python_RSAKey._parsePKCS8(bytes) else: start = s.find("-----BEGIN RSA PRIVATE KEY-----") if start != -1: end = s.find("-----END RSA PRIVATE KEY-----") if end == -1: raise SyntaxError("Missing PEM Postfix") s = s[start+len("-----BEGIN RSA PRIVATE KEY -----") : end] bytes = base64ToBytes(s) return Python_RSAKey._parseSSLeay(bytes) raise SyntaxError("Missing PEM Prefix") parsePEM = staticmethod(parsePEM) def parseXML(s): element = xmltools.parseAndStripWhitespace(s) return Python_RSAKey._parseXML(element) parseXML = staticmethod(parseXML) def _parsePKCS8(bytes): p = ASN1Parser(bytes) version = p.getChild(0).value[0] if version != 0: raise SyntaxError("Unrecognized PKCS8 version") rsaOID = p.getChild(1).value if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]: raise SyntaxError("Unrecognized AlgorithmIdentifier") #Get the privateKey privateKeyP = p.getChild(2) #Adjust for OCTET STRING encapsulation privateKeyP = ASN1Parser(privateKeyP.value) return Python_RSAKey._parseASN1PrivateKey(privateKeyP) _parsePKCS8 = staticmethod(_parsePKCS8) def _parseSSLeay(bytes): privateKeyP = ASN1Parser(bytes) return Python_RSAKey._parseASN1PrivateKey(privateKeyP) _parseSSLeay = staticmethod(_parseSSLeay) def _parseASN1PrivateKey(privateKeyP): version = privateKeyP.getChild(0).value[0] if version != 0: raise SyntaxError("Unrecognized RSAPrivateKey version") n = bytesToNumber(privateKeyP.getChild(1).value) e = bytesToNumber(privateKeyP.getChild(2).value) d = bytesToNumber(privateKeyP.getChild(3).value) p = bytesToNumber(privateKeyP.getChild(4).value) q = bytesToNumber(privateKeyP.getChild(5).value) dP = bytesToNumber(privateKeyP.getChild(6).value) dQ = bytesToNumber(privateKeyP.getChild(7).value) qInv = bytesToNumber(privateKeyP.getChild(8).value) return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) _parseASN1PrivateKey = staticmethod(_parseASN1PrivateKey) def _parseXML(element): try: xmltools.checkName(element, "privateKey") except SyntaxError: xmltools.checkName(element, "publicKey") #Parse attributes xmltools.getReqAttribute(element, "xmlns", "http://trevp.net/rsa\Z") xmltools.checkNoMoreAttributes(element) #Parse public values (<n> and <e>) n = base64ToNumber(xmltools.getText(xmltools.getChild(element, 0, "n"), xmltools.base64RegEx)) e = base64ToNumber(xmltools.getText(xmltools.getChild(element, 1, "e"), xmltools.base64RegEx)) d = 0 p = 0 q = 0 dP = 0 dQ = 0 qInv = 0 #Parse private values, if present if element.childNodes.length>=3: d = base64ToNumber(xmltools.getText(xmltools.getChild(element, 2, "d"), xmltools.base64RegEx)) p = base64ToNumber(xmltools.getText(xmltools.getChild(element, 3, "p"), xmltools.base64RegEx)) q = base64ToNumber(xmltools.getText(xmltools.getChild(element, 4, "q"), xmltools.base64RegEx)) dP = base64ToNumber(xmltools.getText(xmltools.getChild(element, 5, "dP"), xmltools.base64RegEx)) dQ = base64ToNumber(xmltools.getText(xmltools.getChild(element, 6, "dQ"), xmltools.base64RegEx)) qInv = base64ToNumber(xmltools.getText(xmltools.getLastChild(element, 7, "qInv"), xmltools.base64RegEx)) return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) _parseXML = staticmethod(_parseXML)
Python
"""Exception classes. @sort: TLSError, TLSAbruptCloseError, TLSAlert, TLSLocalAlert, TLSRemoteAlert, TLSAuthenticationError, TLSNoAuthenticationError, TLSAuthenticationTypeError, TLSFingerprintError, TLSAuthorizationError, TLSValidationError, TLSFaultError """ from constants import AlertDescription, AlertLevel class TLSError(Exception): """Base class for all TLS Lite exceptions.""" pass class TLSAbruptCloseError(TLSError): """The socket was closed without a proper TLS shutdown. The TLS specification mandates that an alert of some sort must be sent before the underlying socket is closed. If the socket is closed without this, it could signify that an attacker is trying to truncate the connection. It could also signify a misbehaving TLS implementation, or a random network failure. """ pass class TLSAlert(TLSError): """A TLS alert has been signalled.""" pass _descriptionStr = {\ AlertDescription.close_notify: "close_notify",\ AlertDescription.unexpected_message: "unexpected_message",\ AlertDescription.bad_record_mac: "bad_record_mac",\ AlertDescription.decryption_failed: "decryption_failed",\ AlertDescription.record_overflow: "record_overflow",\ AlertDescription.decompression_failure: "decompression_failure",\ AlertDescription.handshake_failure: "handshake_failure",\ AlertDescription.no_certificate: "no certificate",\ AlertDescription.bad_certificate: "bad_certificate",\ AlertDescription.unsupported_certificate: "unsupported_certificate",\ AlertDescription.certificate_revoked: "certificate_revoked",\ AlertDescription.certificate_expired: "certificate_expired",\ AlertDescription.certificate_unknown: "certificate_unknown",\ AlertDescription.illegal_parameter: "illegal_parameter",\ AlertDescription.unknown_ca: "unknown_ca",\ AlertDescription.access_denied: "access_denied",\ AlertDescription.decode_error: "decode_error",\ AlertDescription.decrypt_error: "decrypt_error",\ AlertDescription.export_restriction: "export_restriction",\ AlertDescription.protocol_version: "protocol_version",\ AlertDescription.insufficient_security: "insufficient_security",\ AlertDescription.internal_error: "internal_error",\ AlertDescription.user_canceled: "user_canceled",\ AlertDescription.no_renegotiation: "no_renegotiation",\ AlertDescription.unknown_srp_username: "unknown_srp_username",\ AlertDescription.missing_srp_username: "missing_srp_username"} class TLSLocalAlert(TLSAlert): """A TLS alert has been signalled by the local implementation. @type description: int @ivar description: Set to one of the constants in L{tlslite.constants.AlertDescription} @type level: int @ivar level: Set to one of the constants in L{tlslite.constants.AlertLevel} @type message: str @ivar message: Description of what went wrong. """ def __init__(self, alert, message=None): self.description = alert.description self.level = alert.level self.message = message def __str__(self): alertStr = TLSAlert._descriptionStr.get(self.description) if alertStr == None: alertStr = str(self.description) if self.message: return alertStr + ": " + self.message else: return alertStr class TLSRemoteAlert(TLSAlert): """A TLS alert has been signalled by the remote implementation. @type description: int @ivar description: Set to one of the constants in L{tlslite.constants.AlertDescription} @type level: int @ivar level: Set to one of the constants in L{tlslite.constants.AlertLevel} """ def __init__(self, alert): self.description = alert.description self.level = alert.level def __str__(self): alertStr = TLSAlert._descriptionStr.get(self.description) if alertStr == None: alertStr = str(self.description) return alertStr class TLSAuthenticationError(TLSError): """The handshake succeeded, but the other party's authentication was inadequate. This exception will only be raised when a L{tlslite.Checker.Checker} has been passed to a handshake function. The Checker will be invoked once the handshake completes, and if the Checker objects to how the other party authenticated, a subclass of this exception will be raised. """ pass class TLSNoAuthenticationError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain, but this did not occur.""" pass class TLSAuthenticationTypeError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a different type of certificate chain.""" pass class TLSFingerprintError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain that matches a different fingerprint.""" pass class TLSAuthorizationError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain that has a different authorization.""" pass class TLSValidationError(TLSAuthenticationError): """The Checker has determined that the other party's certificate chain is invalid.""" pass class TLSFaultError(TLSError): """The other party responded incorrectly to an induced fault. This exception will only occur during fault testing, when a TLSConnection's fault variable is set to induce some sort of faulty behavior, and the other party doesn't respond appropriately. """ pass
Python
"""Class for storing shared keys.""" from utils.cryptomath import * from utils.compat import * from mathtls import * from Session import Session from BaseDB import BaseDB class SharedKeyDB(BaseDB): """This class represent an in-memory or on-disk database of shared keys. A SharedKeyDB can be passed to a server handshake function to authenticate a client based on one of the shared keys. This class is thread-safe. """ def __init__(self, filename=None): """Create a new SharedKeyDB. @type filename: str @param filename: Filename for an on-disk database, or None for an in-memory database. If the filename already exists, follow this with a call to open(). To create a new on-disk database, follow this with a call to create(). """ BaseDB.__init__(self, filename, "shared key") def _getItem(self, username, valueStr): session = Session() session._createSharedKey(username, valueStr) return session def __setitem__(self, username, sharedKey): """Add a shared key to the database. @type username: str @param username: The username to associate the shared key with. Must be less than or equal to 16 characters in length, and must not already be in the database. @type sharedKey: str @param sharedKey: The shared key to add. Must be less than 48 characters in length. """ BaseDB.__setitem__(self, username, sharedKey) def _setItem(self, username, value): if len(username)>16: raise ValueError("username too long") if len(value)>=48: raise ValueError("shared key too long") return value def _checkItem(self, value, username, param): newSession = self._getItem(username, param) return value.masterSecret == newSession.masterSecret
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides HTTP functions for gdata.service to use on Google App Engine AppEngineHttpClient: Provides an HTTP request method which uses App Engine's urlfetch API. Set the http_client member of a GDataService object to an instance of an AppEngineHttpClient to allow the gdata library to run on Google App Engine. run_on_appengine: Function which will modify an existing GDataService object to allow it to run on App Engine. It works by creating a new instance of the AppEngineHttpClient and replacing the GDataService object's http_client. """ __author__ = 'api.jscudder (Jeff Scudder)' import StringIO import pickle import atom.http_interface import atom.token_store from google.appengine.api import urlfetch from google.appengine.ext import db from google.appengine.api import users from google.appengine.api import memcache def run_on_appengine(gdata_service, store_tokens=True, single_user_mode=False, deadline=None): """Modifies a GDataService object to allow it to run on App Engine. Args: gdata_service: An instance of AtomService, GDataService, or any of their subclasses which has an http_client member and a token_store member. store_tokens: Boolean, defaults to True. If True, the gdata_service will attempt to add each token to it's token_store when SetClientLoginToken or SetAuthSubToken is called. If False the tokens will not automatically be added to the token_store. single_user_mode: Boolean, defaults to False. If True, the current_token member of gdata_service will be set when SetClientLoginToken or SetAuthTubToken is called. If set to True, the current_token is set in the gdata_service and anyone who accesses the object will use the same token. Note: If store_tokens is set to False and single_user_mode is set to False, all tokens will be ignored, since the library assumes: the tokens should not be stored in the datastore and they should not be stored in the gdata_service object. This will make it impossible to make requests which require authorization. deadline: int (optional) The number of seconds to wait for a response before timing out on the HTTP request. If no deadline is specified, the deafault deadline for HTTP requests from App Engine is used. The maximum is currently 10 (for 10 seconds). The default deadline for App Engine is 5 seconds. """ gdata_service.http_client = AppEngineHttpClient(deadline=deadline) gdata_service.token_store = AppEngineTokenStore() gdata_service.auto_store_tokens = store_tokens gdata_service.auto_set_current_token = single_user_mode return gdata_service class AppEngineHttpClient(atom.http_interface.GenericHttpClient): def __init__(self, headers=None, deadline=None): self.debug = False self.headers = headers or {} self.deadline = deadline def request(self, operation, url, data=None, headers=None): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.http client = atom.http.HttpClient() http_response = client.request('GET', 'http://www.google.com/') Args: operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or DELETE. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. url: The full URL to which the request should be sent. Can be a string or atom.url.Url. headers: dict of strings. HTTP headers which should be sent in the request. """ all_headers = self.headers.copy() if headers: all_headers.update(headers) # Construct the full payload. # Assume that data is None or a string. data_str = data if data: if isinstance(data, list): # If data is a list of different objects, convert them all to strings # and join them together. converted_parts = [_convert_data_part(x) for x in data] data_str = ''.join(converted_parts) else: data_str = _convert_data_part(data) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: all_headers['Content-Length'] = str(len(data_str)) # Set the content type to the default value if none was set. if 'Content-Type' not in all_headers: all_headers['Content-Type'] = 'application/atom+xml' # Lookup the urlfetch operation which corresponds to the desired HTTP verb. if operation == 'GET': method = urlfetch.GET elif operation == 'POST': method = urlfetch.POST elif operation == 'PUT': method = urlfetch.PUT elif operation == 'DELETE': method = urlfetch.DELETE else: method = None if self.deadline is None: return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str, method=method, headers=all_headers, follow_redirects=False)) return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str, method=method, headers=all_headers, follow_redirects=False, deadline=self.deadline)) def _convert_data_part(data): if not data or isinstance(data, str): return data elif hasattr(data, 'read'): # data is a file like object, so read it completely. return data.read() # The data object was not a file. # Try to convert to a string and send the data. return str(data) class HttpResponse(object): """Translates a urlfetch resoinse to look like an hhtplib resoinse. Used to allow the resoinse from HttpRequest to be usable by gdata.service methods. """ def __init__(self, urlfetch_response): self.body = StringIO.StringIO(urlfetch_response.content) self.headers = urlfetch_response.headers self.status = urlfetch_response.status_code self.reason = '' def read(self, length=None): if not length: return self.body.read() else: return self.body.read(length) def getheader(self, name): if not self.headers.has_key(name): return self.headers[name.lower()] return self.headers[name] class TokenCollection(db.Model): """Datastore Model which associates auth tokens with the current user.""" user = db.UserProperty() pickled_tokens = db.BlobProperty() class AppEngineTokenStore(atom.token_store.TokenStore): """Stores the user's auth tokens in the App Engine datastore. Tokens are only written to the datastore if a user is signed in (if users.get_current_user() returns a user object). """ def __init__(self): self.user = None def add_token(self, token): """Associates the token with the current user and stores it. If there is no current user, the token will not be stored. Returns: False if the token was not stored. """ tokens = load_auth_tokens(self.user) if not hasattr(token, 'scopes') or not token.scopes: return False for scope in token.scopes: tokens[str(scope)] = token key = save_auth_tokens(tokens, self.user) if key: return True return False def find_token(self, url): """Searches the current user's collection of token for a token which can be used for a request to the url. Returns: The stored token which belongs to the current user and is valid for the desired URL. If there is no current user, or there is no valid user token in the datastore, a atom.http_interface.GenericToken is returned. """ if url is None: return None if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) tokens = load_auth_tokens(self.user) if url in tokens: token = tokens[url] if token.valid_for_scope(url): return token else: del tokens[url] save_auth_tokens(tokens, self.user) for scope, token in tokens.iteritems(): if token.valid_for_scope(url): return token return atom.http_interface.GenericToken() def remove_token(self, token): """Removes the token from the current user's collection in the datastore. Returns: False if the token was not removed, this could be because the token was not in the datastore, or because there is no current user. """ token_found = False scopes_to_delete = [] tokens = load_auth_tokens(self.user) for scope, stored_token in tokens.iteritems(): if stored_token == token: scopes_to_delete.append(scope) token_found = True for scope in scopes_to_delete: del tokens[scope] if token_found: save_auth_tokens(tokens, self.user) return token_found def remove_all_tokens(self): """Removes all of the current user's tokens from the datastore.""" save_auth_tokens({}, self.user) def save_auth_tokens(token_dict, user=None): """Associates the tokens with the current user and writes to the datastore. If there us no current user, the tokens are not written and this function returns None. Returns: The key of the datastore entity containing the user's tokens, or None if there was no current user. """ if user is None: user = users.get_current_user() if user is None: return None memcache.set('gdata_pickled_tokens:%s' % user, pickle.dumps(token_dict)) user_tokens = TokenCollection.all().filter('user =', user).get() if user_tokens: user_tokens.pickled_tokens = pickle.dumps(token_dict) return user_tokens.put() else: user_tokens = TokenCollection( user=user, pickled_tokens=pickle.dumps(token_dict)) return user_tokens.put() def load_auth_tokens(user=None): """Reads a dictionary of the current user's tokens from the datastore. If there is no current user (a user is not signed in to the app) or the user does not have any tokens, an empty dictionary is returned. """ if user is None: user = users.get_current_user() if user is None: return {} pickled_tokens = memcache.get('gdata_pickled_tokens:%s' % user) if pickled_tokens: return pickle.loads(pickled_tokens) user_tokens = TokenCollection.all().filter('user =', user).get() if user_tokens: memcache.set('gdata_pickled_tokens:%s' % user, user_tokens.pickled_tokens) return pickle.loads(user_tokens.pickled_tokens) return {}
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides functions to persist serialized auth tokens in the datastore. The get_token and set_token functions should be used in conjunction with gdata.gauth's token_from_blob and token_to_blob to allow auth token objects to be reused across requests. It is up to your own code to ensure that the token key's are unique. """ __author__ = 'j.s@google.com (Jeff Scudder)' from google.appengine.ext import db from google.appengine.api import memcache class Token(db.Model): """Datastore Model which stores a serialized auth token.""" t = db.BlobProperty() def get_token(unique_key): """Searches for a stored token with the desired key. Checks memcache and then the datastore if required. Args: unique_key: str which uniquely identifies the desired auth token. Returns: A string encoding the auth token data. Use gdata.gauth.token_from_blob to convert back into a usable token object. None if the token was not found in memcache or the datastore. """ token_string = memcache.get(unique_key) if token_string is None: # The token wasn't in memcache, so look in the datastore. token = Token.get_by_key_name(unique_key) if token is None: return None return token.t return token_string def set_token(unique_key, token_str): """Saves the serialized auth token in the datastore. The token is also stored in memcache to speed up retrieval on a cache hit. Args: unique_key: The unique name for this token as a string. It is up to your code to ensure that this token value is unique in your application. Previous values will be silently overwitten. token_str: A serialized auth token as a string. I expect that this string will be generated by gdata.gauth.token_to_blob. Returns: True if the token was stored sucessfully, False if the token could not be safely cached (if an old value could not be cleared). If the token was set in memcache, but not in the datastore, this function will return None. However, in that situation an exception will likely be raised. Raises: Datastore exceptions may be raised from the App Engine SDK in the event of failure. """ # First try to save in memcache. result = memcache.set(unique_key, token_str) # If memcache fails to save the value, clear the cached value. if not result: result = memcache.delete(unique_key) # If we could not clear the cached value for this token, refuse to save. if result == 0: return False # Save to the datastore. if Token(key_name=unique_key, t=token_str).put(): return True return None def delete_token(unique_key): # Clear from memcache. memcache.delete(unique_key) # Clear from the datastore. Token(key_name=unique_key).delete()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This package's modules adapt the gdata library to run in other environments The first example is the appengine module which contains functions and classes which modify a GDataService object to run on Google App Engine. """
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains a client to communicate with the Google Spreadsheets servers. For documentation on the Spreadsheets API, see: http://code.google.com/apis/spreadsheets/ """ __author__ = 'j.s@google.com (Jeff Scudder)' import gdata.client import gdata.gauth import gdata.spreadsheets.data import atom.data import atom.http_core SPREADSHEETS_URL = ('https://spreadsheets.google.com/feeds/spreadsheets' '/private/full') WORKSHEETS_URL = ('https://spreadsheets.google.com/feeds/worksheets/' '%s/private/full') WORKSHEET_URL = ('https://spreadsheets.google.com/feeds/worksheets/' '%s/private/full/%s') TABLES_URL = 'https://spreadsheets.google.com/feeds/%s/tables' RECORDS_URL = 'https://spreadsheets.google.com/feeds/%s/records/%s' RECORD_URL = 'https://spreadsheets.google.com/feeds/%s/records/%s/%s' class SpreadsheetsClient(gdata.client.GDClient): api_version = '3' auth_service = 'wise' auth_scopes = gdata.gauth.AUTH_SCOPES['wise'] ssl = True def get_spreadsheets(self, auth_token=None, desired_class=gdata.spreadsheets.data.SpreadsheetsFeed, **kwargs): """Obtains a feed with the spreadsheets belonging to the current user. Args: auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.SpreadsheetsFeed. """ return self.get_feed(SPREADSHEETS_URL, auth_token=auth_token, desired_class=desired_class, **kwargs) GetSpreadsheets = get_spreadsheets def get_worksheets(self, spreadsheet_key, auth_token=None, desired_class=gdata.spreadsheets.data.WorksheetsFeed, **kwargs): """Finds the worksheets within a given spreadsheet. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.WorksheetsFeed. """ return self.get_feed(WORKSHEETS_URL % spreadsheet_key, auth_token=auth_token, desired_class=desired_class, **kwargs) GetWorksheets = get_worksheets def add_worksheet(self, spreadsheet_key, title, rows, cols, auth_token=None, **kwargs): """Creates a new worksheet entry in the spreadsheet. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. title: str, The title to be used in for the worksheet. rows: str or int, The number of rows this worksheet should start with. cols: str or int, The number of columns this worksheet should start with. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ new_worksheet = gdata.spreadsheets.data.WorksheetEntry( title=atom.data.Title(text=title), row_count=gdata.spreadsheets.data.RowCount(text=str(rows)), col_count=gdata.spreadsheets.data.ColCount(text=str(cols))) return self.post(new_worksheet, WORKSHEETS_URL % spreadsheet_key, auth_token=auth_token, **kwargs) AddWorksheet = add_worksheet def get_worksheet(self, spreadsheet_key, worksheet_id, desired_class=gdata.spreadsheets.data.WorksheetEntry, auth_token=None, **kwargs): """Retrieves a single worksheet. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. worksheet_id: str, The unique ID for the worksheet withing the desired spreadsheet. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.WorksheetEntry. """ return self.get_entry(WORKSHEET_URL % (spreadsheet_key, worksheet_id,), auth_token=auth_token, desired_class=desired_class, **kwargs) GetWorksheet = get_worksheet def add_table(self, spreadsheet_key, title, summary, worksheet_name, header_row, num_rows, start_row, insertion_mode, column_headers, auth_token=None, **kwargs): """Creates a new table within the worksheet. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. title: str, The title for the new table within a worksheet. summary: str, A description of the table. worksheet_name: str The name of the worksheet in which this table should live. header_row: int or str, The number of the row in the worksheet which will contain the column names for the data in this table. num_rows: int or str, The number of adjacent rows in this table. start_row: int or str, The number of the row at which the data begins. insertion_mode: str column_headers: dict of strings, maps the column letters (A, B, C) to the desired name which will be viewable in the worksheet. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ data = gdata.spreadsheets.data.Data( insertion_mode=insertion_mode, num_rows=str(num_rows), start_row=str(start_row)) for index, name in column_headers.iteritems(): data.column.append(gdata.spreadsheets.data.Column( index=index, name=name)) new_table = gdata.spreadsheets.data.Table( title=atom.data.Title(text=title), summary=atom.data.Summary(summary), worksheet=gdata.spreadsheets.data.Worksheet(name=worksheet_name), header=gdata.spreadsheets.data.Header(row=str(header_row)), data=data) return self.post(new_table, TABLES_URL % spreadsheet_key, auth_token=auth_token, **kwargs) AddTable = add_table def get_tables(self, spreadsheet_key, desired_class=gdata.spreadsheets.data.TablesFeed, auth_token=None, **kwargs): """Retrieves a feed listing the tables in this spreadsheet. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.TablesFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(TABLES_URL % spreadsheet_key, desired_class=desired_class, auth_token=auth_token, **kwargs) GetTables = get_tables def add_record(self, spreadsheet_key, table_id, fields, title=None, auth_token=None, **kwargs): """Adds a new row to the table. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. table_id: str, The ID of the table within the worksheet which should receive this new record. The table ID can be found using the get_table_id method of a gdata.spreadsheets.data.Table. fields: dict of strings mapping column names to values. title: str, optional The title for this row. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ new_record = gdata.spreadsheets.data.Record() if title is not None: new_record.title = atom.data.Title(text=title) for name, value in fields.iteritems(): new_record.field.append(gdata.spreadsheets.data.Field( name=name, text=value)) return self.post(new_record, RECORDS_URL % (spreadsheet_key, table_id), auth_token=auth_token, **kwargs) AddRecord = add_record def get_records(self, spreadsheet_key, table_id, desired_class=gdata.spreadsheets.data.RecordsFeed, auth_token=None, **kwargs): """Retrieves the records in a table. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. table_id: str, The ID of the table within the worksheet whose records we would like to fetch. The table ID can be found using the get_table_id method of a gdata.spreadsheets.data.Table. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.RecordsFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(RECORDS_URL % (spreadsheet_key, table_id), desired_class=desired_class, auth_token=auth_token, **kwargs) GetRecords = get_records def get_record(self, spreadsheet_key, table_id, record_id, desired_class=gdata.spreadsheets.data.Record, auth_token=None, **kwargs): """Retrieves a single record from the table. Args: spreadsheet_key: str, The unique ID of this containing spreadsheet. This can be the ID from the URL or as provided in a Spreadsheet entry. table_id: str, The ID of the table within the worksheet whose records we would like to fetch. The table ID can be found using the get_table_id method of a gdata.spreadsheets.data.Table. record_id: str, The ID of the record within this table which we want to fetch. You can find the record ID using get_record_id() on an instance of the gdata.spreadsheets.data.Record class. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.RecordsFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient.""" return self.get_entry(RECORD_URL % (spreadsheet_key, table_id, record_id), desired_class=desired_class, auth_token=auth_token, **kwargs) GetRecord = get_record class SpreadsheetQuery(gdata.client.Query): def __init__(self, title=None, title_exact=None, **kwargs): """Adds Spreadsheets feed query parameters to a request. Args: title: str Specifies the search terms for the title of a document. This parameter used without title-exact will only submit partial queries, not exact queries. title_exact: str Specifies whether the title query should be taken as an exact string. Meaningless without title. Possible values are 'true' and 'false'. """ gdata.client.Query.__init__(self, **kwargs) self.title = title self.title_exact = title_exact def modify_request(self, http_request): gdata.client._add_query_param('title', self.title, http_request) gdata.client._add_query_param('title-exact', self.title_exact, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request class WorksheetQuery(SpreadsheetQuery): pass class ListQuery(gdata.client.Query): def __init__(self, order_by=None, reverse=None, sq=None, **kwargs): """Adds List-feed specific query parameters to a request. Args: order_by: str Specifies what column to use in ordering the entries in the feed. By position (the default): 'position' returns rows in the order in which they appear in the GUI. Row 1, then row 2, then row 3, and so on. By column: 'column:columnName' sorts rows in ascending order based on the values in the column with the given columnName, where columnName is the value in the header row for that column. reverse: str Specifies whether to sort in descending or ascending order. Reverses default sort order: 'true' results in a descending sort; 'false' (the default) results in an ascending sort. sq: str Structured query on the full text in the worksheet. [columnName][binaryOperator][value] Supported binaryOperators are: - (), for overriding order of operations - = or ==, for strict equality - <> or !=, for strict inequality - and or &&, for boolean and - or or ||, for boolean or """ gdata.client.Query.__init__(self, **kwargs) self.order_by = order_by self.reverse = reverse self.sq = sq def modify_request(self, http_request): gdata.client._add_query_param('orderby', self.order_by, http_request) gdata.client._add_query_param('reverse', self.reverse, http_request) gdata.client._add_query_param('sq', self.sq, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request class TableQuery(ListQuery): pass class CellQuery(gdata.client.Query): def __init__(self, min_row=None, max_row=None, min_col=None, max_col=None, range=None, return_empty=None, **kwargs): """Adds Cells-feed specific query parameters to a request. Args: min_row: str or int Positional number of minimum row returned in query. max_row: str or int Positional number of maximum row returned in query. min_col: str or int Positional number of minimum column returned in query. max_col: str or int Positional number of maximum column returned in query. range: str A single cell or a range of cells. Use standard spreadsheet cell-range notations, using a colon to separate start and end of range. Examples: - 'A1' and 'R1C1' both specify only cell A1. - 'D1:F3' and 'R1C4:R3C6' both specify the rectangle of cells with corners at D1 and F3. return_empty: str If 'true' then empty cells will be returned in the feed. If omitted, the default is 'false'. """ gdata.client.Query.__init__(self, **kwargs) self.min_row = min_row self.max_row = max_row self.min_col = min_col self.max_col = max_col self.range = range self.return_empty = return_empty def modify_request(self, http_request): gdata.client._add_query_param('min-row', self.min_row, http_request) gdata.client._add_query_param('max-row', self.max_row, http_request) gdata.client._add_query_param('min-col', self.min_col, http_request) gdata.client._add_query_param('max-col', self.max_col, http_request) gdata.client._add_query_param('range', self.range, http_request) gdata.client._add_query_param('return-empty', self.return_empty, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found here: http://code.google.com/apis/spreadsheets/docs/3.0/reference.html#Elements """ __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import gdata.data GS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' GSX_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006/extended' INSERT_MODE = 'insert' OVERWRITE_MODE = 'overwrite' WORKSHEETS_REL = 'http://schemas.google.com/spreadsheets/2006#worksheetsfeed' class Error(Exception): pass class FieldMissing(Exception): pass class HeaderNotSet(Error): """The desired column header had no value for the row in the list feed.""" class Cell(atom.core.XmlElement): """The gs:cell element. A cell in the worksheet. The <gs:cell> element can appear only as a child of <atom:entry>. """ _qname = GS_TEMPLATE % 'cell' col = 'col' input_value = 'inputValue' numeric_value = 'numericValue' row = 'row' class ColCount(atom.core.XmlElement): """The gs:colCount element. Indicates the number of columns in the worksheet, including columns that contain only empty cells. The <gs:colCount> element can appear as a child of <atom:entry> or <atom:feed> """ _qname = GS_TEMPLATE % 'colCount' class Field(atom.core.XmlElement): """The gs:field element. A field single cell within a record. Contained in an <atom:entry>. """ _qname = GS_TEMPLATE % 'field' index = 'index' name = 'name' class Column(Field): """The gs:column element.""" _qname = GS_TEMPLATE % 'column' class Data(atom.core.XmlElement): """The gs:data element. A data region of a table. Contained in an <atom:entry> element. """ _qname = GS_TEMPLATE % 'data' column = [Column] insertion_mode = 'insertionMode' num_rows = 'numRows' start_row = 'startRow' class Header(atom.core.XmlElement): """The gs:header element. Indicates which row is the header row. Contained in an <atom:entry>. """ _qname = GS_TEMPLATE % 'header' row = 'row' class RowCount(atom.core.XmlElement): """The gs:rowCount element. Indicates the number of total rows in the worksheet, including rows that contain only empty cells. The <gs:rowCount> element can appear as a child of <atom:entry> or <atom:feed>. """ _qname = GS_TEMPLATE % 'rowCount' class Worksheet(atom.core.XmlElement): """The gs:worksheet element. The worksheet where the table lives.Contained in an <atom:entry>. """ _qname = GS_TEMPLATE % 'worksheet' name = 'name' class Spreadsheet(gdata.data.GDEntry): """An Atom entry which represents a Google Spreadsheet.""" def find_worksheets_feed(self): return self.find_url(WORKSHEETS_REL) FindWorksheetsFeed = find_worksheets_feed class SpreadsheetsFeed(gdata.data.GDFeed): """An Atom feed listing a user's Google Spreadsheets.""" entry = [Spreadsheet] class WorksheetEntry(gdata.data.GDEntry): """An Atom entry representing a single worksheet in a spreadsheet.""" row_count = RowCount col_count = ColCount class WorksheetsFeed(gdata.data.GDFeed): """A feed containing the worksheets in a single spreadsheet.""" entry = [WorksheetEntry] class Table(gdata.data.GDEntry): """An Atom entry that represents a subsection of a worksheet. A table allows you to treat part or all of a worksheet somewhat like a table in a database that is, as a set of structured data items. Tables don't exist until you explicitly create them before you can use a table feed, you have to explicitly define where the table data comes from. """ data = Data header = Header worksheet = Worksheet def get_table_id(self): if self.id.text: return self.id.text.split('/')[-1] return None GetTableId = get_table_id class TablesFeed(gdata.data.GDFeed): """An Atom feed containing the tables defined within a worksheet.""" entry = [Table] class Record(gdata.data.GDEntry): """An Atom entry representing a single record in a table. Note that the order of items in each record is the same as the order of columns in the table definition, which may not match the order of columns in the GUI. """ field = [Field] def value_for_index(self, column_index): for field in self.field: if field.index == column_index: return field.text raise FieldMissing('There is no field for %s' % column_index) ValueForIndex = value_for_index def value_for_name(self, name): for field in self.field: if field.name == name: return field.text raise FieldMissing('There is no field for %s' % name) ValueForName = value_for_name def get_record_id(self): if self.id.text: return self.id.text.split('/')[-1] return None class RecordsFeed(gdata.data.GDFeed): """An Atom feed containing the individuals records in a table.""" entry = [Record] class ListRow(atom.core.XmlElement): """A gsx column value within a row. The local tag in the _qname is blank and must be set to the column name. For example, when adding to a ListEntry, do: col_value = ListRow(text='something') col_value._qname = col_value._qname % 'mycolumnname' """ _qname = '{http://schemas.google.com/spreadsheets/2006/extended}%s' class ListEntry(gdata.data.GDEntry): """An Atom entry representing a worksheet row in the list feed. The values for a particular column can be get and set using x.get_value('columnheader') and x.set_value('columnheader', 'value'). See also the explanation of column names in the ListFeed class. """ def get_value(self, column_name): """Returns the displayed text for the desired column in this row. The formula or input which generated the displayed value is not accessible through the list feed, to see the user's input, use the cells feed. If a column is not present in this spreadsheet, or there is no value for a column in this row, this method will return None. """ values = self.get_elements(column_name, GSX_NAMESPACE) if len(values) == 0: return None return values[0].text def set_value(self, column_name, value): """Changes the value of cell in this row under the desired column name. Warning: if the cell contained a formula, it will be wiped out by setting the value using the list feed since the list feed only works with displayed values. No client side checking is performed on the column_name, you need to ensure that the column_name is the local tag name in the gsx tag for the column. For example, the column_name will not contain special characters, spaces, uppercase letters, etc. """ # Try to find the column in this row to change an existing value. values = self.get_elements(column_name, GSX_NAMESPACE) if len(values) > 0: values[0].text = value else: # There is no value in this row for the desired column, so add a new # gsx:column_name element. new_value = ListRow(text=value) new_value._qname = new_value._qname % (column_name,) self._other_elements.append(new_value) class ListsFeed(gdata.data.GDFeed): """An Atom feed in which each entry represents a row in a worksheet. The first row in the worksheet is used as the column names for the values in each row. If a header cell is empty, then a unique column ID is used for the gsx element name. Spaces in a column name are removed from the name of the corresponding gsx element. Caution: The columnNames are case-insensitive. For example, if you see a <gsx:e-mail> element in a feed, you can't know whether the column heading in the original worksheet was "e-mail" or "E-Mail". Note: If two or more columns have the same name, then subsequent columns of the same name have _n appended to the columnName. For example, if the first column name is "e-mail", followed by columns named "E-Mail" and "E-mail", then the columnNames will be gsx:e-mail, gsx:e-mail_2, and gsx:e-mail_3 respectively. """ entry = [ListEntry] class CellEntry(gdata.data.BatchEntry): """An Atom entry representing a single cell in a worksheet.""" cell = Cell class CellsFeed(gdata.data.BatchFeed): """An Atom feed contains one entry per cell in a worksheet. The cell feed supports batch operations, you can send multiple cell operations in one HTTP request. """ entry = [CellEntry] def batch_set_cell(row, col, input): pass
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import base64 class BasicAuth(object): """Sets the Authorization header as defined in RFC1945""" def __init__(self, user_id, password): self.basic_cookie = base64.encodestring( '%s:%s' % (user_id, password)).strip() def modify_request(self, http_request): http_request.headers['Authorization'] = 'Basic %s' % self.basic_cookie ModifyRequest = modify_request class NoAuth(object): def modify_request(self, http_request): pass
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """HttpClients in this module use httplib to make HTTP requests. This module make HTTP requests based on httplib, but there are environments in which an httplib based approach will not work (if running in Google App Engine for example). In those cases, higher level classes (like AtomService and GDataService) can swap out the HttpClient to transparently use a different mechanism for making HTTP requests. HttpClient: Contains a request method which performs an HTTP call to the server. ProxiedHttpClient: Contains a request method which connects to a proxy using settings stored in operating system environment variables then performs an HTTP call to the endpoint server. """ __author__ = 'api.jscudder (Jeff Scudder)' import types import os import httplib import atom.url import atom.http_interface import socket import base64 import atom.http_core ssl_imported = False ssl = None try: import ssl ssl_imported = True except ImportError: pass class ProxyError(atom.http_interface.Error): pass class TestConfigurationError(Exception): pass DEFAULT_CONTENT_TYPE = 'application/atom+xml' class HttpClient(atom.http_interface.GenericHttpClient): # Added to allow old v1 HttpClient objects to use the new # http_code.HttpClient. Used in unit tests to inject a mock client. v2_http_client = None def __init__(self, headers=None): self.debug = False self.headers = headers or {} def request(self, operation, url, data=None, headers=None): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.http client = atom.http.HttpClient() http_response = client.request('GET', 'http://www.google.com/') Args: operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or DELETE. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. url: The full URL to which the request should be sent. Can be a string or atom.url.Url. headers: dict of strings. HTTP headers which should be sent in the request. """ all_headers = self.headers.copy() if headers: all_headers.update(headers) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: if isinstance(data, types.StringTypes): all_headers['Content-Length'] = str(len(data)) else: raise atom.http_interface.ContentLengthRequired('Unable to calculate ' 'the length of the data parameter. Specify a value for ' 'Content-Length') # Set the content type to the default value if none was set. if 'Content-Type' not in all_headers: all_headers['Content-Type'] = DEFAULT_CONTENT_TYPE if self.v2_http_client is not None: http_request = atom.http_core.HttpRequest(method=operation) atom.http_core.Uri.parse_uri(str(url)).modify_request(http_request) http_request.headers = all_headers if data: http_request._body_parts.append(data) return self.v2_http_client.request(http_request=http_request) if not isinstance(url, atom.url.Url): if isinstance(url, types.StringTypes): url = atom.url.parse_url(url) else: raise atom.http_interface.UnparsableUrlObject('Unable to parse url ' 'parameter because it was not a string or atom.url.Url') connection = self._prepare_connection(url, all_headers) if self.debug: connection.debuglevel = 1 connection.putrequest(operation, self._get_access_url(url), skip_host=True) if url.port is not None: connection.putheader('Host', '%s:%s' % (url.host, url.port)) else: connection.putheader('Host', url.host) # Overcome a bug in Python 2.4 and 2.5 # httplib.HTTPConnection.putrequest adding # HTTP request header 'Host: www.google.com:443' instead of # 'Host: www.google.com', and thus resulting the error message # 'Token invalid - AuthSub token has wrong scope' in the HTTP response. if (url.protocol == 'https' and int(url.port or 443) == 443 and hasattr(connection, '_buffer') and isinstance(connection._buffer, list)): header_line = 'Host: %s:443' % url.host replacement_header_line = 'Host: %s' % url.host try: connection._buffer[connection._buffer.index(header_line)] = ( replacement_header_line) except ValueError: # header_line missing from connection._buffer pass # Send the HTTP headers. for header_name in all_headers: connection.putheader(header_name, all_headers[header_name]) connection.endheaders() # If there is data, send it in the request. if data: if isinstance(data, list): for data_part in data: _send_data_part(data_part, connection) else: _send_data_part(data, connection) # Return the HTTP Response from the server. return connection.getresponse() def _prepare_connection(self, url, headers): if not isinstance(url, atom.url.Url): if isinstance(url, types.StringTypes): url = atom.url.parse_url(url) else: raise atom.http_interface.UnparsableUrlObject('Unable to parse url ' 'parameter because it was not a string or atom.url.Url') if url.protocol == 'https': if not url.port: return httplib.HTTPSConnection(url.host) return httplib.HTTPSConnection(url.host, int(url.port)) else: if not url.port: return httplib.HTTPConnection(url.host) return httplib.HTTPConnection(url.host, int(url.port)) def _get_access_url(self, url): return url.to_string() class ProxiedHttpClient(HttpClient): """Performs an HTTP request through a proxy. The proxy settings are obtained from enviroment variables. The URL of the proxy server is assumed to be stored in the environment variables 'https_proxy' and 'http_proxy' respectively. If the proxy server requires a Basic Auth authorization header, the username and password are expected to be in the 'proxy-username' or 'proxy_username' variable and the 'proxy-password' or 'proxy_password' variable, or in 'http_proxy' or 'https_proxy' as "protocol://[username:password@]host:port". After connecting to the proxy server, the request is completed as in HttpClient.request. """ def _prepare_connection(self, url, headers): proxy_settings = os.environ.get('%s_proxy' % url.protocol) if not proxy_settings: # The request was HTTP or HTTPS, but there was no appropriate proxy set. return HttpClient._prepare_connection(self, url, headers) else: print '!!!!%s' % proxy_settings proxy_auth = _get_proxy_auth(proxy_settings) proxy_netloc = _get_proxy_net_location(proxy_settings) print '!!!!%s' % proxy_auth print '!!!!%s' % proxy_netloc if url.protocol == 'https': # Set any proxy auth headers if proxy_auth: proxy_auth = 'Proxy-authorization: %s' % proxy_auth # Construct the proxy connect command. port = url.port if not port: port = '443' proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (url.host, port) # Set the user agent to send to the proxy if headers and 'User-Agent' in headers: user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent']) else: user_agent = 'User-Agent: python\r\n' proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent) # Find the proxy host and port. proxy_url = atom.url.parse_url(proxy_netloc) if not proxy_url.port: proxy_url.port = '80' # Connect to the proxy server, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((proxy_url.host, int(proxy_url.port))) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status = response.split()[1] if p_status != str(200): raise ProxyError('Error status=%s' % str(p_status)) # Trivial setup for ssl socket. sslobj = None if ssl_imported: sslobj = ssl.wrap_socket(p_sock, None, None) else: sock_ssl = socket.ssl(p_sock, None, None) sslobj = httplib.FakeSocket(p_sock, sock_ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(proxy_url.host) connection.sock = sslobj return connection else: # If protocol was not https. # Find the proxy host and port. proxy_url = atom.url.parse_url(proxy_netloc) if not proxy_url.port: proxy_url.port = '80' if proxy_auth: headers['Proxy-Authorization'] = proxy_auth.strip() return httplib.HTTPConnection(proxy_url.host, int(proxy_url.port)) def _get_access_url(self, url): return url.to_string() def _get_proxy_auth(proxy_settings): """Returns proxy authentication string for header. Will check environment variables for proxy authentication info, starting with proxy(_/-)username and proxy(_/-)password before checking the given proxy_settings for a [protocol://]username:password@host[:port] string. Args: proxy_settings: String from http_proxy or https_proxy environment variable. Returns: Authentication string for proxy, or empty string if no proxy username was found. """ proxy_username = None proxy_password = None proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if not proxy_username: if '@' in proxy_settings: protocol_and_proxy_auth = proxy_settings.split('@')[0].split(':') if len(protocol_and_proxy_auth) == 3: # 3 elements means we have [<protocol>, //<user>, <password>] proxy_username = protocol_and_proxy_auth[1].lstrip('/') proxy_password = protocol_and_proxy_auth[2] elif len(protocol_and_proxy_auth) == 2: # 2 elements means we have [<user>, <password>] proxy_username = protocol_and_proxy_auth[0] proxy_password = protocol_and_proxy_auth[1] if proxy_username: user_auth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) return 'Basic %s\r\n' % (user_auth.strip()) else: return '' def _get_proxy_net_location(proxy_settings): """Returns proxy host and port. Args: proxy_settings: String from http_proxy or https_proxy environment variable. Must be in the form of protocol://[username:password@]host:port Returns: String in the form of protocol://host:port """ if '@' in proxy_settings: protocol = proxy_settings.split(':')[0] netloc = proxy_settings.split('@')[1] return '%s://%s' % (protocol, netloc) else: return proxy_settings def _send_data_part(data, connection): if isinstance(data, types.StringTypes): connection.send(data) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a common interface for all HTTP requests. HttpResponse: Represents the server's response to an HTTP request. Provides an interface identical to httplib.HTTPResponse which is the response expected from higher level classes which use HttpClient.request. GenericHttpClient: Provides an interface (superclass) for an object responsible for making HTTP requests. Subclasses of this object are used in AtomService and GDataService to make requests to the server. By changing the http_client member object, the AtomService is able to make HTTP requests using different logic (for example, when running on Google App Engine, the http_client makes requests using the App Engine urlfetch API). """ __author__ = 'api.jscudder (Jeff Scudder)' import StringIO USER_AGENT = '%s GData-Python/2.0.14' class Error(Exception): pass class UnparsableUrlObject(Error): pass class ContentLengthRequired(Error): pass class HttpResponse(object): def __init__(self, body=None, status=None, reason=None, headers=None): """Constructor for an HttpResponse object. HttpResponse represents the server's response to an HTTP request from the client. The HttpClient.request method returns a httplib.HTTPResponse object and this HttpResponse class is designed to mirror the interface exposed by httplib.HTTPResponse. Args: body: A file like object, with a read() method. The body could also be a string, and the constructor will wrap it so that HttpResponse.read(self) will return the full string. status: The HTTP status code as an int. Example: 200, 201, 404. reason: The HTTP status message which follows the code. Example: OK, Created, Not Found headers: A dictionary containing the HTTP headers in the server's response. A common header in the response is Content-Length. """ if body: if hasattr(body, 'read'): self._body = body else: self._body = StringIO.StringIO(body) else: self._body = None if status is not None: self.status = int(status) else: self.status = None self.reason = reason self._headers = headers or {} def getheader(self, name, default=None): if name in self._headers: return self._headers[name] else: return default def read(self, amt=None): if not amt: return self._body.read() else: return self._body.read(amt) class GenericHttpClient(object): debug = False def __init__(self, http_client, headers=None): """ Args: http_client: An object which provides a request method to make an HTTP request. The request method in GenericHttpClient performs a call-through to the contained HTTP client object. headers: A dictionary containing HTTP headers which should be included in every HTTP request. Common persistent headers include 'User-Agent'. """ self.http_client = http_client self.headers = headers or {} def request(self, operation, url, data=None, headers=None): all_headers = self.headers.copy() if headers: all_headers.update(headers) return self.http_client.request(operation, url, data=data, headers=all_headers) def get(self, url, headers=None): return self.request('GET', url, headers=headers) def post(self, url, data, headers=None): return self.request('POST', url, data=data, headers=headers) def put(self, url, data, headers=None): return self.request('PUT', url, data=data, headers=headers) def delete(self, url, headers=None): return self.request('DELETE', url, headers=headers) class GenericToken(object): """Represents an Authorization token to be added to HTTP requests. Some Authorization headers included calculated fields (digital signatures for example) which are based on the parameters of the HTTP request. Therefore the token is responsible for signing the request and adding the Authorization header. """ def perform_request(self, http_client, operation, url, data=None, headers=None): """For the GenericToken, no Authorization token is set.""" return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. Since the generic token doesn't add an auth header, it is not valid for any scope. """ return False
Python
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AtomService provides CRUD ops. in line with the Atom Publishing Protocol. AtomService: Encapsulates the ability to perform insert, update and delete operations with the Atom Publishing Protocol on which GData is based. An instance can perform query, insertion, deletion, and update. HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request to the specified end point. An AtomService object or a subclass can be used to specify information about the request. """ __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url import atom.http import atom.token_store import os import httplib import urllib import re import base64 import socket import warnings try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom class AtomService(object): """Performs Atom Publishing Protocol CRUD operations. The AtomService contains methods to perform HTTP CRUD operations. """ # Default values for members port = 80 ssl = False # Set the current_token to force the AtomService to use this token # instead of searching for an appropriate token in the token_store. current_token = None auto_store_tokens = True auto_set_current_token = True def _get_override_token(self): return self.current_token def _set_override_token(self, token): self.current_token = token override_token = property(_get_override_token, _set_override_token) #@atom.v1_deprecated('Please use atom.client.AtomPubClient instead.') def __init__(self, server=None, additional_headers=None, application_name='', http_client=None, token_store=None): """Creates a new AtomService client. Args: server: string (optional) The start of a URL for the server to which all operations should be directed. Example: 'www.google.com' additional_headers: dict (optional) Any additional HTTP headers which should be included with CRUD operations. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ self.http_client = http_client or atom.http.ProxiedHttpClient() self.token_store = token_store or atom.token_store.TokenStore() self.server = server self.additional_headers = additional_headers or {} self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( application_name,) # If debug is True, the HTTPConnection will display debug information self._set_debug(False) __init__ = atom.v1_deprecated( 'Please use atom.client.AtomPubClient instead.')( __init__) def _get_debug(self): return self.http_client.debug def _set_debug(self, value): self.http_client.debug = value debug = property(_get_debug, _set_debug, doc='If True, HTTP debug information is printed.') def use_basic_auth(self, username, password, scopes=None): if username is not None and password is not None: if scopes is None: scopes = [atom.token_store.SCOPE_ALL] base_64_string = base64.encodestring('%s:%s' % (username, password)) token = BasicAuthToken('Basic %s' % base_64_string.strip(), scopes=[atom.token_store.SCOPE_ALL]) if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: return self.token_store.add_token(token) return True return False def UseBasicAuth(self, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. Deprecated, use use_basic_auth instead. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. Args: username: str password: str """ self.use_basic_auth(username, password) #@atom.v1_deprecated('Please use atom.client.AtomPubClient for requests.') def request(self, operation, url, data=None, headers=None, url_params=None): if isinstance(url, (str, unicode)): if url.startswith('http:') and self.ssl: # Force all requests to be https if self.ssl is True. url = atom.url.parse_url('https:' + url[5:]) elif not url.startswith('http') and self.ssl: url = atom.url.parse_url('https://%s%s' % (self.server, url)) elif not url.startswith('http'): url = atom.url.parse_url('http://%s%s' % (self.server, url)) else: url = atom.url.parse_url(url) if url_params: for name, value in url_params.iteritems(): url.params[name] = value all_headers = self.additional_headers.copy() if headers: all_headers.update(headers) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: content_length = CalculateDataLength(data) if content_length: all_headers['Content-Length'] = str(content_length) # Find an Authorization token for this URL if one is available. if self.override_token: auth_token = self.override_token else: auth_token = self.token_store.find_token(url) return auth_token.perform_request(self.http_client, operation, url, data=data, headers=all_headers) request = atom.v1_deprecated( 'Please use atom.client.AtomPubClient for requests.')( request) # CRUD operations def Get(self, uri, extra_headers=None, url_params=None, escape_params=True): """Query the APP server with the given URI The uri is the portion of the URI after the server value (server example: 'www.google.com'). Example use: To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dicty (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse The server's response to the GET request. """ return self.request('GET', uri, data=None, headers=extra_headers, url_params=url_params) def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Insert data into an APP server at the given URI. Args: data: string, ElementTree._Element, or something with a __str__ method The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the POST request. """ if extra_headers is None: extra_headers = {} if content_type: extra_headers['Content-Type'] = content_type return self.request('POST', uri, data=data, headers=extra_headers, url_params=url_params) def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request. """ if extra_headers is None: extra_headers = {} if content_type: extra_headers['Content-Type'] = content_type return self.request('PUT', uri, data=data, headers=extra_headers, url_params=url_params) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the DELETE request. """ return self.request('DELETE', uri, data=None, headers=extra_headers, url_params=url_params) class BasicAuthToken(atom.http_interface.GenericToken): def __init__(self, auth_header, scopes=None): """Creates a token used to add Basic Auth headers to HTTP requests. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ self.auth_header = auth_header self.scopes = scopes or [] def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header to the basic auth string.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def __str__(self): return self.auth_header def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False def PrepareConnection(service, full_uri): """Opens a connection to the server based on the full URI. This method is deprecated, instead use atom.http.HttpClient.request. Examines the target URI and the proxy settings, which are set as environment variables, to open a connection with the server. This connection is used to make an HTTP request. Args: service: atom.AtomService or a subclass. It must have a server string which represents the server host to which the request should be made. It may also have a dictionary of additional_headers to send in the HTTP request. full_uri: str Which is the target relative (lacks protocol and host) or absolute URL to be opened. Example: 'https://www.google.com/accounts/ClientLogin' or 'base/feeds/snippets' where the server is set to www.google.com. Returns: A tuple containing the httplib.HTTPConnection and the full_uri for the request. """ deprecation('calling deprecated function PrepareConnection') (server, port, ssl, partial_uri) = ProcessUrl(service, full_uri) if ssl: # destination is https proxy = os.environ.get('https_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: user_auth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % ( user_auth.strip())) else: proxy_authorization = '' proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port) user_agent = 'User-Agent: %s\r\n' % ( service.additional_headers['User-Agent']) proxy_pieces = (proxy_connect + proxy_authorization + user_agent + '\r\n') #now connect, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((p_server,p_port)) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status=response.split()[1] if p_status!=str(200): raise atom.http.ProxyError('Error status=%s' % p_status) # Trivial setup for ssl socket. ssl = socket.ssl(p_sock, None, None) fake_sock = httplib.FakeSocket(p_sock, ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(server) connection.sock=fake_sock full_uri = partial_uri else: connection = httplib.HTTPSConnection(server, port) full_uri = partial_uri else: # destination is http proxy = os.environ.get('http_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: UseBasicAuth(service, proxy_username, proxy_password, True) connection = httplib.HTTPConnection(p_server, p_port) if not full_uri.startswith("http://"): if full_uri.startswith("/"): full_uri = "http://%s%s" % (service.server, full_uri) else: full_uri = "http://%s/%s" % (service.server, full_uri) else: connection = httplib.HTTPConnection(server, port) full_uri = partial_uri return (connection, full_uri) def UseBasicAuth(service, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. Deprecated, use AtomService.use_basic_auth insread. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. The auth header is added to the additional_headers dictionary in the service object. Args: service: atom.AtomService or a subclass which has an additional_headers dict as a member. username: str password: str """ deprecation('calling deprecated function UseBasicAuth') base_64_string = base64.encodestring('%s:%s' % (username, password)) base_64_string = base_64_string.strip() if for_proxy: header_name = 'Proxy-Authorization' else: header_name = 'Authorization' service.additional_headers[header_name] = 'Basic %s' % (base_64_string,) def ProcessUrl(service, url, for_proxy=False): """Processes a passed URL. If the URL does not begin with https?, then the default value for server is used This method is deprecated, use atom.url.parse_url instead. """ if not isinstance(url, atom.url.Url): url = atom.url.parse_url(url) server = url.host ssl = False port = 80 if not server: if hasattr(service, 'server'): server = service.server else: server = service if not url.protocol and hasattr(service, 'ssl'): ssl = service.ssl if hasattr(service, 'port'): port = service.port else: if url.protocol == 'https': ssl = True elif url.protocol == 'http': ssl = False if url.port: port = int(url.port) elif port == 80 and ssl: port = 443 return (server, port, ssl, url.get_request_uri()) def DictionaryToParamList(url_parameters, escape_params=True): """Convert a dictionary of URL arguments into a URL parameter string. This function is deprcated, use atom.url.Url instead. Args: url_parameters: The dictionaty of key-value pairs which will be converted into URL parameters. For example, {'dry-run': 'true', 'foo': 'bar'} will become ['dry-run=true', 'foo=bar']. Returns: A list which contains a string for each key-value pair. The strings are ready to be incorporated into a URL by using '&'.join([] + parameter_list) """ # Choose which function to use when modifying the query and parameters. # Use quote_plus when escape_params is true. transform_op = [str, urllib.quote_plus][bool(escape_params)] # Create a list of tuples containing the escaped version of the # parameter-value pairs. parameter_tuples = [(transform_op(param), transform_op(value)) for param, value in (url_parameters or {}).items()] # Turn parameter-value tuples into a list of strings in the form # 'PARAMETER=VALUE'. return ['='.join(x) for x in parameter_tuples] def BuildUri(uri, url_params=None, escape_params=True): """Converts a uri string and a collection of parameters into a URI. This function is deprcated, use atom.url.Url instead. Args: uri: string url_params: dict (optional) escape_params: boolean (optional) uri: string The start of the desired URI. This string can alrady contain URL parameters. Examples: '/base/feeds/snippets', '/base/feeds/snippets?bq=digital+camera' url_parameters: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: string The URI consisting of the escaped URL parameters appended to the initial uri string. """ # Prepare URL parameters for inclusion into the GET request. parameter_list = DictionaryToParamList(url_params, escape_params) # Append the URL parameters to the URL. if parameter_list: if uri.find('?') != -1: # If there are already URL parameters in the uri string, add the # parameters after a new & character. full_uri = '&'.join([uri] + parameter_list) else: # The uri string did not have any URL parameters (no ? character) # so put a ? between the uri and URL parameters. full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list))) else: full_uri = uri return full_uri def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. This method is deprecated, use atom.http.HttpClient.request instead. Usage example, perform and HTTP GET on http://www.google.com/: import atom.service client = atom.service.AtomService() http_response = client.Get('http://www.google.com/') or you could set the client.server to 'www.google.com' and use the following: client.server = 'www.google.com' http_response = client.Get('/') Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: ElementTree, filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ deprecation('call to deprecated function HttpRequest') full_uri = BuildUri(uri, url_params, escape_params) (connection, full_uri) = PrepareConnection(service, full_uri) if extra_headers is None: extra_headers = {} # Turn on debug mode if the debug member is set. if service.debug: connection.debuglevel = 1 connection.putrequest(operation, full_uri) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if (data and not service.additional_headers.has_key('Content-Length') and not extra_headers.has_key('Content-Length')): content_length = CalculateDataLength(data) if content_length: extra_headers['Content-Length'] = str(content_length) if content_type: extra_headers['Content-Type'] = content_type # Send the HTTP headers. if isinstance(service.additional_headers, dict): for header in service.additional_headers: connection.putheader(header, service.additional_headers[header]) if isinstance(extra_headers, dict): for header in extra_headers: connection.putheader(header, extra_headers[header]) connection.endheaders() # If there is data, send it in the request. if data: if isinstance(data, list): for data_part in data: __SendDataPart(data_part, connection) else: __SendDataPart(data, connection) # Return the HTTP Response from the server. return connection.getresponse() def __SendDataPart(data, connection): """This method is deprecated, use atom.http._send_data_part""" deprecated('call to deprecated function __SendDataPart') if isinstance(data, str): #TODO add handling for unicode. connection.send(data) return elif ElementTree.iselement(data): connection.send(ElementTree.tostring(data)) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return def CalculateDataLength(data): """Attempts to determine the length of the data to send. This method will respond with a length only if the data is a string or and ElementTree element. Args: data: object If this is not a string or ElementTree element this funtion will return None. """ if isinstance(data, str): return len(data) elif isinstance(data, list): return None elif ElementTree.iselement(data): return len(ElementTree.tostring(data)) elif hasattr(data, 'read'): # If this is a file-like object, don't try to guess the length. return None else: return len(str(data)) def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import urlparse import urllib DEFAULT_PROTOCOL = 'http' DEFAULT_PORT = 80 def parse_url(url_string): """Creates a Url object which corresponds to the URL string. This method can accept partial URLs, but it will leave missing members of the Url unset. """ parts = urlparse.urlparse(url_string) url = Url() if parts[0]: url.protocol = parts[0] if parts[1]: host_parts = parts[1].split(':') if host_parts[0]: url.host = host_parts[0] if len(host_parts) > 1: url.port = host_parts[1] if parts[2]: url.path = parts[2] if parts[4]: param_pairs = parts[4].split('&') for pair in param_pairs: pair_parts = pair.split('=') if len(pair_parts) > 1: url.params[urllib.unquote_plus(pair_parts[0])] = ( urllib.unquote_plus(pair_parts[1])) elif len(pair_parts) == 1: url.params[urllib.unquote_plus(pair_parts[0])] = None return url class Url(object): """Represents a URL and implements comparison logic. URL strings which are not identical can still be equivalent, so this object provides a better interface for comparing and manipulating URLs than strings. URL parameters are represented as a dictionary of strings, and defaults are used for the protocol (http) and port (80) if not provided. """ def __init__(self, protocol=None, host=None, port=None, path=None, params=None): self.protocol = protocol self.host = host self.port = port self.path = path self.params = params or {} def to_string(self): url_parts = ['', '', '', '', '', ''] if self.protocol: url_parts[0] = self.protocol if self.host: if self.port: url_parts[1] = ':'.join((self.host, str(self.port))) else: url_parts[1] = self.host if self.path: url_parts[2] = self.path if self.params: url_parts[4] = self.get_param_string() return urlparse.urlunparse(url_parts) def get_param_string(self): param_pairs = [] for key, value in self.params.iteritems(): param_pairs.append('='.join((urllib.quote_plus(key), urllib.quote_plus(str(value))))) return '&'.join(param_pairs) def get_request_uri(self): """Returns the path with the parameters escaped and appended.""" param_string = self.get_param_string() if param_string: return '?'.join([self.path, param_string]) else: return self.path def __cmp__(self, other): if not isinstance(other, Url): return cmp(self.to_string(), str(other)) difference = 0 # Compare the protocol if self.protocol and other.protocol: difference = cmp(self.protocol, other.protocol) elif self.protocol and not other.protocol: difference = cmp(self.protocol, DEFAULT_PROTOCOL) elif not self.protocol and other.protocol: difference = cmp(DEFAULT_PROTOCOL, other.protocol) if difference != 0: return difference # Compare the host difference = cmp(self.host, other.host) if difference != 0: return difference # Compare the port if self.port and other.port: difference = cmp(self.port, other.port) elif self.port and not other.port: difference = cmp(self.port, DEFAULT_PORT) elif not self.port and other.port: difference = cmp(DEFAULT_PORT, other.port) if difference != 0: return difference # Compare the path difference = cmp(self.path, other.path) if difference != 0: return difference # Compare the parameters return cmp(self.params, other.params) def __str__(self): return self.to_string()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a TokenStore class which is designed to manage auth tokens required for different services. Each token is valid for a set of scopes which is the start of a URL. An HTTP client will use a token store to find a valid Authorization header to send in requests to the specified URL. If the HTTP client determines that a token has expired or been revoked, it can remove the token from the store so that it will not be used in future requests. """ __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url SCOPE_ALL = 'http' class TokenStore(object): """Manages Authorization tokens which will be sent in HTTP headers.""" def __init__(self, scoped_tokens=None): self._tokens = scoped_tokens or {} def add_token(self, token): """Adds a new token to the store (replaces tokens with the same scope). Args: token: A subclass of http_interface.GenericToken. The token object is responsible for adding the Authorization header to the HTTP request. The scopes defined in the token are used to determine if the token is valid for a requested scope when find_token is called. Returns: True if the token was added, False if the token was not added becase no scopes were provided. """ if not hasattr(token, 'scopes') or not token.scopes: return False for scope in token.scopes: self._tokens[str(scope)] = token return True def find_token(self, url): """Selects an Authorization header token which can be used for the URL. Args: url: str or atom.url.Url or a list containing the same. The URL which is going to be requested. All tokens are examined to see if any scopes begin match the beginning of the URL. The first match found is returned. Returns: The token object which should execute the HTTP request. If there was no token for the url (the url did not begin with any of the token scopes available), then the atom.http_interface.GenericToken will be returned because the GenericToken calls through to the http client without adding an Authorization header. """ if url is None: return None if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if url in self._tokens: token = self._tokens[url] if token.valid_for_scope(url): return token else: del self._tokens[url] for scope, token in self._tokens.iteritems(): if token.valid_for_scope(url): return token return atom.http_interface.GenericToken() def remove_token(self, token): """Removes the token from the token_store. This method is used when a token is determined to be invalid. If the token was found by find_token, but resulted in a 401 or 403 error stating that the token was invlid, then the token should be removed to prevent future use. Returns: True if a token was found and then removed from the token store. False if the token was not in the TokenStore. """ token_found = False scopes_to_delete = [] for scope, stored_token in self._tokens.iteritems(): if stored_token == token: scopes_to_delete.append(scope) token_found = True for scope in scopes_to_delete: del self._tokens[scope] return token_found def remove_all_tokens(self): self._tokens = {}
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # TODO: add proxy handling. __author__ = 'j.s@google.com (Jeff Scudder)' import os import StringIO import urlparse import urllib import httplib ssl = None try: import ssl except ImportError: pass class Error(Exception): pass class UnknownSize(Error): pass class ProxyError(Error): pass MIME_BOUNDARY = 'END_OF_PART' def get_headers(http_response): """Retrieves all HTTP headers from an HTTP response from the server. This method is provided for backwards compatibility for Python2.2 and 2.3. The httplib.HTTPResponse object in 2.2 and 2.3 does not have a getheaders method so this function will use getheaders if available, but if not it will retrieve a few using getheader. """ if hasattr(http_response, 'getheaders'): return http_response.getheaders() else: headers = [] for header in ( 'location', 'content-type', 'content-length', 'age', 'allow', 'cache-control', 'content-location', 'content-encoding', 'date', 'etag', 'expires', 'last-modified', 'pragma', 'server', 'set-cookie', 'transfer-encoding', 'vary', 'via', 'warning', 'www-authenticate', 'gdata-version'): value = http_response.getheader(header, None) if value is not None: headers.append((header, value)) return headers class HttpRequest(object): """Contains all of the parameters for an HTTP 1.1 request. The HTTP headers are represented by a dictionary, and it is the responsibility of the user to ensure that duplicate field names are combined into one header value according to the rules in section 4.2 of RFC 2616. """ method = None uri = None def __init__(self, uri=None, method=None, headers=None): """Construct an HTTP request. Args: uri: The full path or partial path as a Uri object or a string. method: The HTTP method for the request, examples include 'GET', 'POST', etc. headers: dict of strings The HTTP headers to include in the request. """ self.headers = headers or {} self._body_parts = [] if method is not None: self.method = method if isinstance(uri, (str, unicode)): uri = Uri.parse_uri(uri) self.uri = uri or Uri() def add_body_part(self, data, mime_type, size=None): """Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341. Args: data: str or a file-like object containing a part of the request body. mime_type: str The MIME type describing the data size: int Required if the data is a file like object. If the data is a string, the size is calculated so this parameter is ignored. """ if isinstance(data, str): size = len(data) if size is None: # TODO: support chunked transfer if some of the body is of unknown size. raise UnknownSize('Each part of the body must have a known size.') if 'Content-Length' in self.headers: content_length = int(self.headers['Content-Length']) else: content_length = 0 # If this is the first part added to the body, then this is not a multipart # request. if len(self._body_parts) == 0: self.headers['Content-Type'] = mime_type content_length = size self._body_parts.append(data) elif len(self._body_parts) == 1: # This is the first member in a mime-multipart request, so change the # _body_parts list to indicate a multipart payload. self._body_parts.insert(0, 'Media multipart posting') boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) content_length += len(boundary_string) + size self._body_parts.insert(1, boundary_string) content_length += len('Media multipart posting') # Put the content type of the first part of the body into the multipart # payload. original_type_string = 'Content-Type: %s\r\n\r\n' % ( self.headers['Content-Type'],) self._body_parts.insert(2, original_type_string) content_length += len(original_type_string) boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.append(boundary_string) content_length += len(boundary_string) # Change the headers to indicate this is now a mime multipart request. self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % ( MIME_BOUNDARY,) self.headers['MIME-version'] = '1.0' # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.append(type_string) content_length += len(type_string) self._body_parts.append(data) ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,) self._body_parts.append(ending_boundary_string) content_length += len(ending_boundary_string) else: # This is a mime multipart request. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.insert(-1, boundary_string) content_length += len(boundary_string) + size # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.insert(-1, type_string) content_length += len(type_string) self._body_parts.insert(-1, data) self.headers['Content-Length'] = str(content_length) # I could add an "append_to_body_part" method as well. AddBodyPart = add_body_part def add_form_inputs(self, form_data, mime_type='application/x-www-form-urlencoded'): """Form-encodes and adds data to the request body. Args: form_data: dict or sequnce or two member tuples which contains the form keys and values. mime_type: str The MIME type of the form data being sent. Defaults to 'application/x-www-form-urlencoded'. """ body = urllib.urlencode(form_data) self.add_body_part(body, mime_type) AddFormInputs = add_form_inputs def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) new_request._body_parts = self._body_parts[:] return new_request def _dump(self): """Converts to a printable string for debugging purposes. In order to preserve the request, it does not read from file-like objects in the body. """ output = 'HTTP Request\n method: %s\n url: %s\n headers:\n' % ( self.method, str(self.uri)) for header, value in self.headers.iteritems(): output += ' %s: %s\n' % (header, value) output += ' body sections:\n' i = 0 for part in self._body_parts: if isinstance(part, (str, unicode)): output += ' %s: %s\n' % (i, part) else: output += ' %s: <file like object>\n' % i i += 1 return output def _apply_defaults(http_request): if http_request.uri.scheme is None: if http_request.uri.port == 443: http_request.uri.scheme = 'https' else: http_request.uri.scheme = 'http' class Uri(object): """A URI as used in HTTP 1.1""" scheme = None host = None port = None path = None def __init__(self, scheme=None, host=None, port=None, path=None, query=None): """Constructor for a URI. Args: scheme: str This is usually 'http' or 'https'. host: str The host name or IP address of the desired server. post: int The server's port number. path: str The path of the resource following the host. This begins with a /, example: '/calendar/feeds/default/allcalendars/full' query: dict of strings The URL query parameters. The keys and values are both escaped so this dict should contain the unescaped values. For example {'my key': 'val', 'second': '!!!'} will become '?my+key=val&second=%21%21%21' which is appended to the path. """ self.query = query or {} if scheme is not None: self.scheme = scheme if host is not None: self.host = host if port is not None: self.port = port if path: self.path = path def _get_query_string(self): param_pairs = [] for key, value in self.query.iteritems(): param_pairs.append('='.join((urllib.quote_plus(key), urllib.quote_plus(str(value))))) return '&'.join(param_pairs) def _get_relative_path(self): """Returns the path with the query parameters escaped and appended.""" param_string = self._get_query_string() if self.path is None: path = '/' else: path = self.path if param_string: return '?'.join([path, param_string]) else: return path def _to_string(self): if self.scheme is None and self.port == 443: scheme = 'https' elif self.scheme is None: scheme = 'http' else: scheme = self.scheme if self.path is None: path = '/' else: path = self.path if self.port is None: return '%s://%s%s' % (scheme, self.host, self._get_relative_path()) else: return '%s://%s:%s%s' % (scheme, self.host, str(self.port), self._get_relative_path()) def __str__(self): return self._to_string() def modify_request(self, http_request=None): """Sets HTTP request components based on the URI.""" if http_request is None: http_request = HttpRequest() if http_request.uri is None: http_request.uri = Uri() # Determine the correct scheme. if self.scheme: http_request.uri.scheme = self.scheme if self.port: http_request.uri.port = self.port if self.host: http_request.uri.host = self.host # Set the relative uri path if self.path: http_request.uri.path = self.path if self.query: http_request.uri.query = self.query.copy() return http_request ModifyRequest = modify_request def parse_uri(uri_string): """Creates a Uri object which corresponds to the URI string. This method can accept partial URIs, but it will leave missing members of the Uri unset. """ parts = urlparse.urlparse(uri_string) uri = Uri() if parts[0]: uri.scheme = parts[0] if parts[1]: host_parts = parts[1].split(':') if host_parts[0]: uri.host = host_parts[0] if len(host_parts) > 1: uri.port = int(host_parts[1]) if parts[2]: uri.path = parts[2] if parts[4]: param_pairs = parts[4].split('&') for pair in param_pairs: pair_parts = pair.split('=') if len(pair_parts) > 1: uri.query[urllib.unquote_plus(pair_parts[0])] = ( urllib.unquote_plus(pair_parts[1])) elif len(pair_parts) == 1: uri.query[urllib.unquote_plus(pair_parts[0])] = None return uri parse_uri = staticmethod(parse_uri) ParseUri = parse_uri parse_uri = Uri.parse_uri ParseUri = Uri.parse_uri class HttpResponse(object): status = None reason = None _body = None def __init__(self, status=None, reason=None, headers=None, body=None): self._headers = headers or {} if status is not None: self.status = status if reason is not None: self.reason = reason if body is not None: if hasattr(body, 'read'): self._body = body else: self._body = StringIO.StringIO(body) def getheader(self, name, default=None): if name in self._headers: return self._headers[name] else: return default def getheaders(self): return self._headers def read(self, amt=None): if self._body is None: return None if not amt: return self._body.read() else: return self._body.read(amt) def _dump_response(http_response): """Converts to a string for printing debug messages. Does not read the body since that may consume the content. """ output = 'HttpResponse\n status: %s\n reason: %s\n headers:' % ( http_response.status, http_response.reason) headers = get_headers(http_response) if isinstance(headers, dict): for header, value in headers.iteritems(): output += ' %s: %s\n' % (header, value) else: for pair in headers: output += ' %s: %s\n' % (pair[0], pair[1]) return output class HttpClient(object): """Performs HTTP requests using httplib.""" debug = None def request(self, http_request): return self._http_request(http_request.method, http_request.uri, http_request.headers, http_request._body_parts) Request = request def _get_connection(self, uri, headers=None): """Opens a socket connection to the server to set up an HTTP request. Args: uri: The full URL for the request as a Uri object. headers: A dict of string pairs containing the HTTP headers for the request. """ connection = None if uri.scheme == 'https': if not uri.port: connection = httplib.HTTPSConnection(uri.host) else: connection = httplib.HTTPSConnection(uri.host, int(uri.port)) else: if not uri.port: connection = httplib.HTTPConnection(uri.host) else: connection = httplib.HTTPConnection(uri.host, int(uri.port)) return connection def _http_request(self, method, uri, headers=None, body_parts=None): """Makes an HTTP request using httplib. Args: method: str example: 'GET', 'POST', 'PUT', 'DELETE', etc. uri: str or atom.http_core.Uri headers: dict of strings mapping to strings which will be sent as HTTP headers in the request. body_parts: list of strings, objects with a read method, or objects which can be converted to strings using str. Each of these will be sent in order as the body of the HTTP request. """ if isinstance(uri, (str, unicode)): uri = Uri.parse_uri(uri) connection = self._get_connection(uri, headers=headers) if self.debug: connection.debuglevel = 1 if connection.host != uri.host: connection.putrequest(method, str(uri)) else: connection.putrequest(method, uri._get_relative_path()) # Overcome a bug in Python 2.4 and 2.5 # httplib.HTTPConnection.putrequest adding # HTTP request header 'Host: www.google.com:443' instead of # 'Host: www.google.com', and thus resulting the error message # 'Token invalid - AuthSub token has wrong scope' in the HTTP response. if (uri.scheme == 'https' and int(uri.port or 443) == 443 and hasattr(connection, '_buffer') and isinstance(connection._buffer, list)): header_line = 'Host: %s:443' % uri.host replacement_header_line = 'Host: %s' % uri.host try: connection._buffer[connection._buffer.index(header_line)] = ( replacement_header_line) except ValueError: # header_line missing from connection._buffer pass # Send the HTTP headers. for header_name, value in headers.iteritems(): connection.putheader(header_name, value) connection.endheaders() # If there is data, send it in the request. if body_parts: for part in body_parts: _send_data_part(part, connection) # Return the HTTP Response from the server. return connection.getresponse() def _send_data_part(data, connection): if isinstance(data, (str, unicode)): # I might want to just allow str, not unicode. connection.send(data) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return class ProxiedHttpClient(HttpClient): def _get_connection(self, uri, headers=None): # Check to see if there are proxy settings required for this request. proxy = None if uri.scheme == 'https': proxy = os.environ.get('https_proxy') elif uri.scheme == 'http': proxy = os.environ.get('http_proxy') if not proxy: return HttpClient._get_connection(self, uri, headers=headers) # Now we have the URL of the appropriate proxy server. # Get a username and password for the proxy if required. proxy_auth = _get_proxy_auth() if uri.scheme == 'https': import socket if proxy_auth: proxy_auth = 'Proxy-authorization: %s' % proxy_auth # Construct the proxy connect command. port = uri.port if not port: port = 443 proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (uri.host, port) # Set the user agent to send to the proxy user_agent = '' if headers and 'User-Agent' in headers: user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent']) proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent) # Find the proxy host and port. proxy_uri = Uri.parse_uri(proxy) if not proxy_uri.port: proxy_uri.port = '80' # Connect to the proxy server, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((proxy_uri.host, int(proxy_uri.port))) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status = response.split()[1] if p_status != str(200): raise ProxyError('Error status=%s' % str(p_status)) # Trivial setup for ssl socket. sslobj = None if ssl is not None: sslobj = ssl.wrap_socket(p_sock, None, None) else: sock_ssl = socket.ssl(p_sock, None, Nonesock_) sslobj = httplib.FakeSocket(p_sock, sock_ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(proxy_uri.host) connection.sock = sslobj return connection elif uri.scheme == 'http': proxy_uri = Uri.parse_uri(proxy) if not proxy_uri.port: proxy_uri.port = '80' if proxy_auth: headers['Proxy-Authorization'] = proxy_auth.strip() return httplib.HTTPConnection(proxy_uri.host, int(proxy_uri.port)) return None def _get_proxy_auth(): import base64 proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: user_auth = base64.b64encode('%s:%s' % (proxy_username, proxy_password)) return 'Basic %s\r\n' % (user_auth.strip()) else: return ''
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AtomPubClient provides CRUD ops. in line with the Atom Publishing Protocol. """ __author__ = 'j.s@google.com (Jeff Scudder)' import atom.http_core class Error(Exception): pass class MissingHost(Error): pass class AtomPubClient(object): host = None auth_token = None ssl = False # Whether to force all requests over https def __init__(self, http_client=None, host=None, auth_token=None, source=None, **kwargs): """Creates a new AtomPubClient instance. Args: source: The name of your application. http_client: An object capable of performing HTTP requests through a request method. This object is used to perform the request when the AtomPubClient's request method is called. Used to allow HTTP requests to be directed to a mock server, or use an alternate library instead of the default of httplib to make HTTP requests. host: str The default host name to use if a host is not specified in the requested URI. auth_token: An object which sets the HTTP Authorization header when its modify_request method is called. """ self.http_client = http_client or atom.http_core.ProxiedHttpClient() if host is not None: self.host = host if auth_token is not None: self.auth_token = auth_token self.source = source def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): """Performs an HTTP request to the server indicated. Uses the http_client instance to make the request. Args: method: The HTTP method as a string, usually one of 'GET', 'POST', 'PUT', or 'DELETE' uri: The URI desired as a string or atom.http_core.Uri. http_request: auth_token: An authorization token object whose modify_request method sets the HTTP Authorization header. Returns: The results of calling self.http_client.request. With the default http_client, this is an HTTP response object. """ # Modify the request based on the AtomPubClient settings and parameters # passed in to the request. http_request = self.modify_request(http_request) if isinstance(uri, (str, unicode)): uri = atom.http_core.Uri.parse_uri(uri) if uri is not None: uri.modify_request(http_request) if isinstance(method, (str, unicode)): http_request.method = method # Any unrecognized arguments are assumed to be capable of modifying the # HTTP request. for name, value in kwargs.iteritems(): if value is not None: value.modify_request(http_request) # Default to an http request if the protocol scheme is not set. if http_request.uri.scheme is None: http_request.uri.scheme = 'http' # Override scheme. Force requests over https. if self.ssl: http_request.uri.scheme = 'https' if http_request.uri.path is None: http_request.uri.path = '/' # Add the Authorization header at the very end. The Authorization header # value may need to be calculated using information in the request. if auth_token: auth_token.modify_request(http_request) elif self.auth_token: self.auth_token.modify_request(http_request) # Check to make sure there is a host in the http_request. if http_request.uri.host is None: raise MissingHost('No host provided in request %s %s' % ( http_request.method, str(http_request.uri))) # Perform the fully specified request using the http_client instance. # Sends the request to the server and returns the server's response. return self.http_client.request(http_request) Request = request def get(self, uri=None, auth_token=None, http_request=None, **kwargs): """Performs a request using the GET method, returns an HTTP response.""" return self.request(method='GET', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) Get = get def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): """Sends data using the POST method, returns an HTTP response.""" return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs) Post = post def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): """Sends data using the PUT method, returns an HTTP response.""" return self.request(method='PUT', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs) Put = put def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): """Performs a request using the DELETE method, returns an HTTP response.""" return self.request(method='DELETE', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) Delete = delete def modify_request(self, http_request): """Changes the HTTP request before sending it to the server. Sets the User-Agent HTTP header and fills in the HTTP host portion of the URL if one was not included in the request (for this it uses the self.host member if one is set). This method is called in self.request. Args: http_request: An atom.http_core.HttpRequest() (optional) If one is not provided, a new HttpRequest is instantiated. Returns: An atom.http_core.HttpRequest() with the User-Agent header set and if this client has a value in its host member, the host in the request URL is set. """ if http_request is None: http_request = atom.http_core.HttpRequest() if self.host is not None and http_request.uri.host is None: http_request.uri.host = self.host # Set the user agent header for logging purposes. if self.source: http_request.headers['User-Agent'] = '%s gdata-py/2.0.14' % self.source else: http_request.headers['User-Agent'] = 'gdata-py/2.0.14' return http_request ModifyRequest = modify_request
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import StringIO import pickle import os.path import tempfile import atom.http_core class Error(Exception): pass class NoRecordingFound(Error): pass class MockHttpClient(object): debug = None real_client = None last_request_was_live = False # The following members are used to construct the session cache temp file # name. # These are combined to form the file name # /tmp/cache_prefix.cache_case_name.cache_test_name cache_name_prefix = 'gdata_live_test' cache_case_name = '' cache_test_name = '' def __init__(self, recordings=None, real_client=None): self._recordings = recordings or [] if real_client is not None: self.real_client = real_client def add_response(self, http_request, status, reason, headers=None, body=None): response = MockHttpResponse(status, reason, headers, body) # TODO Scrub the request and the response. self._recordings.append((http_request._copy(), response)) AddResponse = add_response def request(self, http_request): """Provide a recorded response, or record a response for replay. If the real_client is set, the request will be made using the real_client, and the response from the server will be recorded. If the real_client is None (the default), this method will examine the recordings and find the first which matches. """ request = http_request._copy() _scrub_request(request) if self.real_client is None: self.last_request_was_live = False for recording in self._recordings: if _match_request(recording[0], request): return recording[1] else: # Pass along the debug settings to the real client. self.real_client.debug = self.debug # Make an actual request since we can use the real HTTP client. self.last_request_was_live = True response = self.real_client.request(http_request) scrubbed_response = _scrub_response(response) self.add_response(request, scrubbed_response.status, scrubbed_response.reason, dict(atom.http_core.get_headers(scrubbed_response)), scrubbed_response.read()) # Return the recording which we just added. return self._recordings[-1][1] raise NoRecordingFound('No recoding was found for request: %s %s' % ( request.method, str(request.uri))) Request = request def _save_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'wb') pickle.dump(self._recordings, recording_file) recording_file.close() def _load_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'rb') self._recordings = pickle.load(recording_file) recording_file.close() def _delete_recordings(self, filename): full_path = os.path.join(tempfile.gettempdir(), filename) if os.path.exists(full_path): os.remove(full_path) def _load_or_use_client(self, filename, http_client): if os.path.exists(os.path.join(tempfile.gettempdir(), filename)): self._load_recordings(filename) else: self.real_client = http_client def use_cached_session(self, name=None, real_http_client=None): """Attempts to load recordings from a previous live request. If a temp file with the recordings exists, then it is used to fulfill requests. If the file does not exist, then a real client is used to actually make the desired HTTP requests. Requests and responses are recorded and will be written to the desired temprary cache file when close_session is called. Args: name: str (optional) The file name of session file to be used. The file is loaded from the temporary directory of this machine. If no name is passed in, a default name will be constructed using the cache_name_prefix, cache_case_name, and cache_test_name of this object. real_http_client: atom.http_core.HttpClient the real client to be used if the cached recordings are not found. If the default value is used, this will be an atom.http_core.HttpClient. """ if real_http_client is None: real_http_client = atom.http_core.HttpClient() if name is None: self._recordings_cache_name = self.get_cache_file_name() else: self._recordings_cache_name = name self._load_or_use_client(self._recordings_cache_name, real_http_client) def close_session(self): """Saves recordings in the temporary file named in use_cached_session.""" if self.real_client is not None: self._save_recordings(self._recordings_cache_name) def delete_session(self, name=None): """Removes recordings from a previous live request.""" if name is None: self._delete_recordings(self._recordings_cache_name) else: self._delete_recordings(name) def get_cache_file_name(self): return '%s.%s.%s' % (self.cache_name_prefix, self.cache_case_name, self.cache_test_name) def _dump(self): """Provides debug information in a string.""" output = 'MockHttpClient\n real_client: %s\n cache file name: %s\n' % ( self.real_client, self.get_cache_file_name()) output += ' recordings:\n' i = 0 for recording in self._recordings: output += ' recording %i is for: %s %s\n' % ( i, recording[0].method, str(recording[0].uri)) i += 1 return output def _match_request(http_request, stored_request): """Determines whether a request is similar enough to a stored request to cause the stored response to be returned.""" # Check to see if the host names match. if (http_request.uri.host is not None and http_request.uri.host != stored_request.uri.host): return False # Check the request path in the URL (/feeds/private/full/x) elif http_request.uri.path != stored_request.uri.path: return False # Check the method used in the request (GET, POST, etc.) elif http_request.method != stored_request.method: return False # If there is a gsession ID in either request, make sure that it is matched # exactly. elif ('gsessionid' in http_request.uri.query or 'gsessionid' in stored_request.uri.query): if 'gsessionid' not in stored_request.uri.query: return False elif 'gsessionid' not in http_request.uri.query: return False elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']): return False # Ignores differences in the query params (?start-index=5&max-results=20), # the body of the request, the port number, HTTP headers, just to name a # few. return True def _scrub_request(http_request): """ Removes email address and password from a client login request. Since the mock server saves the request and response in plantext, sensitive information like the password should be removed before saving the recordings. At the moment only requests sent to a ClientLogin url are scrubbed. """ if (http_request and http_request.uri and http_request.uri.path and http_request.uri.path.endswith('ClientLogin')): # Remove the email and password from a ClientLogin request. http_request._body_parts = [] http_request.add_form_inputs( {'form_data': 'client login request has been scrubbed'}) else: # We can remove the body of the post from the recorded request, since # the request body is not used when finding a matching recording. http_request._body_parts = [] return http_request def _scrub_response(http_response): return http_response class EchoHttpClient(object): """Sends the request data back in the response. Used to check the formatting of the request as it was sent. Always responds with a 200 OK, and some information from the HTTP request is returned in special Echo-X headers in the response. The following headers are added in the response: 'Echo-Host': The host name and port number to which the HTTP connection is made. If no port was passed in, the header will contain host:None. 'Echo-Uri': The path portion of the URL being requested. /example?x=1&y=2 'Echo-Scheme': The beginning of the URL, usually 'http' or 'https' 'Echo-Method': The HTTP method being used, 'GET', 'POST', 'PUT', etc. """ def request(self, http_request): return self._http_request(http_request.uri, http_request.method, http_request.headers, http_request._body_parts) def _http_request(self, uri, method, headers=None, body_parts=None): body = StringIO.StringIO() response = atom.http_core.HttpResponse(status=200, reason='OK', body=body) if headers is None: response._headers = {} else: # Copy headers from the request to the response but convert values to # strings. Server response headers always come in as strings, so an int # should be converted to a corresponding string when echoing. for header, value in headers.iteritems(): response._headers[header] = str(value) response._headers['Echo-Host'] = '%s:%s' % (uri.host, str(uri.port)) response._headers['Echo-Uri'] = uri._get_relative_path() response._headers['Echo-Scheme'] = uri.scheme response._headers['Echo-Method'] = method for part in body_parts: if isinstance(part, str): body.write(part) elif hasattr(part, 'read'): body.write(part.read()) body.seek(0) return response class SettableHttpClient(object): """An HTTP Client which responds with the data given in set_response.""" def __init__(self, status, reason, body, headers): """Configures the response for the server. See set_response for details on the arguments to the constructor. """ self.set_response(status, reason, body, headers) self.last_request = None def set_response(self, status, reason, body, headers): """Determines the response which will be sent for each request. Args: status: An int for the HTTP status code, example: 200, 404, etc. reason: String for the HTTP reason, example: OK, NOT FOUND, etc. body: The body of the HTTP response as a string or a file-like object (something with a read method). headers: dict of strings containing the HTTP headers in the response. """ self.response = atom.http_core.HttpResponse(status=status, reason=reason, body=body) self.response._headers = headers.copy() def request(self, http_request): self.last_request = http_request return self.response class MockHttpResponse(atom.http_core.HttpResponse): def __init__(self, status=None, reason=None, headers=None, body=None): self._headers = headers or {} if status is not None: self.status = status if reason is not None: self.reason = reason if body is not None: # Instead of using a file-like object for the body, store as a string # so that reads can be repeated. if hasattr(body, 'read'): self._body = body.read() else: self._body = body def read(self): return self._body
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MockService provides CRUD ops. for mocking calls to AtomPub services. MockService: Exposes the publicly used methods of AtomService to provide a mock interface which can be used in unit tests. """ import atom.service import pickle __author__ = 'api.jscudder (Jeffrey Scudder)' # Recordings contains pairings of HTTP MockRequest objects with MockHttpResponse objects. recordings = [] # If set, the mock service HttpRequest are actually made through this object. real_request_handler = None def ConcealValueWithSha(source): import sha return sha.new(source[:-5]).hexdigest() def DumpRecordings(conceal_func=ConcealValueWithSha): if conceal_func: for recording_pair in recordings: recording_pair[0].ConcealSecrets(conceal_func) return pickle.dumps(recordings) def LoadRecordings(recordings_file_or_string): if isinstance(recordings_file_or_string, str): atom.mock_service.recordings = pickle.loads(recordings_file_or_string) elif hasattr(recordings_file_or_string, 'read'): atom.mock_service.recordings = pickle.loads( recordings_file_or_string.read()) def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Simulates an HTTP call to the server, makes an actual HTTP request if real_request_handler is set. This function operates in two different modes depending on if real_request_handler is set or not. If real_request_handler is not set, HttpRequest will look in this module's recordings list to find a response which matches the parameters in the function call. If real_request_handler is set, this function will call real_request_handler.HttpRequest, add the response to the recordings list, and respond with the actual response. Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: ElementTree, filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ full_uri = atom.service.BuildUri(uri, url_params, escape_params) (server, port, ssl, uri) = atom.service.ProcessUrl(service, uri) current_request = MockRequest(operation, full_uri, host=server, ssl=ssl, data=data, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) # If the request handler is set, we should actually make the request using # the request handler and record the response to replay later. if real_request_handler: response = real_request_handler.HttpRequest(service, operation, data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) # TODO: need to copy the HTTP headers from the real response into the # recorded_response. recorded_response = MockHttpResponse(body=response.read(), status=response.status, reason=response.reason) # Insert a tuple which maps the request to the response object returned # when making an HTTP call using the real_request_handler. recordings.append((current_request, recorded_response)) return recorded_response else: # Look through available recordings to see if one matches the current # request. for request_response_pair in recordings: if request_response_pair[0].IsMatch(current_request): return request_response_pair[1] return None class MockRequest(object): """Represents a request made to an AtomPub server. These objects are used to determine if a client request matches a recorded HTTP request to determine what the mock server's response will be. """ def __init__(self, operation, uri, host=None, ssl=False, port=None, data=None, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Constructor for a MockRequest Args: operation: str One of 'GET', 'POST', 'PUT', or 'DELETE' this is the HTTP operation requested on the resource. uri: str The URL describing the resource to be modified or feed to be retrieved. This should include the protocol (http/https) and the host (aka domain). For example, these are some valud full_uris: 'http://example.com', 'https://www.google.com/accounts/ClientLogin' host: str (optional) The server name which will be placed at the beginning of the URL if the uri parameter does not begin with 'http'. Examples include 'example.com', 'www.google.com', 'www.blogger.com'. ssl: boolean (optional) If true, the request URL will begin with https instead of http. data: ElementTree, filestream, list of parts, or other object which can be converted to a string. (optional) Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, the constructor will read the entire file into memory. If the data is a list of parts to be sent, each part will be evaluated and stored. extra_headers: dict (optional) HTTP headers included in the request. url_params: dict (optional) Key value pairs which should be added to the URL as URL parameters in the request. For example uri='/', url_parameters={'foo':'1','bar':'2'} could become '/?foo=1&bar=2'. escape_params: boolean (optional) Perform URL escaping on the keys and values specified in url_params. Defaults to True. content_type: str (optional) Provides the MIME type of the data being sent. """ self.operation = operation self.uri = _ConstructFullUrlBase(uri, host=host, ssl=ssl) self.data = data self.extra_headers = extra_headers self.url_params = url_params or {} self.escape_params = escape_params self.content_type = content_type def ConcealSecrets(self, conceal_func): """Conceal secret data in this request.""" if self.extra_headers.has_key('Authorization'): self.extra_headers['Authorization'] = conceal_func( self.extra_headers['Authorization']) def IsMatch(self, other_request): """Check to see if the other_request is equivalent to this request. Used to determine if a recording matches an incoming request so that a recorded response should be sent to the client. The matching is not exact, only the operation and URL are examined currently. Args: other_request: MockRequest The request which we want to check this (self) MockRequest against to see if they are equivalent. """ # More accurate matching logic will likely be required. return (self.operation == other_request.operation and self.uri == other_request.uri) def _ConstructFullUrlBase(uri, host=None, ssl=False): """Puts URL components into the form http(s)://full.host.strinf/uri/path Used to construct a roughly canonical URL so that URLs which begin with 'http://example.com/' can be compared to a uri of '/' when the host is set to 'example.com' If the uri contains 'http://host' already, the host and ssl parameters are ignored. Args: uri: str The path component of the URL, examples include '/' host: str (optional) The host name which should prepend the URL. Example: 'example.com' ssl: boolean (optional) If true, the returned URL will begin with https instead of http. Returns: String which has the form http(s)://example.com/uri/string/contents """ if uri.startswith('http'): return uri if ssl: return 'https://%s%s' % (host, uri) else: return 'http://%s%s' % (host, uri) class MockHttpResponse(object): """Returned from MockService crud methods as the server's response.""" def __init__(self, body=None, status=None, reason=None, headers=None): """Construct a mock HTTPResponse and set members. Args: body: str (optional) The HTTP body of the server's response. status: int (optional) reason: str (optional) headers: dict (optional) """ self.body = body self.status = status self.reason = reason self.headers = headers or {} def read(self): return self.body def getheader(self, header_name): return self.headers[header_name]
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core XML_TEMPLATE = '{http://www.w3.org/XML/1998/namespace}%s' ATOM_TEMPLATE = '{http://www.w3.org/2005/Atom}%s' APP_TEMPLATE_V1 = '{http://purl.org/atom/app#}%s' APP_TEMPLATE_V2 = '{http://www.w3.org/2007/app}%s' class Name(atom.core.XmlElement): """The atom:name element.""" _qname = ATOM_TEMPLATE % 'name' class Email(atom.core.XmlElement): """The atom:email element.""" _qname = ATOM_TEMPLATE % 'email' class Uri(atom.core.XmlElement): """The atom:uri element.""" _qname = ATOM_TEMPLATE % 'uri' class Person(atom.core.XmlElement): """A foundation class which atom:author and atom:contributor extend. A person contains information like name, email address, and web page URI for an author or contributor to an Atom feed. """ name = Name email = Email uri = Uri class Author(Person): """The atom:author element. An author is a required element in Feed unless each Entry contains an Author. """ _qname = ATOM_TEMPLATE % 'author' class Contributor(Person): """The atom:contributor element.""" _qname = ATOM_TEMPLATE % 'contributor' class Link(atom.core.XmlElement): """The atom:link element.""" _qname = ATOM_TEMPLATE % 'link' href = 'href' rel = 'rel' type = 'type' hreflang = 'hreflang' title = 'title' length = 'length' class Generator(atom.core.XmlElement): """The atom:generator element.""" _qname = ATOM_TEMPLATE % 'generator' uri = 'uri' version = 'version' class Text(atom.core.XmlElement): """A foundation class from which atom:title, summary, etc. extend. This class should never be instantiated. """ type = 'type' class Title(Text): """The atom:title element.""" _qname = ATOM_TEMPLATE % 'title' class Subtitle(Text): """The atom:subtitle element.""" _qname = ATOM_TEMPLATE % 'subtitle' class Rights(Text): """The atom:rights element.""" _qname = ATOM_TEMPLATE % 'rights' class Summary(Text): """The atom:summary element.""" _qname = ATOM_TEMPLATE % 'summary' class Content(Text): """The atom:content element.""" _qname = ATOM_TEMPLATE % 'content' src = 'src' class Category(atom.core.XmlElement): """The atom:category element.""" _qname = ATOM_TEMPLATE % 'category' term = 'term' scheme = 'scheme' label = 'label' class Id(atom.core.XmlElement): """The atom:id element.""" _qname = ATOM_TEMPLATE % 'id' class Icon(atom.core.XmlElement): """The atom:icon element.""" _qname = ATOM_TEMPLATE % 'icon' class Logo(atom.core.XmlElement): """The atom:logo element.""" _qname = ATOM_TEMPLATE % 'logo' class Draft(atom.core.XmlElement): """The app:draft element which indicates if this entry should be public.""" _qname = (APP_TEMPLATE_V1 % 'draft', APP_TEMPLATE_V2 % 'draft') class Control(atom.core.XmlElement): """The app:control element indicating restrictions on publication. The APP control element may contain a draft element indicating whether or not this entry should be publicly available. """ _qname = (APP_TEMPLATE_V1 % 'control', APP_TEMPLATE_V2 % 'control') draft = Draft class Date(atom.core.XmlElement): """A parent class for atom:updated, published, etc.""" class Updated(Date): """The atom:updated element.""" _qname = ATOM_TEMPLATE % 'updated' class Published(Date): """The atom:published element.""" _qname = ATOM_TEMPLATE % 'published' class LinkFinder(object): """An "interface" providing methods to find link elements Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in Atom entries and feeds. """ def find_url(self, rel): """Returns the URL in a link with the desired rel value.""" for link in self.link: if link.rel == rel and link.href: return link.href return None FindUrl = find_url def get_link(self, rel): """Returns a link object which has the desired rel value. If you are interested in the URL instead of the link object, consider using find_url instead. """ for link in self.link: if link.rel == rel and link.href: return link return None GetLink = get_link def find_self_link(self): """Find the first link with rel set to 'self' Returns: A str containing the link's href or None if none of the links had rel equal to 'self' """ return self.find_url('self') FindSelfLink = find_self_link def get_self_link(self): return self.get_link('self') GetSelfLink = get_self_link def find_edit_link(self): return self.find_url('edit') FindEditLink = find_edit_link def get_edit_link(self): return self.get_link('edit') GetEditLink = get_edit_link def find_edit_media_link(self): link = self.find_url('edit-media') # Search for media-edit as well since Picasa API used media-edit instead. if link is None: return self.find_url('media-edit') return link FindEditMediaLink = find_edit_media_link def get_edit_media_link(self): link = self.get_link('edit-media') if link is None: return self.get_link('media-edit') return link GetEditMediaLink = get_edit_media_link def find_next_link(self): return self.find_url('next') FindNextLink = find_next_link def get_next_link(self): return self.get_link('next') GetNextLink = get_next_link def find_license_link(self): return self.find_url('license') FindLicenseLink = find_license_link def get_license_link(self): return self.get_link('license') GetLicenseLink = get_license_link def find_alternate_link(self): return self.find_url('alternate') FindAlternateLink = find_alternate_link def get_alternate_link(self): return self.get_link('alternate') GetAlternateLink = get_alternate_link class FeedEntryParent(atom.core.XmlElement, LinkFinder): """A super class for atom:feed and entry, contains shared attributes""" author = [Author] category = [Category] contributor = [Contributor] id = Id link = [Link] rights = Rights title = Title updated = Updated def __init__(self, atom_id=None, text=None, *args, **kwargs): if atom_id is not None: self.id = atom_id atom.core.XmlElement.__init__(self, text=text, *args, **kwargs) class Source(FeedEntryParent): """The atom:source element.""" _qname = ATOM_TEMPLATE % 'source' generator = Generator icon = Icon logo = Logo subtitle = Subtitle class Entry(FeedEntryParent): """The atom:entry element.""" _qname = ATOM_TEMPLATE % 'entry' content = Content published = Published source = Source summary = Summary control = Control class Feed(Source): """The atom:feed element which contains entries.""" _qname = ATOM_TEMPLATE % 'feed' entry = [Entry] class ExtensionElement(atom.core.XmlElement): """Provided for backwards compatibility to the v1 atom.ExtensionElement.""" def __init__(self, tag=None, namespace=None, attributes=None, children=None, text=None, *args, **kwargs): if namespace: self._qname = '{%s}%s' % (namespace, tag) else: self._qname = tag self.children = children or [] self.attributes = attributes or {} self.text = text _BecomeChildElement = atom.core.XmlElement._become_child
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains classes representing Atom elements. Module objective: provide data classes for Atom constructs. These classes hide the XML-ness of Atom and provide a set of native Python classes to interact with. Conversions to and from XML should only be necessary when the Atom classes "touch the wire" and are sent over HTTP. For this reason this module provides methods and functions to convert Atom classes to and from strings. For more information on the Atom data model, see RFC 4287 (http://www.ietf.org/rfc/rfc4287.txt) AtomBase: A foundation class on which Atom classes are built. It handles the parsing of attributes and children which are common to all Atom classes. By default, the AtomBase class translates all XML child nodes into ExtensionElements. ExtensionElement: Atom allows Atom objects to contain XML which is not part of the Atom specification, these are called extension elements. If a classes parser encounters an unexpected XML construct, it is translated into an ExtensionElement instance. ExtensionElement is designed to fully capture the information in the XML. Child nodes in an XML extension are turned into ExtensionElements as well. """ __author__ = 'api.jscudder (Jeffrey Scudder)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import warnings # XML namespaces which are often used in Atom entities. ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom' ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s' APP_NAMESPACE = 'http://purl.org/atom/app#' APP_TEMPLATE = '{http://purl.org/atom/app#}%s' # This encoding is used for converting strings before translating the XML # into an object. XML_STRING_ENCODING = 'utf-8' # The desired string encoding for object members. set or monkey-patch to # unicode if you want object members to be Python unicode strings, instead of # encoded strings MEMBER_STRING_ENCODING = 'utf-8' #MEMBER_STRING_ENCODING = unicode # If True, all methods which are exclusive to v1 will raise a # DeprecationWarning ENABLE_V1_WARNINGS = False def v1_deprecated(warning=None): """Shows a warning if ENABLE_V1_WARNINGS is True. Function decorator used to mark methods used in v1 classes which may be removed in future versions of the library. """ warning = warning or '' # This closure is what is returned from the deprecated function. def mark_deprecated(f): # The deprecated_function wraps the actual call to f. def optional_warn_function(*args, **kwargs): if ENABLE_V1_WARNINGS: warnings.warn(warning, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) # Preserve the original name to avoid masking all decorated functions as # 'deprecated_function' try: optional_warn_function.func_name = f.func_name except TypeError: pass # In Python2.3 we can't set the func_name return optional_warn_function return mark_deprecated def CreateClassFromXMLString(target_class, xml_string, string_encoding=None): """Creates an instance of the target class from the string contents. Args: target_class: class The class which will be instantiated and populated with the contents of the XML. This class must have a _tag and a _namespace class variable. xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. string_encoding: str The character encoding which the xml_string should be converted to before it is interpreted and translated into objects. The default is None in which case the string encoding is not changed. Returns: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class. """ encoding = string_encoding or XML_STRING_ENCODING if encoding and isinstance(xml_string, unicode): xml_string = xml_string.encode(encoding) tree = ElementTree.fromstring(xml_string) return _CreateClassFromElementTree(target_class, tree) CreateClassFromXMLString = v1_deprecated( 'Please use atom.core.parse with atom.data classes instead.')( CreateClassFromXMLString) def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None): """Instantiates the class and populates members according to the tree. Note: Only use this function with classes that have _namespace and _tag class members. Args: target_class: class The class which will be instantiated and populated with the contents of the XML. tree: ElementTree An element tree whose contents will be converted into members of the new target_class instance. namespace: str (optional) The namespace which the XML tree's root node must match. If omitted, the namespace defaults to the _namespace of the target class. tag: str (optional) The tag which the XML tree's root node must match. If omitted, the tag defaults to the _tag class member of the target class. Returns: An instance of the target class - or None if the tag and namespace of the XML tree's root node did not match the desired namespace and tag. """ if namespace is None: namespace = target_class._namespace if tag is None: tag = target_class._tag if tree.tag == '{%s}%s' % (namespace, tag): target = target_class() target._HarvestElementTree(tree) return target else: return None class ExtensionContainer(object): def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text __init__ = v1_deprecated( 'Please use data model classes in atom.data instead.')( __init__) # Three methods to create an object from an ElementTree def _HarvestElementTree(self, tree): # Fill in the instance members from the contents of the XML tree. for child in tree: self._ConvertElementTreeToMember(child) for attribute, value in tree.attrib.iteritems(): self._ConvertElementAttributeToMember(attribute, value) # Encode the text string according to the desired encoding type. (UTF-8) if tree.text: if MEMBER_STRING_ENCODING is unicode: self.text = tree.text else: self.text = tree.text.encode(MEMBER_STRING_ENCODING) def _ConvertElementTreeToMember(self, child_tree, current_class=None): self.extension_elements.append(_ExtensionElementFromElementTree( child_tree)) def _ConvertElementAttributeToMember(self, attribute, value): # Encode the attribute value's string with the desired type Default UTF-8 if value: if MEMBER_STRING_ENCODING is unicode: self.extension_attributes[attribute] = value else: self.extension_attributes[attribute] = value.encode( MEMBER_STRING_ENCODING) # One method to create an ElementTree from an object def _AddMembersToElementTree(self, tree): for child in self.extension_elements: child._BecomeChildElement(tree) for attribute, value in self.extension_attributes.iteritems(): if value: if isinstance(value, unicode) or MEMBER_STRING_ENCODING is unicode: tree.attrib[attribute] = value else: # Decode the value from the desired encoding (default UTF-8). tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING) if self.text: if isinstance(self.text, unicode) or MEMBER_STRING_ENCODING is unicode: tree.text = self.text else: tree.text = self.text.decode(MEMBER_STRING_ENCODING) def FindExtensions(self, tag=None, namespace=None): """Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. Args: tag: str (optional) The desired tag namespace: str (optional) The desired namespace Returns: A list of elements whose tag and/or namespace match the parameters values """ results = [] if tag and namespace: for element in self.extension_elements: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.extension_elements: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.extension_elements: if element.namespace == namespace: results.append(element) else: for element in self.extension_elements: results.append(element) return results class AtomBase(ExtensionContainer): _children = {} _attributes = {} def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text __init__ = v1_deprecated( 'Please use data model classes in atom.data instead.')( __init__) def _ConvertElementTreeToMember(self, child_tree): # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(_CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, _CreateClassFromElementTree(member_class, child_tree)) else: ExtensionContainer._ConvertElementTreeToMember(self, child_tree) def _ConvertElementAttributeToMember(self, attribute, value): # Find the attribute in this class's list of attributes. if self.__class__._attributes.has_key(attribute): # Find the member of this class which corresponds to the XML attribute # (lookup in current_class._attributes) and set this member to the # desired value (using self.__dict__). if value: # Encode the string to capture non-ascii characters (default UTF-8) if MEMBER_STRING_ENCODING is unicode: setattr(self, self.__class__._attributes[attribute], value) else: setattr(self, self.__class__._attributes[attribute], value.encode(MEMBER_STRING_ENCODING)) else: ExtensionContainer._ConvertElementAttributeToMember( self, attribute, value) # Three methods to create an ElementTree from an object def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: if isinstance(member, unicode) or MEMBER_STRING_ENCODING is unicode: tree.attrib[xml_attribute] = member else: tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING) # Lastly, call the ExtensionContainers's _AddMembersToElementTree to # convert any extension attributes. ExtensionContainer._AddMembersToElementTree(self, tree) def _BecomeChildElement(self, tree): """ Note: Only for use with classes that have a _tag and _namespace class member. It is in AtomBase so that it can be inherited but it should not be called on instances of AtomBase. """ new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.__class__._tag) self._AddMembersToElementTree(new_child) def _ToElementTree(self): """ Note, this method is designed to be used only with classes that have a _tag and _namespace. It is placed in AtomBase for inheritance but should not be called on this class. """ new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.__class__._tag)) self._AddMembersToElementTree(new_tree) return new_tree def ToString(self, string_encoding='UTF-8'): """Converts the Atom object to a string containing XML.""" return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding) def __str__(self): return self.ToString() class Name(AtomBase): """The atom:name element""" _tag = 'name' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Name Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return CreateClassFromXMLString(Name, xml_string) class Email(AtomBase): """The atom:email element""" _tag = 'email' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Email Args: extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailFromString(xml_string): return CreateClassFromXMLString(Email, xml_string) class Uri(AtomBase): """The atom:uri element""" _tag = 'uri' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Uri Args: extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UriFromString(xml_string): return CreateClassFromXMLString(Uri, xml_string) class Person(AtomBase): """A foundation class from which atom:author and atom:contributor extend. A person contains information like name, email address, and web page URI for an author or contributor to an Atom feed. """ _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name) _children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email) _children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri) def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Foundation from which author and contributor are derived. The constructor is provided for illustrative purposes, you should not need to instantiate a Person. Args: name: Name The person's name email: Email The person's email address uri: Uri The URI of the person's webpage extension_elements: list A list of ExtensionElement instances which are children of this element. extension_attributes: dict A dictionary of strings which are the values for additional XML attributes of this element. text: String The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text class Author(Person): """The atom:author element An author is a required element in Feed. """ _tag = 'author' _namespace = ATOM_NAMESPACE _children = Person._children.copy() _attributes = Person._attributes.copy() #_children = {} #_attributes = {} def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Author Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def AuthorFromString(xml_string): return CreateClassFromXMLString(Author, xml_string) class Contributor(Person): """The atom:contributor element""" _tag = 'contributor' _namespace = ATOM_NAMESPACE _children = Person._children.copy() _attributes = Person._attributes.copy() def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Contributor Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def ContributorFromString(xml_string): return CreateClassFromXMLString(Contributor, xml_string) class Link(AtomBase): """The atom:link element""" _tag = 'link' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['href'] = 'href' _attributes['type'] = 'type' _attributes['title'] = 'title' _attributes['length'] = 'length' _attributes['hreflang'] = 'hreflang' def __init__(self, href=None, rel=None, link_type=None, hreflang=None, title=None, length=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Link Args: href: string The href attribute of the link rel: string type: string hreflang: string The language for the href title: string length: string The length of the href's destination extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.href = href self.rel = rel self.type = link_type self.hreflang = hreflang self.title = title self.length = length self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LinkFromString(xml_string): return CreateClassFromXMLString(Link, xml_string) class Generator(AtomBase): """The atom:generator element""" _tag = 'generator' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['uri'] = 'uri' _attributes['version'] = 'version' def __init__(self, uri=None, version=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Generator Args: uri: string version: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.uri = uri self.version = version self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GeneratorFromString(xml_string): return CreateClassFromXMLString(Generator, xml_string) class Text(AtomBase): """A foundation class from which atom:title, summary, etc. extend. This class should never be instantiated. """ _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, text_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Text Args: text_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = text_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Title(Text): """The atom:title element""" _tag = 'title' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, title_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Title Args: title_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = title_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def TitleFromString(xml_string): return CreateClassFromXMLString(Title, xml_string) class Subtitle(Text): """The atom:subtitle element""" _tag = 'subtitle' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, subtitle_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Subtitle Args: subtitle_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = subtitle_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SubtitleFromString(xml_string): return CreateClassFromXMLString(Subtitle, xml_string) class Rights(Text): """The atom:rights element""" _tag = 'rights' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, rights_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Rights Args: rights_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = rights_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def RightsFromString(xml_string): return CreateClassFromXMLString(Rights, xml_string) class Summary(Text): """The atom:summary element""" _tag = 'summary' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, summary_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Summary Args: summary_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = summary_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SummaryFromString(xml_string): return CreateClassFromXMLString(Summary, xml_string) class Content(Text): """The atom:content element""" _tag = 'content' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() _attributes['src'] = 'src' def __init__(self, content_type=None, src=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Content Args: content_type: string src: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = content_type self.src = src self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ContentFromString(xml_string): return CreateClassFromXMLString(Content, xml_string) class Category(AtomBase): """The atom:category element""" _tag = 'category' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['term'] = 'term' _attributes['scheme'] = 'scheme' _attributes['label'] = 'label' def __init__(self, term=None, scheme=None, label=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Category Args: term: str scheme: str label: str text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.term = term self.scheme = scheme self.label = label self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def CategoryFromString(xml_string): return CreateClassFromXMLString(Category, xml_string) class Id(AtomBase): """The atom:id element.""" _tag = 'id' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Id Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def IdFromString(xml_string): return CreateClassFromXMLString(Id, xml_string) class Icon(AtomBase): """The atom:icon element.""" _tag = 'icon' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Icon Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def IconFromString(xml_string): return CreateClassFromXMLString(Icon, xml_string) class Logo(AtomBase): """The atom:logo element.""" _tag = 'logo' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Logo Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LogoFromString(xml_string): return CreateClassFromXMLString(Logo, xml_string) class Draft(AtomBase): """The app:draft element which indicates if this entry should be public.""" _tag = 'draft' _namespace = APP_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for app:draft Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def DraftFromString(xml_string): return CreateClassFromXMLString(Draft, xml_string) class Control(AtomBase): """The app:control element indicating restrictions on publication. The APP control element may contain a draft element indicating whether or not this entry should be publicly available. """ _tag = 'control' _namespace = APP_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft) def __init__(self, draft=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for app:control""" self.draft = draft self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ControlFromString(xml_string): return CreateClassFromXMLString(Control, xml_string) class Date(AtomBase): """A parent class for atom:updated, published, etc.""" #TODO Add text to and from time conversion methods to allow users to set # the contents of a Date to a python DateTime object. _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Updated(Date): """The atom:updated element.""" _tag = 'updated' _namespace = ATOM_NAMESPACE _children = Date._children.copy() _attributes = Date._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Updated Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UpdatedFromString(xml_string): return CreateClassFromXMLString(Updated, xml_string) class Published(Date): """The atom:published element.""" _tag = 'published' _namespace = ATOM_NAMESPACE _children = Date._children.copy() _attributes = Date._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Published Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PublishedFromString(xml_string): return CreateClassFromXMLString(Published, xml_string) class LinkFinder(object): """An "interface" providing methods to find link elements Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in Atom entries and feeds. """ def GetSelfLink(self): """Find the first link with rel set to 'self' Returns: An atom.Link or none if none of the links had rel equal to 'self' """ for a_link in self.link: if a_link.rel == 'self': return a_link return None def GetEditLink(self): for a_link in self.link: if a_link.rel == 'edit': return a_link return None def GetEditMediaLink(self): for a_link in self.link: if a_link.rel == 'edit-media': return a_link return None def GetNextLink(self): for a_link in self.link: if a_link.rel == 'next': return a_link return None def GetLicenseLink(self): for a_link in self.link: if a_link.rel == 'license': return a_link return None def GetAlternateLink(self): for a_link in self.link: if a_link.rel == 'alternate': return a_link return None class FeedEntryParent(AtomBase, LinkFinder): """A super class for atom:feed and entry, contains shared attributes""" _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author]) _children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category]) _children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor]) _children['{%s}id' % ATOM_NAMESPACE] = ('id', Id) _children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link]) _children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights) _children['{%s}title' % ATOM_NAMESPACE] = ('title', Title) _children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated) def __init__(self, author=None, category=None, contributor=None, atom_id=None, link=None, rights=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.rights = rights self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Source(FeedEntryParent): """The atom:source element""" _tag = 'source' _namespace = ATOM_NAMESPACE _children = FeedEntryParent._children.copy() _attributes = FeedEntryParent._attributes.copy() _children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator) _children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon) _children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo) _children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SourceFromString(xml_string): return CreateClassFromXMLString(Source, xml_string) class Entry(FeedEntryParent): """The atom:entry element""" _tag = 'entry' _namespace = ATOM_NAMESPACE _children = FeedEntryParent._children.copy() _attributes = FeedEntryParent._attributes.copy() _children['{%s}content' % ATOM_NAMESPACE] = ('content', Content) _children['{%s}published' % ATOM_NAMESPACE] = ('published', Published) _children['{%s}source' % ATOM_NAMESPACE] = ('source', Source) _children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary) _children['{%s}control' % APP_NAMESPACE] = ('control', Control) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for atom:entry Args: author: list A list of Author instances which belong to this class. category: list A list of Category instances content: Content The entry's Content contributor: list A list on Contributor instances id: Id The entry's Id element link: list A list of Link instances published: Published The entry's Published element rights: Rights The entry's Rights element source: Source the entry's source element summary: Summary the entry's summary element title: Title the entry's title element updated: Updated the entry's updated element control: The entry's app:control element which can be used to mark an entry as a draft which should not be publicly viewable. text: String The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list A list of ExtensionElement instances which are children of this element. extension_attributes: dict A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.title = title self.updated = updated self.control = control self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} __init__ = v1_deprecated('Please use atom.data.Entry instead.')(__init__) def EntryFromString(xml_string): return CreateClassFromXMLString(Entry, xml_string) class Feed(Source): """The atom:feed element""" _tag = 'feed' _namespace = ATOM_NAMESPACE _children = Source._children.copy() _attributes = Source._attributes.copy() _children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.entry = entry or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} __init__ = v1_deprecated('Please use atom.data.Feed instead.')(__init__) def FeedFromString(xml_string): return CreateClassFromXMLString(Feed, xml_string) class ExtensionElement(object): """Represents extra XML elements contained in Atom classes.""" def __init__(self, tag, namespace=None, attributes=None, children=None, text=None): """Constructor for EtensionElement Args: namespace: string (optional) The XML namespace for this element. tag: string (optional) The tag (without the namespace qualifier) for this element. To reconstruct the full qualified name of the element, combine this tag with the namespace. attributes: dict (optinal) The attribute value string pairs for the XML attributes of this element. children: list (optional) A list of ExtensionElements which represent the XML child nodes of this element. """ self.namespace = namespace self.tag = tag self.attributes = attributes or {} self.children = children or [] self.text = text def ToString(self): element_tree = self._TransferToElementTree(ElementTree.Element('')) return ElementTree.tostring(element_tree, encoding="UTF-8") def _TransferToElementTree(self, element_tree): if self.tag is None: return None if self.namespace is not None: element_tree.tag = '{%s}%s' % (self.namespace, self.tag) else: element_tree.tag = self.tag for key, value in self.attributes.iteritems(): element_tree.attrib[key] = value for child in self.children: child._BecomeChildElement(element_tree) element_tree.text = self.text return element_tree def _BecomeChildElement(self, element_tree): """Converts this object into an etree element and adds it as a child node. Adds self to the ElementTree. This method is required to avoid verbose XML which constantly redefines the namespace. Args: element_tree: ElementTree._Element The element to which this object's XML will be added. """ new_element = ElementTree.Element('') element_tree.append(new_element) self._TransferToElementTree(new_element) def FindChildren(self, tag=None, namespace=None): """Searches child nodes for objects with the desired tag/namespace. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all children in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. Args: tag: str (optional) The desired tag namespace: str (optional) The desired namespace Returns: A list of elements whose tag and/or namespace match the parameters values """ results = [] if tag and namespace: for element in self.children: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.children: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.children: if element.namespace == namespace: results.append(element) else: for element in self.children: results.append(element) return results def ExtensionElementFromString(xml_string): element_tree = ElementTree.fromstring(xml_string) return _ExtensionElementFromElementTree(element_tree) def _ExtensionElementFromElementTree(element_tree): element_tag = element_tree.tag if '}' in element_tag: namespace = element_tag[1:element_tag.index('}')] tag = element_tag[element_tag.index('}')+1:] else: namespace = None tag = element_tag extension = ExtensionElement(namespace=namespace, tag=tag) for key, value in element_tree.attrib.iteritems(): extension.attributes[key] = value for child in element_tree: extension.children.append(_ExtensionElementFromElementTree(child)) extension.text = element_tree.text return extension def deprecated(warning=None): """Decorator to raise warning each time the function is called. Args: warning: The warning message to be displayed as a string (optinoal). """ warning = warning or '' # This closure is what is returned from the deprecated function. def mark_deprecated(f): # The deprecated_function wraps the actual call to f. def deprecated_function(*args, **kwargs): warnings.warn(warning, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) # Preserve the original name to avoid masking all decorated functions as # 'deprecated_function' try: deprecated_function.func_name = f.func_name except TypeError: # Setting the func_name is not allowed in Python2.3. pass return deprecated_function return mark_deprecated
Python
#!/usr/bin/env python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import inspect try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree try: from xml.dom.minidom import parseString as xmlString except ImportError: xmlString = None STRING_ENCODING = 'utf-8' class XmlElement(object): """Represents an element node in an XML document. The text member is a UTF-8 encoded str or unicode. """ _qname = None _other_elements = None _other_attributes = None # The rule set contains mappings for XML qnames to child members and the # appropriate member classes. _rule_set = None _members = None text = None def __init__(self, text=None, *args, **kwargs): if ('_members' not in self.__class__.__dict__ or self.__class__._members is None): self.__class__._members = tuple(self.__class__._list_xml_members()) for member_name, member_type in self.__class__._members: if member_name in kwargs: setattr(self, member_name, kwargs[member_name]) else: if isinstance(member_type, list): setattr(self, member_name, []) else: setattr(self, member_name, None) self._other_elements = [] self._other_attributes = {} if text is not None: self.text = text def _list_xml_members(cls): """Generator listing all members which are XML elements or attributes. The following members would be considered XML members: foo = 'abc' - indicates an XML attribute with the qname abc foo = SomeElement - indicates an XML child element foo = [AnElement] - indicates a repeating XML child element, each instance will be stored in a list in this member foo = ('att1', '{http://example.com/namespace}att2') - indicates an XML attribute which has different parsing rules in different versions of the protocol. Version 1 of the XML parsing rules will look for an attribute with the qname 'att1' but verion 2 of the parsing rules will look for a namespaced attribute with the local name of 'att2' and an XML namespace of 'http://example.com/namespace'. """ members = [] for pair in inspect.getmembers(cls): if not pair[0].startswith('_') and pair[0] != 'text': member_type = pair[1] if (isinstance(member_type, tuple) or isinstance(member_type, list) or isinstance(member_type, (str, unicode)) or (inspect.isclass(member_type) and issubclass(member_type, XmlElement))): members.append(pair) return members _list_xml_members = classmethod(_list_xml_members) def _get_rules(cls, version): """Initializes the _rule_set for the class which is used when parsing XML. This method is used internally for parsing and generating XML for an XmlElement. It is not recommended that you call this method directly. Returns: A tuple containing the XML parsing rules for the appropriate version. The tuple looks like: (qname, {sub_element_qname: (member_name, member_class, repeating), ..}, {attribute_qname: member_name}) To give a couple of concrete example, the atom.data.Control _get_rules with version of 2 will return: ('{http://www.w3.org/2007/app}control', {'{http://www.w3.org/2007/app}draft': ('draft', <class 'atom.data.Draft'>, False)}, {}) Calling _get_rules with version 1 on gdata.data.FeedLink will produce: ('{http://schemas.google.com/g/2005}feedLink', {'{http://www.w3.org/2005/Atom}feed': ('feed', <class 'gdata.data.GDFeed'>, False)}, {'href': 'href', 'readOnly': 'read_only', 'countHint': 'count_hint', 'rel': 'rel'}) """ # Initialize the _rule_set to make sure there is a slot available to store # the parsing rules for this version of the XML schema. # Look for rule set in the class __dict__ proxy so that only the # _rule_set for this class will be found. By using the dict proxy # we avoid finding rule_sets defined in superclasses. # The four lines below provide support for any number of versions, but it # runs a bit slower then hard coding slots for two versions, so I'm using # the below two lines. #if '_rule_set' not in cls.__dict__ or cls._rule_set is None: # cls._rule_set = [] #while len(cls.__dict__['_rule_set']) < version: # cls._rule_set.append(None) # If there is no rule set cache in the class, provide slots for two XML # versions. If and when there is a version 3, this list will need to be # expanded. if '_rule_set' not in cls.__dict__ or cls._rule_set is None: cls._rule_set = [None, None] # If a version higher than 2 is requested, fall back to version 2 because # 2 is currently the highest supported version. if version > 2: return cls._get_rules(2) # Check the dict proxy for the rule set to avoid finding any rule sets # which belong to the superclass. We only want rule sets for this class. if cls._rule_set[version-1] is None: # The rule set for each version consists of the qname for this element # ('{namespace}tag'), a dictionary (elements) for looking up the # corresponding class member when given a child element's qname, and a # dictionary (attributes) for looking up the corresponding class member # when given an XML attribute's qname. elements = {} attributes = {} if ('_members' not in cls.__dict__ or cls._members is None): cls._members = tuple(cls._list_xml_members()) for member_name, target in cls._members: if isinstance(target, list): # This member points to a repeating element. elements[_get_qname(target[0], version)] = (member_name, target[0], True) elif isinstance(target, tuple): # This member points to a versioned XML attribute. if version <= len(target): attributes[target[version-1]] = member_name else: attributes[target[-1]] = member_name elif isinstance(target, (str, unicode)): # This member points to an XML attribute. attributes[target] = member_name elif issubclass(target, XmlElement): # This member points to a single occurance element. elements[_get_qname(target, version)] = (member_name, target, False) version_rules = (_get_qname(cls, version), elements, attributes) cls._rule_set[version-1] = version_rules return version_rules else: return cls._rule_set[version-1] _get_rules = classmethod(_get_rules) def get_elements(self, tag=None, namespace=None, version=1): """Find all sub elements which match the tag and namespace. To find all elements in this object, call get_elements with the tag and namespace both set to None (the default). This method searches through the object's members and the elements stored in _other_elements which did not match any of the XML parsing rules for this class. Args: tag: str namespace: str version: int Specifies the version of the XML rules to be used when searching for matching elements. Returns: A list of the matching XmlElements. """ matches = [] ignored1, elements, ignored2 = self.__class__._get_rules(version) if elements: for qname, element_def in elements.iteritems(): member = getattr(self, element_def[0]) if member: if _qname_matches(tag, namespace, qname): if element_def[2]: # If this is a repeating element, copy all instances into the # result list. matches.extend(member) else: matches.append(member) for element in self._other_elements: if _qname_matches(tag, namespace, element._qname): matches.append(element) return matches GetElements = get_elements # FindExtensions and FindChildren are provided for backwards compatibility # to the atom.AtomBase class. # However, FindExtensions may return more results than the v1 atom.AtomBase # method does, because get_elements searches both the expected children # and the unexpected "other elements". The old AtomBase.FindExtensions # method searched only "other elements" AKA extension_elements. FindExtensions = get_elements FindChildren = get_elements def get_attributes(self, tag=None, namespace=None, version=1): """Find all attributes which match the tag and namespace. To find all attributes in this object, call get_attributes with the tag and namespace both set to None (the default). This method searches through the object's members and the attributes stored in _other_attributes which did not fit any of the XML parsing rules for this class. Args: tag: str namespace: str version: int Specifies the version of the XML rules to be used when searching for matching attributes. Returns: A list of XmlAttribute objects for the matching attributes. """ matches = [] ignored1, ignored2, attributes = self.__class__._get_rules(version) if attributes: for qname, attribute_def in attributes.iteritems(): if isinstance(attribute_def, (list, tuple)): attribute_def = attribute_def[0] member = getattr(self, attribute_def) # TODO: ensure this hasn't broken existing behavior. #member = getattr(self, attribute_def[0]) if member: if _qname_matches(tag, namespace, qname): matches.append(XmlAttribute(qname, member)) for qname, value in self._other_attributes.iteritems(): if _qname_matches(tag, namespace, qname): matches.append(XmlAttribute(qname, value)) return matches GetAttributes = get_attributes def _harvest_tree(self, tree, version=1): """Populates object members from the data in the tree Element.""" qname, elements, attributes = self.__class__._get_rules(version) for element in tree: if elements and element.tag in elements: definition = elements[element.tag] # If this is a repeating element, make sure the member is set to a # list. if definition[2]: if getattr(self, definition[0]) is None: setattr(self, definition[0], []) getattr(self, definition[0]).append(_xml_element_from_tree(element, definition[1], version)) else: setattr(self, definition[0], _xml_element_from_tree(element, definition[1], version)) else: self._other_elements.append(_xml_element_from_tree(element, XmlElement, version)) for attrib, value in tree.attrib.iteritems(): if attributes and attrib in attributes: setattr(self, attributes[attrib], value) else: self._other_attributes[attrib] = value if tree.text: self.text = tree.text def _to_tree(self, version=1, encoding=None): new_tree = ElementTree.Element(_get_qname(self, version)) self._attach_members(new_tree, version, encoding) return new_tree def _attach_members(self, tree, version=1, encoding=None): """Convert members to XML elements/attributes and add them to the tree. Args: tree: An ElementTree.Element which will be modified. The members of this object will be added as child elements or attributes according to the rules described in _expected_elements and _expected_attributes. The elements and attributes stored in other_attributes and other_elements are also added a children of this tree. version: int Ingnored in this method but used by VersionedElement. encoding: str (optional) """ qname, elements, attributes = self.__class__._get_rules(version) encoding = encoding or STRING_ENCODING # Add the expected elements and attributes to the tree. if elements: for tag, element_def in elements.iteritems(): member = getattr(self, element_def[0]) # If this is a repeating element and there are members in the list. if member and element_def[2]: for instance in member: instance._become_child(tree, version) elif member: member._become_child(tree, version) if attributes: for attribute_tag, member_name in attributes.iteritems(): value = getattr(self, member_name) if value: tree.attrib[attribute_tag] = value # Add the unexpected (other) elements and attributes to the tree. for element in self._other_elements: element._become_child(tree, version) for key, value in self._other_attributes.iteritems(): # I'm not sure if unicode can be used in the attribute name, so for now # we assume the encoding is correct for the attribute name. if not isinstance(value, unicode): value = value.decode(encoding) tree.attrib[key] = value if self.text: if isinstance(self.text, unicode): tree.text = self.text else: tree.text = self.text.decode(encoding) def to_string(self, version=1, encoding=None, pretty_print=None): """Converts this object to XML.""" tree_string = ElementTree.tostring(self._to_tree(version, encoding)) if pretty_print and xmlString is not None: return xmlString(tree_string).toprettyxml() return tree_string ToString = to_string def __str__(self): return self.to_string() def _become_child(self, tree, version=1): """Adds a child element to tree with the XML data in self.""" new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = _get_qname(self, version) self._attach_members(new_child, version) def __get_extension_elements(self): return self._other_elements def __set_extension_elements(self, elements): self._other_elements = elements extension_elements = property(__get_extension_elements, __set_extension_elements, """Provides backwards compatibility for v1 atom.AtomBase classes.""") def __get_extension_attributes(self): return self._other_attributes def __set_extension_attributes(self, attributes): self._other_attributes = attributes extension_attributes = property(__get_extension_attributes, __set_extension_attributes, """Provides backwards compatibility for v1 atom.AtomBase classes.""") def _get_tag(self, version=1): qname = _get_qname(self, version) if qname: return qname[qname.find('}')+1:] return None def _get_namespace(self, version=1): qname = _get_qname(self, version) if qname.startswith('{'): return qname[1:qname.find('}')] else: return None def _set_tag(self, tag): if isinstance(self._qname, tuple): self._qname = self._qname.copy() if self._qname[0].startswith('{'): self._qname[0] = '{%s}%s' % (self._get_namespace(1), tag) else: self._qname[0] = tag else: if self._qname is not None and self._qname.startswith('{'): self._qname = '{%s}%s' % (self._get_namespace(), tag) else: self._qname = tag def _set_namespace(self, namespace): tag = self._get_tag(1) if tag is None: tag = '' if isinstance(self._qname, tuple): self._qname = self._qname.copy() if namespace: self._qname[0] = '{%s}%s' % (namespace, tag) else: self._qname[0] = tag else: if namespace: self._qname = '{%s}%s' % (namespace, tag) else: self._qname = tag tag = property(_get_tag, _set_tag, """Provides backwards compatibility for v1 atom.AtomBase classes.""") namespace = property(_get_namespace, _set_namespace, """Provides backwards compatibility for v1 atom.AtomBase classes.""") # Provided for backwards compatibility to atom.ExtensionElement children = extension_elements attributes = extension_attributes def _get_qname(element, version): if isinstance(element._qname, tuple): if version <= len(element._qname): return element._qname[version-1] else: return element._qname[-1] else: return element._qname def _qname_matches(tag, namespace, qname): """Logic determines if a QName matches the desired local tag and namespace. This is used in XmlElement.get_elements and XmlElement.get_attributes to find matches in the element's members (among all expected-and-unexpected elements-and-attributes). Args: expected_tag: string expected_namespace: string qname: string in the form '{xml_namespace}localtag' or 'tag' if there is no namespace. Returns: boolean True if the member's tag and namespace fit the expected tag and namespace. """ # If there is no expected namespace or tag, then everything will match. if qname is None: member_tag = None member_namespace = None else: if qname.startswith('{'): member_namespace = qname[1:qname.index('}')] member_tag = qname[qname.index('}') + 1:] else: member_namespace = None member_tag = qname return ((tag is None and namespace is None) # If there is a tag, but no namespace, see if the local tag matches. or (namespace is None and member_tag == tag) # There was no tag, but there was a namespace so see if the namespaces # match. or (tag is None and member_namespace == namespace) # There was no tag, and the desired elements have no namespace, so check # to see that the member's namespace is None. or (tag is None and namespace == '' and member_namespace is None) # The tag and the namespace both match. or (tag == member_tag and namespace == member_namespace) # The tag matches, and the expected namespace is the empty namespace, # check to make sure the member's namespace is None. or (tag == member_tag and namespace == '' and member_namespace is None)) def parse(xml_string, target_class=None, version=1, encoding=None): """Parses the XML string according to the rules for the target_class. Args: xml_string: str or unicode target_class: XmlElement or a subclass. If None is specified, the XmlElement class is used. version: int (optional) The version of the schema which should be used when converting the XML into an object. The default is 1. encoding: str (optional) The character encoding of the bytes in the xml_string. Default is 'UTF-8'. """ if target_class is None: target_class = XmlElement if isinstance(xml_string, unicode): if encoding is None: xml_string = xml_string.encode(STRING_ENCODING) else: xml_string = xml_string.encode(encoding) tree = ElementTree.fromstring(xml_string) return _xml_element_from_tree(tree, target_class, version) Parse = parse xml_element_from_string = parse XmlElementFromString = xml_element_from_string def _xml_element_from_tree(tree, target_class, version=1): if target_class._qname is None: instance = target_class() instance._qname = tree.tag instance._harvest_tree(tree, version) return instance # TODO handle the namespace-only case # Namespace only will be used with Google Spreadsheets rows and # Google Base item attributes. elif tree.tag == _get_qname(target_class, version): instance = target_class() instance._harvest_tree(tree, version) return instance return None class XmlAttribute(object): def __init__(self, qname, value): self._qname = qname self.value = value
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url class Error(Exception): pass class NoRecordingFound(Error): pass class MockRequest(object): """Holds parameters of an HTTP request for matching against future requests. """ def __init__(self, operation, url, data=None, headers=None): self.operation = operation if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) self.url = url self.data = data self.headers = headers class MockResponse(atom.http_interface.HttpResponse): """Simulates an httplib.HTTPResponse object.""" def __init__(self, body=None, status=None, reason=None, headers=None): if body and hasattr(body, 'read'): self.body = body.read() else: self.body = body if status is not None: self.status = int(status) else: self.status = None self.reason = reason self._headers = headers or {} def read(self): return self.body class MockHttpClient(atom.http_interface.GenericHttpClient): def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers or {} def add_response(self, response, operation, url, data=None, headers=None): """Adds a request-response pair to the recordings list. After the recording is added, future matching requests will receive the response. Args: response: MockResponse operation: str url: str data: str, Currently the data is ignored when looking for matching requests. headers: dict of strings: Currently the headers are ignored when looking for matching requests. """ request = MockRequest(operation, url, data=data, headers=headers) self.recordings.append((request, response)) def request(self, operation, url, data=None, headers=None): """Returns a matching MockResponse from the recordings. If the real_client is set, the request will be passed along and the server's response will be added to the recordings and also returned. If there is no match, a NoRecordingFound error will be raised. """ if self.real_client is None: if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for recording in self.recordings: if recording[0].operation == operation and recording[0].url == url: return recording[1] raise NoRecordingFound('No recodings found for %s %s' % ( operation, url)) else: # There is a real HTTP client, so make the request, and record the # response. response = self.real_client.request(operation, url, data=data, headers=headers) # TODO: copy the headers stored_response = MockResponse(body=response, status=response.status, reason=response.reason) self.add_response(stored_response, operation, url, data=data, headers=headers) return stored_response
Python
#!/usr/bin/python import sys import unittest import module_test_runner import getopt import getpass # Modules whose tests we will run. import atom_tests.service_test import gdata_tests.service_test import gdata_tests.apps.service_test import gdata_tests.base.service_test import gdata_tests.books.service_test import gdata_tests.calendar.service_test import gdata_tests.docs.service_test import gdata_tests.health.service_test import gdata_tests.spreadsheet.service_test import gdata_tests.spreadsheet.text_db_test import gdata_tests.photos.service_test import gdata_tests.contacts.service_test import gdata_tests.blogger.service_test import gdata_tests.youtube.service_test import gdata_tests.health.service_test import gdata_tests.contacts.profiles.service_test def RunAllTests(username, password, spreadsheet_key, worksheet_key, apps_username, apps_password, apps_domain): test_runner = module_test_runner.ModuleTestRunner() test_runner.modules = [atom_tests.service_test, gdata_tests.service_test, gdata_tests.apps.service_test, gdata_tests.base.service_test, gdata_tests.books.service_test, gdata_tests.calendar.service_test, gdata_tests.docs.service_test, gdata_tests.health.service_test, gdata_tests.spreadsheet.service_test, gdata_tests.spreadsheet.text_db_test, gdata_tests.contacts.service_test, gdata_tests.youtube.service_test, gdata_tests.photos.service_test, gdata_tests.contacts.profiles.service_test,] test_runner.settings = {'username':username, 'password':password, 'test_image_location':'testimage.jpg', 'ss_key':spreadsheet_key, 'ws_key':worksheet_key, 'apps_username':apps_username, 'apps_password':apps_password, 'apps_domain':apps_domain} test_runner.RunAllTests() def GetValuesForTestSettingsAndRunAllTests(): username = '' password = '' spreadsheet_key = '' worksheet_key = '' apps_domain = '' apps_username = '' apps_password = '' print ('NOTE: Please run these tests only with a test account. ' 'The tests may delete or update your data.') try: opts, args = getopt.getopt(sys.argv[1:], '', ['username=', 'password=', 'ss_key=', 'ws_key=', 'apps_username=', 'apps_password=', 'apps_domain=']) for o, a in opts: if o == '--username': username = a elif o == '--password': password = a elif o == '--ss_key': spreadsheet_key = a elif o == '--ws_key': worksheet_key = a elif o == '--apps_username': apps_username = a elif o == '--apps_password': apps_password = a elif o == '--apps_domain': apps_domain = a except getopt.GetoptError: pass if username == '' and password == '': print ('Missing --user and --pw command line arguments, ' 'prompting for credentials.') if username == '': username = raw_input('Please enter your username: ') if password == '': password = getpass.getpass() if spreadsheet_key == '': spreadsheet_key = raw_input( 'Please enter the key for the test spreadsheet: ') if worksheet_key == '': worksheet_key = raw_input( 'Please enter the id for the worksheet to be edited: ') if apps_username == '': apps_username = raw_input('Please enter your Google Apps admin username: ') if apps_password == '': apps_password = getpass.getpass() if apps_domain == '': apps_domain = raw_input('Please enter your Google Apps domain: ') RunAllTests(username, password, spreadsheet_key, worksheet_key, apps_username, apps_password, apps_domain) if __name__ == '__main__': GetValuesForTestSettingsAndRunAllTests()
Python
#!/usr/bin/python import sys import unittest import module_test_runner import getopt import getpass # Modules whose tests we will run. import gdata_test import atom_test import atom_tests.http_interface_test import atom_tests.mock_http_test import atom_tests.token_store_test import atom_tests.url_test import atom_tests.core_test import gdata_tests.apps.emailsettings.data_test import gdata_tests.apps_test import gdata_tests.auth_test import gdata_tests.base_test import gdata_tests.books_test import gdata_tests.blogger_test import gdata_tests.calendar_test import gdata_tests.calendar_resource.data_test import gdata_tests.client_test import gdata_tests.codesearch_test import gdata_tests.contacts_test import gdata_tests.docs_test import gdata_tests.health_test import gdata_tests.photos_test import gdata_tests.spreadsheet_test import gdata_tests.youtube_test import gdata_tests.webmastertools_test import gdata_tests.oauth.data_test def RunAllTests(): test_runner = module_test_runner.ModuleTestRunner() test_runner.modules = [gdata_test, atom_test, atom_tests.url_test, atom_tests.http_interface_test, atom_tests.mock_http_test, atom_tests.core_test, atom_tests.token_store_test, gdata_tests.client_test, gdata_tests.apps_test, gdata_tests.apps.emailsettings.data_test, gdata_tests.auth_test, gdata_tests.base_test, gdata_tests.books_test, gdata_tests.calendar_test, gdata_tests.docs_test, gdata_tests.health_test, gdata_tests.spreadsheet_test, gdata_tests.photos_test, gdata_tests.codesearch_test, gdata_tests.contacts_test, gdata_tests.youtube_test, gdata_tests.blogger_test, gdata_tests.webmastertools_test, gdata_tests.calendar_resource.data_test, gdata_tests.oauth.data_test] test_runner.RunAllTests() if __name__ == '__main__': RunAllTests()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest from gdata import test_data import gdata.blogger.data import atom.core import gdata.test_config as conf class BlogEntryTest(unittest.TestCase): def testBlogEntryFromString(self): entry = atom.core.parse(test_data.BLOG_ENTRY, gdata.blogger.data.Blog) self.assertEquals(entry.GetBlogName(), 'blogName') self.assertEquals(entry.GetBlogId(), 'blogID') self.assertEquals(entry.title.text, 'Lizzy\'s Diary') def testBlogPostFeedFromString(self): feed = atom.core.parse(test_data.BLOG_POSTS_FEED, gdata.blogger.data.BlogPostFeed) self.assertEquals(len(feed.entry), 1) self.assert_(isinstance(feed, gdata.blogger.data.BlogPostFeed)) self.assert_(isinstance(feed.entry[0], gdata.blogger.data.BlogPost)) self.assertEquals(feed.entry[0].GetPostId(), 'postID') self.assertEquals(feed.entry[0].GetBlogId(), 'blogID') self.assertEquals(feed.entry[0].title.text, 'Quite disagreeable') def testCommentFeedFromString(self): feed = atom.core.parse(test_data.BLOG_COMMENTS_FEED, gdata.blogger.data.CommentFeed) self.assertEquals(len(feed.entry), 1) self.assert_(isinstance(feed, gdata.blogger.data.CommentFeed)) self.assert_(isinstance(feed.entry[0], gdata.blogger.data.Comment)) self.assertEquals(feed.entry[0].get_blog_id(), 'blogID') self.assertEquals(feed.entry[0].get_blog_name(), 'a-blogName') self.assertEquals(feed.entry[0].get_comment_id(), 'commentID') self.assertEquals(feed.entry[0].title.text, 'This is my first comment') self.assertEquals(feed.entry[0].in_reply_to.source, 'http://blogName.blogspot.com/feeds/posts/default/postID') self.assertEquals(feed.entry[0].in_reply_to.ref, 'tag:blogger.com,1999:blog-blogID.post-postID') self.assertEquals(feed.entry[0].in_reply_to.href, 'http://blogName.blogspot.com/2007/04/first-post.html') self.assertEquals(feed.entry[0].in_reply_to.type, 'text/html') def testIdParsing(self): entry = gdata.blogger.data.Blog() entry.id = atom.data.Id( text='tag:blogger.com,1999:user-146606542.blog-4023408167658848') self.assertEquals(entry.GetBlogId(), '4023408167658848') entry.id = atom.data.Id(text='tag:blogger.com,1999:blog-4023408167658848') self.assertEquals(entry.GetBlogId(), '4023408167658848') class InReplyToTest(unittest.TestCase): def testToAndFromString(self): in_reply_to = gdata.blogger.data.InReplyTo( href='http://example.com/href', ref='http://example.com/ref', source='http://example.com/my_post', type='text/html') xml_string = str(in_reply_to) parsed = atom.core.parse(xml_string, gdata.blogger.data.InReplyTo) self.assertEquals(parsed.source, in_reply_to.source) self.assertEquals(parsed.href, in_reply_to.href) self.assertEquals(parsed.ref, in_reply_to.ref) self.assertEquals(parsed.type, in_reply_to.type) class CommentTest(unittest.TestCase): def testToAndFromString(self): comment = gdata.blogger.data.Comment( content=atom.data.Content(text='Nifty!'), in_reply_to=gdata.blogger.data.InReplyTo( source='http://example.com/my_post')) parsed = atom.core.parse(str(comment), gdata.blogger.data.Comment) self.assertEquals(parsed.in_reply_to.source, comment.in_reply_to.source) self.assertEquals(parsed.content.text, comment.content.text) def suite(): return conf.build_suite([BlogEntryTest, InReplyToTest, CommentTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests to exercise server interactions for blogger.""" __author__ = 'api.jscudder (Jeffrey Scudder)' import unittest import getpass import atom from gdata import test_data import gdata.blogger import gdata.blogger.service username = '' password = '' test_blog_id = '' class BloggerCrudTests(unittest.TestCase): def setUp(self): self.client = gdata.blogger.service.BloggerService(email=username, password=password, source='GoogleInc-PythonBloggerUnitTests-1') # TODO: if the test_blog_id is not set, get the list of the user's blogs # and prompt for which blog to add the test posts to. self.client.ProgrammaticLogin() def testPostDraftUpdateAndDelete(self): new_entry = gdata.blogger.BlogPostEntry(title=atom.Title( text='Unit Test Post')) new_entry.content = atom.Content('text', None, 'Hello World') # Make this post a draft so it will not appear publicly on the blog. new_entry.control = atom.Control(draft=atom.Draft(text='yes')) new_entry.AddLabel('test') posted = self.client.AddPost(new_entry, blog_id=test_blog_id) self.assertEquals(posted.title.text, new_entry.title.text) # Should be one category in the posted entry for the 'test' label. self.assertEquals(len(posted.category), 1) self.assert_(isinstance(posted, gdata.blogger.BlogPostEntry)) # Change the title and add more labels. posted.title.text = 'Updated' posted.AddLabel('second') updated = self.client.UpdatePost(entry=posted) self.assertEquals(updated.title.text, 'Updated') self.assertEquals(len(updated.category), 2) # Cleanup and delete the draft blog post. self.client.DeletePost(entry=posted) def testAddComment(self): # Create a test post to add comments to. new_entry = gdata.blogger.BlogPostEntry(title=atom.Title( text='Comments Test Post')) new_entry.content = atom.Content('text', None, 'Hello Comments') target_post = self.client.AddPost(new_entry, blog_id=test_blog_id) blog_id = target_post.GetBlogId() post_id = target_post.GetPostId() new_comment = gdata.blogger.CommentEntry() new_comment.content = atom.Content(text='Test comment') posted = self.client.AddComment(new_comment, blog_id=blog_id, post_id=post_id) self.assertEquals(posted.content.text, new_comment.content.text) # Cleanup and delete the comment test blog post. self.client.DeletePost(entry=target_post) class BloggerQueryTests(unittest.TestCase): def testConstructBlogQuery(self): pass def testConstructBlogQuery(self): pass def testConstructBlogQuery(self): pass if __name__ == '__main__': print ('NOTE: Please run these tests only with a test account. ' + 'The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() test_blog_id = raw_input('Please enter the blog id for the test blog: ') unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.blogger.client import gdata.blogger.data import gdata.gauth import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data import gdata.test_config as conf conf.options.register_option(conf.BLOG_ID_OPTION) class BloggerClientTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.blogger.client.BloggerClient() conf.configure_client(self.client, 'BloggerTest', 'blogger') def tearDown(self): conf.close_client(self.client) def test_create_update_delete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') # Add a blog post. created = self.client.add_post(conf.options.get_value('blogid'), 'test post from BloggerClientTest', 'Hey look, another test!', labels=['test', 'python']) self.assertEqual(created.title.text, 'test post from BloggerClientTest') self.assertEqual(created.content.text, 'Hey look, another test!') self.assertEqual(len(created.category), 2) self.assert_(created.control is None) # Change the title of the blog post we just added. created.title.text = 'Edited' updated = self.client.update(created) self.assertEqual(updated.title.text, 'Edited') self.assert_(isinstance(updated, gdata.blogger.data.BlogPost)) self.assertEqual(updated.content.text, created.content.text) # Delete the test entry from the blog. self.client.delete(updated) def test_create_draft_post(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_create_draft_post') # Add a draft blog post. created = self.client.add_post(conf.options.get_value('blogid'), 'draft test post from BloggerClientTest', 'This should only be a draft.', labels=['test2', 'python'], draft=True) self.assertEqual(created.title.text, 'draft test post from BloggerClientTest') self.assertEqual(created.content.text, 'This should only be a draft.') self.assertEqual(len(created.category), 2) self.assert_(created.control is not None) self.assert_(created.control.draft is not None) self.assertEqual(created.control.draft.text, 'yes') # Publish the blog post. created.control.draft.text = 'no' updated = self.client.update(created) if updated.control is not None and updated.control.draft is not None: self.assertNotEqual(updated.control.draft.text, 'yes') # Delete the test entry from the blog using the URL instead of the entry. self.client.delete(updated.find_edit_link()) def test_create_draft_page(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_create_draft_page') # List all pages on the blog. pages_before = self.client.get_pages(conf.options.get_value('blogid')) # Add a draft page to blog. created = self.client.add_page(conf.options.get_value('blogid'), 'draft page from BloggerClientTest', 'draft content', draft=True) self.assertEqual(created.title.text, 'draft page from BloggerClientTest') self.assertEqual(created.content.text, 'draft content') self.assert_(created.control is not None) self.assert_(created.control.draft is not None) self.assertEqual(created.control.draft.text, 'yes') self.assertEqual(str(int(created.get_page_id())), created.get_page_id()) # List all pages after adding one. pages_after = self.client.get_pages(conf.options.get_value('blogid')) self.assertEqual(len(pages_before.entry) + 1, len(pages_after.entry)) # Publish page. created.control.draft.text = 'no' updated = self.client.update(created) if updated.control is not None and updated.control.draft is not None: self.assertNotEqual(updated.control.draft.text, 'yes') # Delete test page. self.client.delete(updated.find_edit_link()) pages_after = self.client.get_pages(conf.options.get_value('blogid')) self.assertEqual(len(pages_before.entry), len(pages_after.entry)) def test_retrieve_post_with_categories(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_retrieve_post_with_categories') query = gdata.blogger.client.Query(categories=["news"], strict=True) posts = self.client.get_posts(conf.options.get_value('blogid'), query=query) def suite(): return conf.build_suite([BloggerClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for Groups service.""" __author__ = 'google-apps-apis@googlegroups.com' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.apps import gdata.apps.service import gdata.apps.groups.service import getpass import time domain = '' admin_email = '' admin_password = '' username = '' class GroupsTest(unittest.TestCase): """Test for the GroupsService.""" def setUp(self): self.postfix = time.strftime("%Y%m%d%H%M%S") self.apps_client = gdata.apps.service.AppsService( email=admin_email, domain=domain, password=admin_password, source='GroupsClient "Unit" Tests') self.apps_client.ProgrammaticLogin() self.groups_client = gdata.apps.groups.service.GroupsService( email=admin_email, domain=domain, password=admin_password, source='GroupsClient "Unit" Tests') self.groups_client.ProgrammaticLogin() self.created_users = [] self.created_groups = [] self.createUsers(); def createUsers(self): user_name = 'yujimatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Yuji' password = '123$$abc' suspended = 'false' try: self.user_yuji = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) print 'User ' + user_name + ' created' except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(self.user_yuji) user_name = 'taromatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Taro' password = '123$$abc' suspended = 'false' try: self.user_taro = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) print 'User ' + user_name + ' created' except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(self.user_taro) def tearDown(self): print '\n' for user in self.created_users: try: self.apps_client.DeleteUser(user.login.user_name) print 'User ' + user.login.user_name + ' deleted' except Exception, e: print e for group in self.created_groups: try: self.groups_client.DeleteGroup(group) print 'Group ' + group + ' deleted' except Exception, e: print e def test001GroupsMethods(self): # tests CreateGroup method group01_id = 'group01-' + self.postfix group02_id = 'group02-' + self.postfix try: created_group01 = self.groups_client.CreateGroup(group01_id, 'US Sales 1', 'Testing', gdata.apps.groups.service.PERMISSION_OWNER) created_group02 = self.groups_client.CreateGroup(group02_id, 'US Sales 2', 'Testing', gdata.apps.groups.service.PERMISSION_OWNER) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(created_group01['groupId'], group01_id) self.assertEquals(created_group02['groupId'], group02_id) self.created_groups.append(group01_id) self.created_groups.append(group02_id) # tests UpdateGroup method try: updated_group = self.groups_client.UpdateGroup(group01_id, 'Updated!', 'Testing', gdata.apps.groups.service.PERMISSION_OWNER) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(updated_group['groupName'], 'Updated!') # tests RetrieveGroup method try: retrieved_group = self.groups_client.RetrieveGroup(group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(retrieved_group['groupId'], group01_id + '@' + domain) # tests RetrieveAllGroups method try: retrieved_groups = self.groups_client.RetrieveAllGroups() except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_groups), len(self.apps_client.RetrieveAllEmailLists().entry)) # tests AddMemberToGroup try: added_member = self.groups_client.AddMemberToGroup( self.user_yuji.login.user_name, group01_id) self.groups_client.AddMemberToGroup( self.user_taro.login.user_name, group02_id) self.groups_client.AddMemberToGroup( group01_id, group02_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(added_member['memberId'], self.user_yuji.login.user_name) # tests RetrieveGroups method try: retrieved_direct_groups = self.groups_client.RetrieveGroups( self.user_yuji.login.user_name, True) retrieved_groups = self.groups_client.RetrieveGroups( self.user_yuji.login.user_name, False) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_direct_groups), 1) # TODO: Enable this test after a directOnly bug is fixed #self.assertEquals(len(retrieved_groups), 2) # tests IsMember method try: result = self.groups_client.IsMember( self.user_yuji.login.user_name, group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(result, True) # tests RetrieveMember method try: retrieved_member = self.groups_client.RetrieveMember( self.user_yuji.login.user_name, group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(retrieved_member['memberId'], self.user_yuji.login.user_name + '@' + domain) # tests RetrieveAllMembers method try: retrieved_members = self.groups_client.RetrieveAllMembers(group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_members), 1) # tests RemoveMemberFromGroup method try: self.groups_client.RemoveMemberFromGroup(self.user_yuji.login.user_name, group01_id) retrieved_members = self.groups_client.RetrieveAllMembers(group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_members), 0) # tests AddOwnerToGroup try: added_owner = self.groups_client.AddOwnerToGroup( self.user_yuji.login.user_name, group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(added_owner['email'], self.user_yuji.login.user_name) # tests IsOwner method try: result = self.groups_client.IsOwner( self.user_yuji.login.user_name, group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(result, True) # tests RetrieveOwner method try: retrieved_owner = self.groups_client.RetrieveOwner( self.user_yuji.login.user_name, group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(retrieved_owner['email'], self.user_yuji.login.user_name + '@' + domain) # tests RetrieveAllOwners method try: retrieved_owners = self.groups_client.RetrieveAllOwners(group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_owners), 1) # tests RemoveOwnerFromGroup method try: self.groups_client.RemoveOwnerFromGroup(self.user_yuji.login.user_name, group01_id) retrieved_owners = self.groups_client.RetrieveAllOwners(group01_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_owners), 0) if __name__ == '__main__': print("""Google Apps Groups Service Tests NOTE: Please run these tests only with a test user account. """) domain = raw_input('Google Apps domain: ') admin_email = '%s@%s' % (raw_input('Administrator username: '), domain) admin_password = getpass.getpass('Administrator password: ') unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for Email Migration service.""" __author__ = 'google-apps-apis@googlegroups.com' import getpass import gdata.apps.migration.service import unittest domain = '' admin_email = '' admin_password = '' username = '' MESS="""From: joe@blow.com To: jane@doe.com Date: Mon, 29 Sep 2008 20:00:34 -0500 (CDT) Subject: %s %s""" class MigrationTest(unittest.TestCase): """Test for the MigrationService.""" def setUp(self): self.ms = gdata.apps.migration.service.MigrationService( email=admin_email, password=admin_password, domain=domain) self.ms.ProgrammaticLogin() def testImportMail(self): self.ms.ImportMail(user_name=username, mail_message=MESS%('Test subject', 'Test body'), mail_item_properties=['IS_STARRED'], mail_labels=['Test']) def testBatch(self): for i in xrange(1,10): self.ms.AddBatchEntry(mail_message=MESS%('Test batch %d'%i, 'Test batch'), mail_item_properties=['IS_INBOX'], mail_labels=['Test', 'Batch']) self.ms.SubmitBatch(user_name=username) if __name__ == '__main__': print("""Google Apps Email Migration Service Tests NOTE: Please run these tests only with a test user account. """) domain = raw_input('Google Apps domain: ') admin_email = '%s@%s' % (raw_input('Administrator username: '), domain) admin_password = getpass.getpass('Administrator password: ') username = raw_input('Test username: ') unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'tmatsuo@sios.com (Takashi Matsuo)' import unittest import time, os try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import re import pickle import atom import atom.http import atom.service from atom import mock_http import gdata.apps import gdata.apps.service import getpass apps_domain = 'test.shehas.net' apps_username = '' apps_password = '' def conceal_secrets(recordings): ret = [] for rec in recordings: req, res = rec if req.data: req.data = re.sub(r'Passwd=[^&]+', 'Passwd=hogehoge', req.data) if res.body: res.body = re.sub(r'SID=[^\n]+', 'SID=hogehoge', res.body) res.body = re.sub(r'LSID=[^\n]+', 'LSID=hogehoge', res.body) res.body = re.sub(r'Auth=[^\n]+', 'Auth=hogehoge', res.body) if req.headers.has_key('Authorization'): req.headers['Authorization'] = 'hogehoge' ret.append((req, res)) return ret class AppsServiceBaseTest(object): def setUp(self): self.datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "%s.pickle" % self.name) if os.path.isfile(self.datafile): f = open(self.datafile, "rb") data = pickle.load(f) f.close() http_client = mock_http.MockHttpClient(recordings=data) else: real_client = atom.http.ProxiedHttpClient() http_client = mock_http.MockHttpClient(real_client=real_client) email = apps_username + '@' + apps_domain self.apps_client = gdata.apps.service.AppsService( email=email, domain=apps_domain, password=apps_password, source='AppsClient "Unit" Tests') self.apps_client.http_client = http_client self.apps_client.ProgrammaticLogin() def tearDown(self): if self.apps_client.http_client.real_client: # create pickle file f = open(self.datafile, "wb") data = conceal_secrets(self.apps_client.http_client.recordings) pickle.dump(data, f) f.close() class AppsServiceTestForGetGeneratorForAllRecipients(AppsServiceBaseTest, unittest.TestCase): name = "AppsServiceTestForGetGeneratorForAllRecipients" def testGetGeneratorForAllRecipients(self): """Tests GetGeneratorForAllRecipientss method""" generator = self.apps_client.GetGeneratorForAllRecipients( "b101-20091013151051") i = 0 for recipient_feed in generator: for a_recipient in recipient_feed.entry: i = i + 1 self.assert_(i == 102) class AppsServiceTestForGetGeneratorForAllEmailLists(AppsServiceBaseTest, unittest.TestCase): name = "AppsServiceTestForGetGeneratorForAllEmailLists" def testGetGeneratorForAllEmailLists(self): """Tests GetGeneratorForAllEmailLists method""" generator = self.apps_client.GetGeneratorForAllEmailLists() i = 0 for emaillist_feed in generator: for a_emaillist in emaillist_feed.entry: i = i + 1 self.assert_(i == 105) class AppsServiceTestForGetGeneratorForAllNicknames(AppsServiceBaseTest, unittest.TestCase): name = "AppsServiceTestForGetGeneratorForAllNicknames" def testGetGeneratorForAllNicknames(self): """Tests GetGeneratorForAllNicknames method""" generator = self.apps_client.GetGeneratorForAllNicknames() i = 0 for nickname_feed in generator: for a_nickname in nickname_feed.entry: i = i + 1 self.assert_(i == 102) class AppsServiceTestForGetGeneratorForAllUsers(AppsServiceBaseTest, unittest.TestCase): name = "AppsServiceTestForGetGeneratorForAllUsers" def testGetGeneratorForAllUsers(self): """Tests GetGeneratorForAllUsers method""" generator = self.apps_client.GetGeneratorForAllUsers() i = 0 for user_feed in generator: for a_user in user_feed.entry: i = i + 1 self.assert_(i == 102) if __name__ == '__main__': print ('The tests may delete or update your data.') apps_username = raw_input('Please enter your username: ') apps_password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Claudio Cherubino <ccherubino@google.com>' import unittest import gdata.apps.emailsettings.data import gdata.test_config as conf class EmailSettingsLabelTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsLabel() def testName(self): self.entry.name = 'test label' self.assertEquals(self.entry.name, 'test label') class EmailSettingsFilterTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsFilter() def testFrom(self): self.entry.from_address = 'abc@example.com' self.assertEquals(self.entry.from_address, 'abc@example.com') def testTo(self): self.entry.to_address = 'to@example.com' self.assertEquals(self.entry.to_address, 'to@example.com') def testFrom(self): self.entry.from_address = 'abc@example.com' self.assertEquals(self.entry.from_address, 'abc@example.com') def testSubject(self): self.entry.subject = 'Read me' self.assertEquals(self.entry.subject, 'Read me') def testHasTheWord(self): self.entry.has_the_word = 'important' self.assertEquals(self.entry.has_the_word, 'important') def testDoesNotHaveTheWord(self): self.entry.does_not_have_the_word = 'spam' self.assertEquals(self.entry.does_not_have_the_word, 'spam') def testHasAttachments(self): self.entry.has_attachments = True self.assertEquals(self.entry.has_attachments, True) def testLabel(self): self.entry.label = 'Trip reports' self.assertEquals(self.entry.label, 'Trip reports') def testMarkHasRead(self): self.entry.mark_has_read = True self.assertEquals(self.entry.mark_has_read, True) def testArchive(self): self.entry.archive = True self.assertEquals(self.entry.archive, True) class EmailSettingsSendAsAliasTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsSendAsAlias() def testName(self): self.entry.name = 'Sales' self.assertEquals(self.entry.name, 'Sales') def testAddress(self): self.entry.address = 'sales@example.com' self.assertEquals(self.entry.address, 'sales@example.com') def testReplyTo(self): self.entry.reply_to = 'support@example.com' self.assertEquals(self.entry.reply_to, 'support@example.com') def testMakeDefault(self): self.entry.make_default = True self.assertEquals(self.entry.make_default, True) class EmailSettingsWebClipTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsWebClip() def testEnable(self): self.entry.enable = True self.assertEquals(self.entry.enable, True) class EmailSettingsForwardingTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsForwarding() def testEnable(self): self.entry.enable = True self.assertEquals(self.entry.enable, True) def testForwardTo(self): self.entry.forward_to = 'fred@example.com' self.assertEquals(self.entry.forward_to, 'fred@example.com') def testAction(self): self.entry.action = 'KEEP' self.assertEquals(self.entry.action, 'KEEP') class EmailSettingsPopTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsPop() def testEnable(self): self.entry.enable = True self.assertEquals(self.entry.enable, True) def testForwardTo(self): self.entry.enable_for = 'ALL_MAIL' self.assertEquals(self.entry.enable_for, 'ALL_MAIL') def testAction(self): self.entry.action = 'KEEP' self.assertEquals(self.entry.action, 'KEEP') class EmailSettingsImapTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsImap() def testEnable(self): self.entry.enable = True self.assertEquals(self.entry.enable, True) class EmailSettingsVacationResponderTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsVacationResponder() def testEnable(self): self.entry.enable = True self.assertEquals(self.entry.enable, True) def testSubject(self): self.entry.subject = 'On vacation!' self.assertEquals(self.entry.subject, 'On vacation!') def testMessage(self): self.entry.message = 'See you on September 1st' self.assertEquals(self.entry.message, 'See you on September 1st') def testContactsOnly(self): self.entry.contacts_only = True self.assertEquals(self.entry.contacts_only, True) class EmailSettingsSignatureTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsSignature() def testValue(self): self.entry.signature_value = 'Regards, Joe' self.assertEquals(self.entry.signature_value, 'Regards, Joe') class EmailSettingsLanguageTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsLanguage() def testLanguage(self): self.entry.language_tag = 'es' self.assertEquals(self.entry.language_tag, 'es') class EmailSettingsGeneralTest(unittest.TestCase): def setUp(self): self.entry = gdata.apps.emailsettings.data.EmailSettingsGeneral() def testPageSize(self): self.entry.page_size = 25 self.assertEquals(self.entry.page_size, 25) def testShortcuts(self): self.entry.shortcuts = True self.assertEquals(self.entry.shortcuts, True) def testArrows(self): self.entry.arrows = True self.assertEquals(self.entry.arrows, True) def testSnippets(self): self.entry.snippets = True self.assertEquals(self.entry.snippets, True) def testUnicode(self): self.entry.use_unicode = True self.assertEquals(self.entry.use_unicode, True) def suite(): return conf.build_suite([EmailSettingsLabelTest, EmailSettingsFilterTest, EmailSettingsSendAsAliasTest, EmailSettingsWebClipTest, EmailSettingsForwardingTest, EmailSettingsPopTest, EmailSettingsImapTest, EmailSettingsVacationResponderTest, EmailSettingsSignatureTest, EmailSettingsLanguageTest, EmailSettingsGeneralTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for Email Settings service.""" __author__ = 'google-apps-apis@googlegroups.com' import getpass import gdata.apps.emailsettings.service import unittest domain = '' admin_email = '' admin_password = '' username = '' class EmailSettingsTest(unittest.TestCase): """Test for the EmailSettingsService.""" def setUp(self): self.es = gdata.apps.emailsettings.service.EmailSettingsService( email=admin_email, password=admin_password, domain=domain) self.es.ProgrammaticLogin() def testCreateLabel(self): result = self.es.CreateLabel(username, label='New label!!!') self.assertEquals(result['label'], 'New label!!!') def testCreateFilter(self): result = self.es.CreateFilter(username, from_='from_foo', to='to_foo', subject='subject_foo', has_the_word='has_the_words_foo', does_not_have_the_word='doesnt_have_foo', has_attachment=True, label='label_foo', should_mark_as_read=True, should_archive=True) self.assertEquals(result['from'], 'from_foo') self.assertEquals(result['to'], 'to_foo') self.assertEquals(result['subject'], 'subject_foo') def testCreateSendAsAlias(self): result = self.es.CreateSendAsAlias(username, name='Send-as Alias', address='user2@sizzles.org', reply_to='user3@sizzles.org', make_default=True) self.assertEquals(result['name'], 'Send-as Alias') def testUpdateWebClipSettings(self): result = self.es.UpdateWebClipSettings(username, enable=True) self.assertEquals(result['enable'], 'true') def testUpdateForwarding(self): result = self.es.UpdateForwarding(username, enable=True, forward_to='user4@sizzles.org', action=gdata.apps.emailsettings.service.KEEP) self.assertEquals(result['enable'], 'true') def testUpdatePop(self): result = self.es.UpdatePop(username, enable=True, enable_for=gdata.apps.emailsettings.service.ALL_MAIL, action=gdata.apps.emailsettings.service.ARCHIVE) self.assertEquals(result['enable'], 'true') def testUpdateImap(self): result = self.es.UpdateImap(username, enable=True) self.assertEquals(result['enable'], 'true') def testUpdateVacation(self): result = self.es.UpdateVacation(username, enable=True, subject='Hawaii', message='Wish you were here!', contacts_only=True) self.assertEquals(result['subject'], 'Hawaii') def testUpdateSignature(self): result = self.es.UpdateSignature(username, signature='Signature') self.assertEquals(result['signature'], 'Signature') def testUpdateLanguage(self): result = self.es.UpdateLanguage(username, language='fr') self.assertEquals(result['language'], 'fr') def testUpdateGeneral(self): result = self.es.UpdateGeneral(username, page_size=100, shortcuts=True, arrows=True, snippets=True, unicode=True) self.assertEquals(result['pageSize'], '100') if __name__ == '__main__': print("""Google Apps Email Settings Service Tests NOTE: Please run these tests only with a test user account. """) domain = raw_input('Google Apps domain: ') admin_email = '%s@%s' % (raw_input('Administrator username: '), domain) admin_password = getpass.getpass('Administrator password: ') username = raw_input('Test username: ') unittest.main()
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'Claudio Cherubino <ccherubino@google.com>' import unittest import gdata.client import gdata.data import gdata.gauth import gdata.apps.emailsettings.client import gdata.apps.emailsettings.data import gdata.test_config as conf conf.options.register_option(conf.APPS_DOMAIN_OPTION) conf.options.register_option(conf.TARGET_USERNAME_OPTION) class EmailSettingsClientTest(unittest.TestCase): def setUp(self): self.client = gdata.apps.emailsettings.client.EmailSettingsClient( domain='example.com') if conf.options.get_value('runlive') == 'true': self.client = gdata.apps.emailsettings.client.EmailSettingsClient( domain=conf.options.get_value('appsdomain')) if conf.options.get_value('ssl') == 'true': self.client.ssl = True conf.configure_client(self.client, 'EmailSettingsClientTest', self.client.auth_service, True) self.username = conf.options.get_value('appsusername').split('@')[0] def tearDown(self): conf.close_client(self.client) def testClientConfiguration(self): self.assertEqual('apps-apis.google.com', self.client.host) self.assertEqual('2.0', self.client.api_version) self.assertEqual('apps', self.client.auth_service) self.assertEqual( ('http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'), self.client.auth_scopes) if conf.options.get_value('runlive') == 'true': self.assertEqual(self.client.domain, conf.options.get_value('appsdomain')) else: self.assertEqual(self.client.domain, 'example.com') def testMakeEmailSettingsUri(self): self.assertEqual('/a/feeds/emailsettings/2.0/%s/%s/%s' % (self.client.domain, 'abc', 'label'), self.client.MakeEmailSettingsUri('abc', 'label')) def testCreateLabel(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateLabel') new_label = self.client.CreateLabel( username=conf.options.get_value('targetusername'), name='status updates') self.assert_(isinstance(new_label, gdata.apps.emailsettings.data.EmailSettingsLabel)) self.assertEqual(new_label.name, 'status updates') def testCreateFilter(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateFilter') new_filter = self.client.CreateFilter( username=conf.options.get_value('targetusername'), from_address='alice@gmail.com', has_the_word='project proposal', mark_as_read=True) self.assert_(isinstance(new_filter, gdata.apps.emailsettings.data.EmailSettingsFilter)) self.assertEqual(new_filter.from_address, 'alice@gmail.com') self.assertEqual(new_filter.has_the_word, 'project proposal') self.assertEqual(new_filter.mark_as_read, 'True') new_filter = self.client.CreateFilter( username=conf.options.get_value('targetusername'), to_address='announcements@example.com', label="announcements") self.assert_(isinstance(new_filter, gdata.apps.emailsettings.data.EmailSettingsFilter)) self.assertEqual(new_filter.to_address, 'announcements@example.com') self.assertEqual(new_filter.label, 'announcements') new_filter = self.client.CreateFilter( username=conf.options.get_value('targetusername'), subject='urgent', does_not_have_the_word='spam', has_attachments=True, archive=True) self.assert_(isinstance(new_filter, gdata.apps.emailsettings.data.EmailSettingsFilter)) self.assertEqual(new_filter.subject, 'urgent') self.assertEqual(new_filter.does_not_have_the_word, 'spam') self.assertEqual(new_filter.has_attachments, 'True') self.assertEqual(new_filter.archive, 'True') def testCreateSendAs(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateSendAs') new_sendas = self.client.CreateSendAs( username=conf.options.get_value('targetusername'), name='Sales', address=conf.options.get_value('appsusername'), reply_to='abc@gmail.com', make_default=True) self.assert_(isinstance(new_sendas, gdata.apps.emailsettings.data.EmailSettingsSendAsAlias)) self.assertEqual(new_sendas.name, 'Sales') self.assertEqual(new_sendas.address, conf.options.get_value('appsusername')) self.assertEqual(new_sendas.reply_to, 'abc@gmail.com') self.assertEqual(new_sendas.make_default, 'True') def testUpdateWebclip(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateWebclip') new_webclip = self.client.UpdateWebclip( username=conf.options.get_value('targetusername'), enable=True) self.assert_(isinstance(new_webclip, gdata.apps.emailsettings.data.EmailSettingsWebClip)) self.assertEqual(new_webclip.enable, 'True') new_webclip = self.client.UpdateWebclip( username=conf.options.get_value('targetusername'), enable=False) self.assert_(isinstance(new_webclip, gdata.apps.emailsettings.data.EmailSettingsWebClip)) self.assertEqual(new_webclip.enable, 'False') def testUpdateForwarding(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateForwarding') new_forwarding = self.client.UpdateForwarding( username=conf.options.get_value('targetusername'), enable=True, forward_to=conf.options.get_value('appsusername'), action='KEEP') self.assert_(isinstance(new_forwarding, gdata.apps.emailsettings.data.EmailSettingsForwarding)) self.assertEqual(new_forwarding.enable, 'True') self.assertEqual(new_forwarding.forward_to, conf.options.get_value('appsusername')) self.assertEqual(new_forwarding.action, 'KEEP') new_forwarding = self.client.UpdateForwarding( username=conf.options.get_value('targetusername'), enable=False) self.assert_(isinstance(new_forwarding, gdata.apps.emailsettings.data.EmailSettingsForwarding)) self.assertEqual(new_forwarding.enable, 'False') def testUpdatePop(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdatePop') new_pop = self.client.UpdatePop( username=conf.options.get_value('targetusername'), enable=True, enable_for='MAIL_FROM_NOW_ON', action='KEEP') self.assert_(isinstance(new_pop, gdata.apps.emailsettings.data.EmailSettingsPop)) self.assertEqual(new_pop.enable, 'True') self.assertEqual(new_pop.enable_for, 'MAIL_FROM_NOW_ON') self.assertEqual(new_pop.action, 'KEEP') new_pop = self.client.UpdatePop( username=conf.options.get_value('targetusername'), enable=False) self.assert_(isinstance(new_pop, gdata.apps.emailsettings.data.EmailSettingsPop)) self.assertEqual(new_pop.enable, 'False') def testUpdateImap(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateImap') new_imap = self.client.UpdateImap( username=conf.options.get_value('targetusername'), enable=True) self.assert_(isinstance(new_imap, gdata.apps.emailsettings.data.EmailSettingsImap)) self.assertEqual(new_imap.enable, 'True') new_imap = self.client.UpdateImap( username=conf.options.get_value('targetusername'), enable=False) self.assert_(isinstance(new_imap, gdata.apps.emailsettings.data.EmailSettingsImap)) self.assertEqual(new_imap.enable, 'False') def testUpdateVacation(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateVacation') new_vacation = self.client.UpdateVacation( username=conf.options.get_value('targetusername'), enable=True, subject='Out of office', message='If urgent call me at 555-5555.', contacts_only=True) self.assert_(isinstance(new_vacation, gdata.apps.emailsettings.data.EmailSettingsVacationResponder)) self.assertEqual(new_vacation.enable, 'True') self.assertEqual(new_vacation.subject, 'Out of office') self.assertEqual(new_vacation.message, 'If urgent call me at 555-5555.') self.assertEqual(new_vacation.contacts_only, 'True') new_vacation = self.client.UpdateVacation( username=conf.options.get_value('targetusername'), enable=False) self.assert_(isinstance(new_vacation, gdata.apps.emailsettings.data.EmailSettingsVacationResponder)) self.assertEqual(new_vacation.enable, 'False') def testUpdateSignature(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateSignature') new_signature = self.client.UpdateSignature( username=conf.options.get_value('targetusername'), signature='Regards, Joe') self.assert_(isinstance(new_signature, gdata.apps.emailsettings.data.EmailSettingsSignature)) self.assertEqual(new_signature.signature_value, 'Regards, Joe') new_signature = self.client.UpdateSignature( username=conf.options.get_value('targetusername'), signature='') self.assert_(isinstance(new_signature, gdata.apps.emailsettings.data.EmailSettingsSignature)) self.assertEqual(new_signature.signature_value, '') def testUpdateLanguage(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateLanguage') new_language = self.client.UpdateLanguage( username=conf.options.get_value('targetusername'), language='es') self.assert_(isinstance(new_language, gdata.apps.emailsettings.data.EmailSettingsLanguage)) self.assertEqual(new_language.language_tag, 'es') def testUpdateGeneral(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUpdateGeneral') new_general = self.client.UpdateGeneralSettings( username=conf.options.get_value('targetusername'), page_size=25, arrows=True) self.assert_(isinstance(new_general, gdata.apps.emailsettings.data.EmailSettingsGeneral)) self.assertEqual(new_general.page_size, '25') self.assertEqual(new_general.arrows, 'True') new_general = self.client.UpdateGeneralSettings( username=conf.options.get_value('targetusername'), shortcuts=False, snippets=True, use_unicode=False) self.assert_(isinstance(new_general, gdata.apps.emailsettings.data.EmailSettingsGeneral)) self.assertEqual(new_general.shortcuts, 'False') self.assertEqual(new_general.snippets, 'True') self.assertEqual(new_general.use_unicode, 'False') def suite(): return conf.build_suite([EmailSettingsClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for Organization service.""" __author__ = 'Alexandre Vivien (alex@simplecode.fr)' import urllib import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.apps import gdata.apps.service import gdata.apps.organization.service import getpass import time domain = '' admin_email = '' admin_password = '' username = '' class OrganizationTest(unittest.TestCase): """Test for the OrganizationService.""" def setUp(self): self.postfix = time.strftime("%Y%m%d%H%M%S") self.apps_client = gdata.apps.service.AppsService( email=admin_email, domain=domain, password=admin_password, source='OrganizationClient "Unit" Tests') self.apps_client.ProgrammaticLogin() self.organization_client = gdata.apps.organization.service.OrganizationService( email=admin_email, domain=domain, password=admin_password, source='GroupsClient "Unit" Tests') self.organization_client.ProgrammaticLogin() self.created_users = [] self.created_org_units = [] self.cutomer_id = None self.createUsers(); def createUsers(self): user_name = 'yujimatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Yuji' password = '123$$abc' suspended = 'false' try: self.user_yuji = self.apps_client.CreateUser(user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) print 'User ' + user_name + ' created' except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(self.user_yuji) user_name = 'taromatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Taro' password = '123$$abc' suspended = 'false' try: self.user_taro = self.apps_client.CreateUser(user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) print 'User ' + user_name + ' created' except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(self.user_taro) user_name = 'alexandrevivien-' + self.postfix family_name = 'Vivien' given_name = 'Alexandre' password = '123$$abc' suspended = 'false' try: self.user_alex = self.apps_client.CreateUser(user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) print 'User ' + user_name + ' created' except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(self.user_alex) def tearDown(self): print '\n' for user in self.created_users: try: self.apps_client.DeleteUser(user.login.user_name) print 'User ' + user.login.user_name + ' deleted' except Exception, e: print e # We reverse to delete sub OrgUnit first self.created_org_units.reverse() for org_unit_path in self.created_org_units: try: self.organization_client.DeleteOrgUnit(self.customer_id, org_unit_path) print 'OrgUnit ' + org_unit_path + ' deleted' except Exception, e: print e def testOrganizationService(self): # tests RetrieveCustomerId method try: customer = self.organization_client.RetrieveCustomerId() self.customer_id = customer['customerId'] except Exception, e: self.fail('Unexpected exception occurred: %s' % e) print 'tests RetrieveCustomerId successful' # tests CreateOrgUnit method orgUnit01_name = 'OrgUnit01-' + self.postfix orgUnit02_name = 'OrgUnit02-' + self.postfix sub0rgUnit01_name = 'SubOrgUnit01-' + self.postfix orgUnit03_name = 'OrgUnit03-' + self.postfix try: orgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id, name=orgUnit01_name, parent_org_unit_path='/', description='OrgUnit Test 01', block_inheritance=False) orgUnit02 = self.organization_client.CreateOrgUnit(self.customer_id, name=orgUnit02_name, parent_org_unit_path='/', description='OrgUnit Test 02', block_inheritance=False) sub0rgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id, name=sub0rgUnit01_name, parent_org_unit_path=orgUnit02['orgUnitPath'], description='SubOrgUnit Test 01', block_inheritance=False) orgUnit03 = self.organization_client.CreateOrgUnit(self.customer_id, name=orgUnit03_name, parent_org_unit_path='/', description='OrgUnit Test 03', block_inheritance=False) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(orgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit01_name)) self.assertEquals(orgUnit02['orgUnitPath'], urllib.quote_plus(orgUnit02_name)) self.assertEquals(sub0rgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit02_name) + '/' + urllib.quote_plus(sub0rgUnit01_name)) self.assertEquals(orgUnit03['orgUnitPath'], urllib.quote_plus(orgUnit03_name)) self.created_org_units.append(orgUnit01['orgUnitPath']) self.created_org_units.append(orgUnit02['orgUnitPath']) self.created_org_units.append(sub0rgUnit01['orgUnitPath']) self.created_org_units.append(orgUnit03['orgUnitPath']) print 'tests CreateOrgUnit successful' # tests UpdateOrgUnit method try: updated_orgunit = self.organization_client.UpdateOrgUnit(self.customer_id, org_unit_path=self.created_org_units[3], description='OrgUnit Test 03 Updated description') except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(updated_orgunit['orgUnitPath'], self.created_org_units[3]) print 'tests UpdateOrgUnit successful' # tests RetrieveOrgUnit method try: retrieved_orgunit = self.organization_client.RetrieveOrgUnit(self.customer_id, org_unit_path=self.created_org_units[1]) retrieved_suborgunit = self.organization_client.RetrieveOrgUnit(self.customer_id, org_unit_path=self.created_org_units[2]) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(retrieved_orgunit['orgUnitPath'], self.created_org_units[1]) self.assertEquals(retrieved_suborgunit['orgUnitPath'], self.created_org_units[2]) print 'tests RetrieveOrgUnit successful' # tests RetrieveAllOrgUnits method try: retrieved_orgunits = self.organization_client.RetrieveAllOrgUnits(self.customer_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertTrue(len(retrieved_orgunits) >= len(self.created_org_units)) print 'tests RetrieveAllOrgUnits successful' # tests MoveUserToOrgUnit method try: updated_orgunit01 = self.organization_client.MoveUserToOrgUnit(self.customer_id, org_unit_path=self.created_org_units[0], users_to_move=[self.user_yuji.login.user_name + '@' + domain]) updated_orgunit02 = self.organization_client.MoveUserToOrgUnit(self.customer_id, org_unit_path=self.created_org_units[1], users_to_move=[self.user_taro.login.user_name + '@' + domain, self.user_alex.login.user_name + '@' + domain]) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(updated_orgunit01['usersMoved'], self.user_yuji.login.user_name + '@' + domain) self.assertEquals(updated_orgunit02['usersMoved'], self.user_taro.login.user_name + '@' + domain + ',' + \ self.user_alex.login.user_name + '@' + domain) print 'tests MoveUserToOrgUnit successful' # tests RetrieveSubOrgUnits method try: retrieved_suborgunits = self.organization_client.RetrieveSubOrgUnits(self.customer_id, org_unit_path=self.created_org_units[1]) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_suborgunits), 1) self.assertEquals(retrieved_suborgunits[0]['orgUnitPath'], self.created_org_units[2]) print 'tests RetrieveSubOrgUnits successful' # tests RetrieveOrgUser method try: retrieved_orguser = self.organization_client.RetrieveOrgUser(self.customer_id, user_email=self.user_yuji.login.user_name + '@' + domain) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(retrieved_orguser['orgUserEmail'], self.user_yuji.login.user_name + '@' + domain) self.assertEquals(retrieved_orguser['orgUnitPath'], self.created_org_units[0]) print 'tests RetrieveOrgUser successful' # tests UpdateOrgUser method try: updated_orguser = self.organization_client.UpdateOrgUser(self.customer_id, org_unit_path=self.created_org_units[0], user_email=self.user_alex.login.user_name + '@' + domain) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(updated_orguser['orgUserEmail'], self.user_alex.login.user_name + '@' + domain) self.assertEquals(updated_orguser['orgUnitPath'], self.created_org_units[0]) print 'tests UpdateOrgUser successful' # tests RetrieveAllOrgUsers method try: retrieved_orgusers = self.organization_client.RetrieveAllOrgUsers(self.customer_id) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertTrue(len(retrieved_orgusers) >= len(self.created_users)) print 'tests RetrieveAllOrgUsers successful' """ This test needs to create more than 100 test users # tests RetrievePageOfOrgUsers method try: retrieved_orgusers01_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id) next = retrieved_orgusers01_feed.GetNextLink() self.assertNotEquals(next, None) startKey = next.href.split("startKey=")[1] retrieved_orgusers02_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id, startKey=startKey) retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0]) retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0]) self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail']) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) print 'tests RetrievePageOfOrgUsers successful' """ # tests RetrieveOrgUnitUsers method try: retrieved_orgusers = self.organization_client.RetrieveOrgUnitUsers(self.customer_id, org_unit_path=self.created_org_units[0]) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assertEquals(len(retrieved_orgusers), 2) print 'tests RetrieveOrgUnitUsers successful' """ This test needs to create more than 100 test users # tests RetrieveOrgUnitPageOfUsers method try: retrieved_orgusers01_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id, org_unit_path='/') next = retrieved_orgusers01_feed.GetNextLink() self.assertNotEquals(next, None) startKey = next.href.split("startKey=")[1] retrieved_orgusers02_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id, org_unit_path='/', startKey=startKey) retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0]) retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0]) self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail']) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) print 'tests RetrieveOrgUnitPageOfUsers successful' """ if __name__ == '__main__': print("""Google Apps Groups Service Tests NOTE: Please run these tests only with a test user account. """) domain = raw_input('Google Apps domain: ') admin_email = '%s@%s' % (raw_input('Administrator username: '), domain) admin_password = getpass.getpass('Administrator password: ') unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'tmatsuo@sios.com (Takashi Matsuo)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.apps import gdata.apps.service import getpass import time apps_domain = '' apps_username = '' apps_password = '' class AppsServiceUnitTest01(unittest.TestCase): def setUp(self): self.postfix = time.strftime("%Y%m%d%H%M%S") email = apps_username + '@' + apps_domain self.apps_client = gdata.apps.service.AppsService( email=email, domain=apps_domain, password=apps_password, source='AppsClient "Unit" Tests') self.apps_client.ProgrammaticLogin() self.created_user = None def tearDown(self): if self.created_user is not None: try: self.apps_client.DeleteUser(self.created_user.login.user_name) except Exception, e: pass def test001RetrieveUser(self): """Tests RetrieveUser method""" try: self_user_entry = self.apps_client.RetrieveUser(apps_username) except: self.fail('Unexpected exception occurred') self.assert_(isinstance(self_user_entry, gdata.apps.UserEntry), "The return value of RetrieveUser() must be an instance of " + "apps.UserEntry: %s" % self_user_entry) self.assertEquals(self_user_entry.login.user_name, apps_username) def test002RetrieveUserRaisesException(self): """Tests if RetrieveUser() raises AppsForYourDomainException with appropriate error code""" try: non_existance = self.apps_client.RetrieveUser('nobody-' + self.postfix) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') def testSuspendAndRestoreUser(self): # Create a test user user_name = 'an-apps-service-test-account-' + self.postfix family_name = 'Tester' given_name = 'Apps' password = '123$$abc' suspended = 'false' created_user = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) # Suspend then restore the new user. entry = self.apps_client.SuspendUser(created_user.login.user_name) self.assertEquals(entry.login.suspended, 'true') entry = self.apps_client.RestoreUser(created_user.login.user_name) self.assertEquals(entry.login.suspended, 'false') # Clean up, delete the test user. self.apps_client.DeleteUser(user_name) def test003MethodsForUser(self): """Tests methods for user""" user_name = 'TakashiMatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Takashi' password = '123$$abc' suspended = 'false' try: created_user = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) except Exception, e: self.assert_(False, 'Unexpected exception occurred: %s' % e) self.created_user = created_user self.assertEquals(created_user.login.user_name, user_name) self.assertEquals(created_user.login.suspended, suspended) self.assertEquals(created_user.name.family_name, family_name) self.assertEquals(created_user.name.given_name, given_name) # self.assertEquals(created_user.quota.limit, # gdata.apps.service.DEFAULT_QUOTA_LIMIT) """Tests RetrieveAllUsers method""" try: user_feed = self.apps_client.RetrieveAllUsers() except Exception, e: self.assert_(False, 'Unexpected exception occurred: %s' % e) succeed = False for a_entry in user_feed.entry: if a_entry.login.user_name == user_name: succeed = True self.assert_(succeed, 'There must be a user: %s' % user_name) """Tests UpdateUser method""" new_family_name = 'NewFamilyName' new_given_name = 'NewGivenName' new_quota = '4096' created_user.name.family_name = new_family_name created_user.name.given_name = new_given_name created_user.quota.limit = new_quota created_user.login.suspended = 'true' try: new_user_entry = self.apps_client.UpdateUser(user_name, created_user) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(new_user_entry, gdata.apps.UserEntry), "new user entry must be an instance of gdata.apps.UserEntry: %s" % new_user_entry) self.assertEquals(new_user_entry.name.family_name, new_family_name) self.assertEquals(new_user_entry.name.given_name, new_given_name) self.assertEquals(new_user_entry.login.suspended, 'true') # quota limit update does not always success. # self.assertEquals(new_user_entry.quota.limit, new_quota) nobody = gdata.apps.UserEntry() nobody.login = gdata.apps.Login(user_name='nobody-' + self.postfix) nobody.name = gdata.apps.Name(family_name='nobody', given_name='nobody') # make sure that there is no account with nobody- + self.postfix try: tmp_entry = self.apps_client.RetrieveUser('nobody-' + self.postfix) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') # make sure that UpdateUser fails with AppsForYourDomainException. try: new_user_entry = self.apps_client.UpdateUser('nobody-' + self.postfix, nobody) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') """Tests DeleteUser method""" try: self.apps_client.DeleteUser(user_name) except Exception, e: self.assert_(False, 'Unexpected exception occurred: %s' % e) # make sure that the account deleted try: self.apps_client.RetrieveUser(user_name) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') self.created_user = None # make sure that DeleteUser fails with AppsForYourDomainException. try: self.apps_client.DeleteUser(user_name) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') def test004MethodsForNickname(self): """Tests methods for nickname""" # first create a user account user_name = 'EmmyMatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Emmy' password = '123$$abc' suspended = 'false' try: created_user = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_user = created_user # tests CreateNickname method nickname = 'emmy-' + self.postfix try: created_nickname = self.apps_client.CreateNickname(user_name, nickname) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(created_nickname, gdata.apps.NicknameEntry), "Return value of CreateNickname method must be an instance of " + "gdata.apps.NicknameEntry: %s" % created_nickname) self.assertEquals(created_nickname.login.user_name, user_name) self.assertEquals(created_nickname.nickname.name, nickname) # tests RetrieveNickname method retrieved_nickname = self.apps_client.RetrieveNickname(nickname) self.assert_(isinstance(retrieved_nickname, gdata.apps.NicknameEntry), "Return value of RetrieveNickname method must be an instance of " + "gdata.apps.NicknameEntry: %s" % retrieved_nickname) self.assertEquals(retrieved_nickname.login.user_name, user_name) self.assertEquals(retrieved_nickname.nickname.name, nickname) # tests RetrieveNicknames method nickname_feed = self.apps_client.RetrieveNicknames(user_name) self.assert_(isinstance(nickname_feed, gdata.apps.NicknameFeed), "Return value of RetrieveNicknames method must be an instance of " + "gdata.apps.NicknameFeed: %s" % nickname_feed) self.assertEquals(nickname_feed.entry[0].login.user_name, user_name) self.assertEquals(nickname_feed.entry[0].nickname.name, nickname) # tests RetrieveAllNicknames method nickname_feed = self.apps_client.RetrieveAllNicknames() self.assert_(isinstance(nickname_feed, gdata.apps.NicknameFeed), "Return value of RetrieveAllNicknames method must be an instance of " + "gdata.apps.NicknameFeed: %s" % nickname_feed) succeed = False for a_entry in nickname_feed.entry: if a_entry.login.user_name == user_name and \ a_entry.nickname.name == nickname: succeed = True self.assert_(succeed, "There must be a nickname entry named %s." % nickname) # tests DeleteNickname method self.apps_client.DeleteNickname(nickname) try: non_existence = self.apps_client.RetrieveNickname(nickname) except gdata.apps.service.AppsForYourDomainException, e: self.assertEquals(e.error_code, gdata.apps.service.ENTITY_DOES_NOT_EXIST) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) else: self.fail('No exception occurred') class AppsServiceUnitTest02(unittest.TestCase): def setUp(self): self.postfix = time.strftime("%Y%m%d%H%M%S") email = apps_username + '@' + apps_domain self.apps_client = gdata.apps.service.AppsService( email=email, domain=apps_domain, password=apps_password, source='AppsClient "Unit" Tests') self.apps_client.ProgrammaticLogin() self.created_users = [] self.created_email_lists = [] def tearDown(self): for user in self.created_users: try: self.apps_client.DeleteUser(user.login.user_name) except Exception, e: print e for email_list in self.created_email_lists: try: self.apps_client.DeleteEmailList(email_list.email_list.name) except Exception, e: print e def test001MethodsForEmaillist(self): """Tests methods for emaillist """ user_name = 'YujiMatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Yuji' password = '123$$abc' suspended = 'false' try: user_yuji = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(user_yuji) user_name = 'TaroMatsuo-' + self.postfix family_name = 'Matsuo' given_name = 'Taro' password = '123$$abc' suspended = 'false' try: user_taro = self.apps_client.CreateUser( user_name=user_name, family_name=family_name, given_name=given_name, password=password, suspended=suspended) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_users.append(user_taro) # tests CreateEmailList method list_name = 'list01-' + self.postfix try: created_email_list = self.apps_client.CreateEmailList(list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(created_email_list, gdata.apps.EmailListEntry), "Return value of CreateEmailList method must be an instance of " + "EmailListEntry: %s" % created_email_list) self.assertEquals(created_email_list.email_list.name, list_name) self.created_email_lists.append(created_email_list) # tests AddRecipientToEmailList method try: recipient = self.apps_client.AddRecipientToEmailList( user_yuji.login.user_name + '@' + apps_domain, list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(recipient, gdata.apps.EmailListRecipientEntry), "Return value of AddRecipientToEmailList method must be an instance " + "of EmailListRecipientEntry: %s" % recipient) self.assertEquals(recipient.who.email, user_yuji.login.user_name + '@' + apps_domain) try: recipient = self.apps_client.AddRecipientToEmailList( user_taro.login.user_name + '@' + apps_domain, list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) # tests RetrieveAllRecipients method try: recipient_feed = self.apps_client.RetrieveAllRecipients(list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed), "Return value of RetrieveAllRecipients method must be an instance " + "of EmailListRecipientFeed: %s" % recipient_feed) self.assertEquals(len(recipient_feed.entry), 2) # tests RemoveRecipientFromEmailList method try: self.apps_client.RemoveRecipientFromEmailList( user_taro.login.user_name + '@' + apps_domain, list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) # make sure that removal succeeded. try: recipient_feed = self.apps_client.RetrieveAllRecipients(list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(recipient_feed, gdata.apps.EmailListRecipientFeed), "Return value of RetrieveAllRecipients method must be an instance " + "of EmailListRecipientFeed: %s" % recipient_feed) self.assertEquals(len(recipient_feed.entry), 1) # tests RetrieveAllEmailLists try: list_feed = self.apps_client.RetrieveAllEmailLists() except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed), "Return value of RetrieveAllEmailLists method must be an instance" + "of EmailListFeed: %s" % list_feed) succeed = False for email_list in list_feed.entry: if email_list.email_list.name == list_name: succeed = True self.assert_(succeed, "There must be an email list named %s" % list_name) # tests RetrieveEmailLists method. try: list_feed = self.apps_client.RetrieveEmailLists( user_yuji.login.user_name + '@' + apps_domain) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.assert_(isinstance(list_feed, gdata.apps.EmailListFeed), "Return value of RetrieveEmailLists method must be an instance" + "of EmailListFeed: %s" % list_feed) succeed = False for email_list in list_feed.entry: if email_list.email_list.name == list_name: succeed = True self.assert_(succeed, "There must be an email list named %s" % list_name) def testRetrieveEmailList(self): new_list = self.apps_client.CreateEmailList('my_testing_email_list') retrieved_list = self.apps_client.RetrieveEmailList('my_testing_email_list') self.assertEquals(new_list.title.text, retrieved_list.title.text) self.assertEquals(new_list.id.text, retrieved_list.id.text) self.assertEquals(new_list.email_list.name, retrieved_list.email_list.name) self.apps_client.DeleteEmailList('my_testing_email_list') # Should not be able to retrieve the deleted list. try: removed_list = self.apps_client.RetrieveEmailList('my_testing_email_list') self.fail() except gdata.apps.service.AppsForYourDomainException: pass class AppsServiceUnitTest03(unittest.TestCase): def setUp(self): self.postfix = time.strftime("%Y%m%d%H%M%S") email = apps_username + '@' + apps_domain self.apps_client = gdata.apps.service.AppsService( email=email, domain=apps_domain, password=apps_password, source='AppsClient "Unit" Tests') self.apps_client.ProgrammaticLogin() self.created_users = [] self.created_email_lists = [] def tearDown(self): for user in self.created_users: try: self.apps_client.DeleteUser(user.login.user_name) except Exception, e: print e for email_list in self.created_email_lists: try: self.apps_client.DeleteEmailList(email_list.email_list.name) except Exception, e: print e def test001Pagenation(self): """Tests for pagination. It takes toooo long.""" list_feed = self.apps_client.RetrieveAllEmailLists() quantity = len(list_feed.entry) list_nums = 101 for i in range(list_nums): list_name = 'list%03d-' % i + self.postfix try: created_email_list = self.apps_client.CreateEmailList(list_name) except Exception, e: self.fail('Unexpected exception occurred: %s' % e) self.created_email_lists.append(created_email_list) list_feed = self.apps_client.RetrieveAllEmailLists() self.assertEquals(len(list_feed.entry), list_nums + quantity) if __name__ == '__main__': print ('Google Apps Service Tests\nNOTE: Please run these tests only with ' 'a test domain. The tests may delete or update your domain\'s ' 'account data.') apps_domain = raw_input('Please enter your domain: ') apps_username = raw_input('Please enter your username of admin account: ') apps_password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = ('api.jfisher (Jeff Fisher), ' 'api.eric@google.com (Eric Bidelman)') import unittest from gdata import test_data import gdata.docs class DocumentListEntryTest(unittest.TestCase): def setUp(self): self.dl_entry = gdata.docs.DocumentListEntryFromString( test_data.DOCUMENT_LIST_ENTRY) def testToAndFromStringWithData(self): entry = gdata.docs.DocumentListEntryFromString(str(self.dl_entry)) self.assertEqual(entry.author[0].name.text, 'test.user') self.assertEqual(entry.author[0].email.text, 'test.user@gmail.com') self.assertEqual(entry.GetDocumentType(), 'spreadsheet') self.assertEqual(entry.id.text, 'https://docs.google.com/feeds/documents/private/full/' +\ 'spreadsheet%3Asupercalifragilisticexpealidocious') self.assertEqual(entry.title.text,'Test Spreadsheet') self.assertEqual(entry.resourceId.text, 'spreadsheet:supercalifragilisticexpealidocious') self.assertEqual(entry.lastModifiedBy.name.text,'test.user') self.assertEqual(entry.lastModifiedBy.email.text,'test.user@gmail.com') self.assertEqual(entry.lastViewed.text,'2009-03-05T07:48:21.493Z') self.assertEqual(entry.writersCanInvite.value, 'true') class DocumentListFeedTest(unittest.TestCase): def setUp(self): self.dl_feed = gdata.docs.DocumentListFeedFromString( test_data.DOCUMENT_LIST_FEED) def testToAndFromString(self): self.assert_(len(self.dl_feed.entry) == 2) for an_entry in self.dl_feed.entry: self.assert_(isinstance(an_entry, gdata.docs.DocumentListEntry)) new_dl_feed = gdata.docs.DocumentListFeedFromString(str(self.dl_feed)) for an_entry in new_dl_feed.entry: self.assert_(isinstance(an_entry, gdata.docs.DocumentListEntry)) def testConvertActualData(self): for an_entry in self.dl_feed.entry: self.assertEqual(an_entry.author[0].name.text, 'test.user') self.assertEqual(an_entry.author[0].email.text, 'test.user@gmail.com') self.assertEqual(an_entry.lastModifiedBy.name.text, 'test.user') self.assertEqual(an_entry.lastModifiedBy.email.text, 'test.user@gmail.com') self.assertEqual(an_entry.lastViewed.text,'2009-03-05T07:48:21.493Z') if(an_entry.GetDocumentType() == 'spreadsheet'): self.assertEqual(an_entry.title.text, 'Test Spreadsheet') self.assertEqual(an_entry.writersCanInvite.value, 'true') elif(an_entry.GetDocumentType() == 'document'): self.assertEqual(an_entry.title.text, 'Test Document') self.assertEqual(an_entry.writersCanInvite.value, 'false') def testLinkFinderFindsLinks(self): for entry in self.dl_feed.entry: # All Document List entries should have a self link self.assert_(entry.GetSelfLink() is not None) # All Document List entries should have an HTML link self.assert_(entry.GetHtmlLink() is not None) self.assert_(entry.feedLink.href is not None) class DocumentListAclEntryTest(unittest.TestCase): def setUp(self): self.acl_entry = gdata.docs.DocumentListAclEntryFromString( test_data.DOCUMENT_LIST_ACL_ENTRY) def testToAndFromString(self): self.assert_(isinstance(self.acl_entry, gdata.docs.DocumentListAclEntry)) self.assert_(isinstance(self.acl_entry.role, gdata.docs.Role)) self.assert_(isinstance(self.acl_entry.scope, gdata.docs.Scope)) self.assertEqual(self.acl_entry.scope.value, 'user@gmail.com') self.assertEqual(self.acl_entry.scope.type, 'user') self.assertEqual(self.acl_entry.role.value, 'writer') acl_entry_str = str(self.acl_entry) new_acl_entry = gdata.docs.DocumentListAclEntryFromString(acl_entry_str) self.assert_(isinstance(new_acl_entry, gdata.docs.DocumentListAclEntry)) self.assert_(isinstance(new_acl_entry.role, gdata.docs.Role)) self.assert_(isinstance(new_acl_entry.scope, gdata.docs.Scope)) self.assertEqual(new_acl_entry.scope.value, self.acl_entry.scope.value) self.assertEqual(new_acl_entry.scope.type, self.acl_entry.scope.type) self.assertEqual(new_acl_entry.role.value, self.acl_entry.role.value) def testCreateNewAclEntry(self): cat = gdata.atom.Category( term='http://schemas.google.com/acl/2007#accessRule', scheme='http://schemas.google.com/g/2005#kind') acl_entry = gdata.docs.DocumentListAclEntry(category=[cat]) acl_entry.scope = gdata.docs.Scope(value='user@gmail.com', type='user') acl_entry.role = gdata.docs.Role(value='writer') self.assert_(isinstance(acl_entry, gdata.docs.DocumentListAclEntry)) self.assert_(isinstance(acl_entry.role, gdata.docs.Role)) self.assert_(isinstance(acl_entry.scope, gdata.docs.Scope)) self.assertEqual(acl_entry.scope.value, 'user@gmail.com') self.assertEqual(acl_entry.scope.type, 'user') self.assertEqual(acl_entry.role.value, 'writer') class DocumentListAclFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.docs.DocumentListAclFeedFromString( test_data.DOCUMENT_LIST_ACL_FEED) def testToAndFromString(self): for entry in self.feed.entry: self.assert_(isinstance(entry, gdata.docs.DocumentListAclEntry)) feed = gdata.docs.DocumentListAclFeedFromString(str(self.feed)) for entry in feed.entry: self.assert_(isinstance(entry, gdata.docs.DocumentListAclEntry)) def testConvertActualData(self): entries = self.feed.entry self.assert_(len(entries) == 2) self.assertEqual(entries[0].title.text, 'Document Permission - user@gmail.com') self.assertEqual(entries[0].role.value, 'owner') self.assertEqual(entries[0].scope.type, 'user') self.assertEqual(entries[0].scope.value, 'user@gmail.com') self.assert_(entries[0].GetSelfLink() is not None) self.assert_(entries[0].GetEditLink() is not None) self.assertEqual(entries[1].title.text, 'Document Permission - user2@google.com') self.assertEqual(entries[1].role.value, 'writer') self.assertEqual(entries[1].scope.type, 'domain') self.assertEqual(entries[1].scope.value, 'google.com') self.assert_(entries[1].GetSelfLink() is not None) self.assert_(entries[1].GetEditLink() is not None) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'e.bidelman (Eric Bidelman)' import unittest import atom from gdata import test_data import gdata.acl.data import gdata.data import gdata.sites.data import gdata.test_config as conf def parse(xml_string, target_class): """Convenience wrapper for converting an XML string to an XmlElement.""" return atom.core.xml_element_from_string(xml_string, target_class) class CommentEntryTest(unittest.TestCase): def setUp(self): self.entry = parse(test_data.SITES_COMMENT_ENTRY, gdata.sites.data.ContentEntry) def testToAndFromStringCommentEntry(self): self.assertEqual(self.entry.Kind(), 'comment') self.assert_(isinstance(self.entry.in_reply_to, gdata.sites.data.InReplyTo)) self.assertEqual(self.entry.in_reply_to.type, 'text/html') self.assertEqual( self.entry.FindParentLink(), 'http://sites.google.com/feeds/content/site/gdatatestsite/abc123parent') self.assertEqual( self.entry.in_reply_to.href, 'http://sites.google.com/site/gdatatestsite/annoucment/testpost') self.assertEqual( self.entry.in_reply_to.ref, 'http://sites.google.com/feeds/content/site/gdatatestsite/abc123') self.assertEqual( self.entry.in_reply_to.source, 'http://sites.google.com/feeds/content/site/gdatatestsite') class ListPageEntryTest(unittest.TestCase): def setUp(self): self.entry = parse(test_data.SITES_LISTPAGE_ENTRY, gdata.sites.data.ContentEntry) def testToAndFromStringWithData(self): self.assert_(isinstance(self.entry, gdata.sites.data.ContentEntry)) self.assertEqual(self.entry.title.text, 'ListPagesTitle') self.assertEqual(len(self.entry.author), 1) self.assertEqual(self.entry.author[0].name.text, 'Test User') self.assertEqual(self.entry.author[0].email.text, 'test@gmail.com') self.assertEqual(self.entry.worksheet.name, 'listpage') self.assertEqual(self.entry.header.row, '1') self.assertEqual(self.entry.data.startRow, '2') self.assertEqual(len(self.entry.data.column), 5) self.assert_(isinstance(self.entry.data.column[0], gdata.sites.data.Column)) self.assertEqual(self.entry.data.column[0].index, 'A') self.assertEqual(self.entry.data.column[0].name, 'Owner') self.assert_(isinstance(self.entry.feed_link, gdata.data.FeedLink)) self.assertEqual( self.entry.feed_link.href, 'http:///sites.google.com/feeds/content/site/gdatatestsite?parent=abc') self.assert_(isinstance(self.entry.content, gdata.sites.data.Content)) self.assert_(isinstance(self.entry.content.html, atom.core.XmlElement)) self.assertEqual(self.entry.content.type, 'xhtml') class ListItemEntryTest(unittest.TestCase): def setUp(self): self.entry = parse(test_data.SITES_LISTITEM_ENTRY, gdata.sites.data.ContentEntry) def testToAndFromStringWithData(self): self.assert_(isinstance(self.entry, gdata.sites.data.ContentEntry)) self.assertEqual(len(self.entry.field), 5) self.assert_(isinstance(self.entry.field[0], gdata.sites.data.Field)) self.assertEqual(self.entry.field[0].index, 'A') self.assertEqual(self.entry.field[0].name, 'Owner') self.assertEqual(self.entry.field[0].text, 'test value') self.assertEqual( self.entry.FindParentLink(), 'http://sites.google.com/feeds/content/site/gdatatestsite/abc123def') class BaseSiteEntryTest(unittest.TestCase): def testCreateBaseSiteEntry(self): entry = gdata.sites.data.BaseSiteEntry() parent_link = atom.data.Link( rel=gdata.sites.data.SITES_PARENT_LINK_REL, href='abc') entry.link.append(parent_link) entry.category.append( atom.data.Category( scheme=gdata.sites.data.SITES_KIND_SCHEME, term='%s#%s' % (gdata.sites.data.SITES_NAMESPACE, 'webpage'), label='webpage')) self.assertEqual(entry.Kind(), 'webpage') self.assertEqual(entry.category[0].label, 'webpage') self.assertEqual( entry.category[0].term, '%s#%s' % ('http://schemas.google.com/sites/2008', 'webpage')) self.assertEqual(entry.link[0].href, 'abc') self.assertEqual(entry.link[0].rel, 'http://schemas.google.com/sites/2008#parent') entry2 = gdata.sites.data.BaseSiteEntry(kind='webpage') self.assertEqual( entry2.category[0].term, '%s#%s' % ('http://schemas.google.com/sites/2008', 'webpage')) class ContentFeedTest(unittest.TestCase): def setUp(self): self.feed = parse(test_data.SITES_CONTENT_FEED, gdata.sites.data.ContentFeed) def testToAndFromStringContentFeed(self): self.assert_(isinstance(self.feed, gdata.sites.data.ContentFeed)) self.assertEqual(len(self.feed.entry), 8) self.assert_(isinstance(self.feed.entry[0].revision, gdata.sites.data.Revision)) self.assertEqual(int(self.feed.entry[0].revision.text), 2) self.assertEqual(self.feed.entry[0].GetNodeId(), '1712987567114738703') self.assert_(isinstance(self.feed.entry[0].page_name, gdata.sites.data.PageName)) self.assertEqual(self.feed.entry[0].page_name.text, 'home') self.assertEqual(self.feed.entry[0].FindRevisionLink(), 'http:///sites.google.com/feeds/content/site/gdatatestsite/12345') for entry in self.feed.entry: self.assert_(isinstance(entry, gdata.sites.data.ContentEntry)) if entry.deleted is not None: self.assert_(isinstance(entry.deleted, gdata.sites.data.Deleted)) self.assertEqual(entry.IsDeleted(), True) else: self.assertEqual(entry.IsDeleted(), False) def testCreateContentEntry(self): new_entry = gdata.sites.data.ContentEntry() new_entry.content = gdata.sites.data.Content() new_entry.content.html = '<div><p>here is html</p></div>' self.assert_(isinstance(new_entry, gdata.sites.data.ContentEntry)) self.assert_(isinstance(new_entry.content, gdata.sites.data.Content)) self.assert_(isinstance(new_entry.content.html, atom.core.XmlElement)) new_entry2 = gdata.sites.data.ContentEntry() new_entry2.content = gdata.sites.data.Content( html='<div><p>here is html</p></div>') self.assert_(isinstance(new_entry2, gdata.sites.data.ContentEntry)) self.assert_(isinstance(new_entry2.content, gdata.sites.data.Content)) self.assert_(isinstance(new_entry2.content.html, atom.core.XmlElement)) def testGetHelpers(self): kinds = {'announcement': self.feed.GetAnnouncements, 'announcementspage': self.feed.GetAnnouncementPages, 'attachment': self.feed.GetAttachments, 'comment': self.feed.GetComments, 'filecabinet': self.feed.GetFileCabinets, 'listitem': self.feed.GetListItems, 'listpage': self.feed.GetListPages, 'webpage': self.feed.GetWebpages} for k, v in kinds.iteritems(): entries = v() self.assertEqual(len(entries), 1) for entry in entries: self.assertEqual(entry.Kind(), k) if k == 'attachment': self.assertEqual(entry.GetAlternateLink().href, 'http://sites.google.com/feeds/SOMELONGURL') class ActivityFeedTest(unittest.TestCase): def setUp(self): self.feed = parse(test_data.SITES_ACTIVITY_FEED, gdata.sites.data.ActivityFeed) def testToAndFromStringActivityFeed(self): self.assert_(isinstance(self.feed, gdata.sites.data.ActivityFeed)) self.assertEqual(len(self.feed.entry), 2) for entry in self.feed.entry: self.assert_(isinstance(entry.summary, gdata.sites.data.Summary)) self.assertEqual(entry.summary.type, 'xhtml') self.assert_(isinstance(entry.summary.html, atom.core.XmlElement)) class RevisionFeedTest(unittest.TestCase): def setUp(self): self.feed = parse(test_data.SITES_REVISION_FEED, gdata.sites.data.RevisionFeed) def testToAndFromStringRevisionFeed(self): self.assert_(isinstance(self.feed, gdata.sites.data.RevisionFeed)) self.assertEqual(len(self.feed.entry), 1) entry = self.feed.entry[0] self.assert_(isinstance(entry.content, gdata.sites.data.Content)) self.assert_(isinstance(entry.content.html, atom.core.XmlElement)) self.assertEqual(entry.content.type, 'xhtml') self.assertEqual( entry.FindParentLink(), 'http://sites.google.com/feeds/content/site/siteName/54395424125706119') class SiteFeedTest(unittest.TestCase): def setUp(self): self.feed = parse(test_data.SITES_SITE_FEED, gdata.sites.data.SiteFeed) def testToAndFromStringSiteFeed(self): self.assert_(isinstance(self.feed, gdata.sites.data.SiteFeed)) self.assertEqual(len(self.feed.entry), 2) entry = self.feed.entry[0] self.assert_(isinstance(entry.site_name, gdata.sites.data.SiteName)) self.assertEqual(entry.title.text, 'New Test Site') self.assertEqual(entry.site_name.text, 'new-test-site') self.assertEqual( entry.FindAclLink(), 'http://sites.google.com/feeds/acl/site/example.com/new-test-site') self.assertEqual( entry.FindSourceLink(), 'http://sites.google.com/feeds/site/example.com/source-site') self.assertEqual(entry.theme.text, 'iceberg') class AclFeedTest(unittest.TestCase): def setUp(self): self.feed = parse(test_data.SITES_ACL_FEED, gdata.sites.data.AclFeed) def testToAndFromStringAclFeed(self): self.assert_(isinstance(self.feed, gdata.sites.data.AclFeed)) self.assertEqual(len(self.feed.entry), 1) entry = self.feed.entry[0] self.assert_(isinstance(entry, gdata.sites.data.AclEntry)) self.assert_(isinstance(entry.scope, gdata.acl.data.AclScope)) self.assertEqual(entry.scope.type, 'user') self.assertEqual(entry.scope.value, 'user@example.com') self.assert_(isinstance(entry.role, gdata.acl.data.AclRole)) self.assertEqual(entry.role.value, 'owner') self.assertEqual( entry.GetSelfLink().href, ('https://sites.google.com/feeds/acl/site/example.com/' 'new-test-site/user%3Auser%40example.com')) class DataClassSanityTest(unittest.TestCase): def test_basic_element_structure(self): conf.check_data_classes(self, [ gdata.sites.data.Revision, gdata.sites.data.PageName, gdata.sites.data.Deleted, gdata.sites.data.Publisher, gdata.sites.data.Worksheet, gdata.sites.data.Header, gdata.sites.data.Column, gdata.sites.data.Data, gdata.sites.data.Field, gdata.sites.data.InReplyTo, gdata.sites.data.BaseSiteEntry, gdata.sites.data.ContentEntry, gdata.sites.data.ContentFeed, gdata.sites.data.ActivityEntry, gdata.sites.data.ActivityFeed, gdata.sites.data.RevisionEntry, gdata.sites.data.RevisionFeed, gdata.sites.data.Content, gdata.sites.data.Summary, gdata.sites.data.SiteName, gdata.sites.data.SiteEntry, gdata.sites.data.SiteFeed, gdata.sites.data.AclEntry, gdata.sites.data.AclFeed, gdata.sites.data.Theme]) def suite(): return conf.build_suite([ CommentEntryTest, ListPageEntryTest, ListItemEntryTest, BaseSiteEntryTest, ContentFeedTest, ActivityFeedTest, RevisionFeedTest, SiteFeedTest, AclFeedTest, DataClassSanityTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'e.bidelman (Eric Bidelman)' import unittest import gdata.client import gdata.data import gdata.gauth import gdata.sites.client import gdata.sites.data import gdata.test_config as conf conf.options.register_option(conf.TEST_IMAGE_LOCATION_OPTION) conf.options.register_option(conf.APPS_DOMAIN_OPTION) conf.options.register_option(conf.SITES_NAME_OPTION) class SitesClientTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.sites.client.SitesClient( site=conf.options.get_value('sitename'), domain=conf.options.get_value('appsdomain')) if conf.options.get_value('ssl') == 'true': self.client.ssl = True conf.configure_client(self.client, 'SitesTest', self.client.auth_service, True) def tearDown(self): conf.close_client(self.client) def testCreateUpdateDelete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateUpdateDelete') new_entry = self.client.CreatePage( 'webpage', 'Title Of Page', '<b>Your html content</b>') self.assertEqual(new_entry.title.text, 'Title Of Page') self.assertEqual(new_entry.page_name.text, 'title-of-page') self.assert_(new_entry.GetAlternateLink().href is not None) self.assertEqual(new_entry.Kind(), 'webpage') # Change the title of the webpage we just added. new_entry.title.text = 'Edited' updated_entry = self.client.update(new_entry) self.assertEqual(updated_entry.title.text, 'Edited') self.assertEqual(updated_entry.page_name.text, 'title-of-page') self.assert_(isinstance(updated_entry, gdata.sites.data.ContentEntry)) # Delete the test webpage from the Site. self.client.delete(updated_entry) def testCreateAndUploadToFilecabinet(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateAndUploadToFilecabinet') filecabinet = self.client.CreatePage( 'filecabinet', 'FilesGoHere', '<b>Your html content</b>', page_name='diff-pagename-than-title') self.assertEqual(filecabinet.title.text, 'FilesGoHere') self.assertEqual(filecabinet.page_name.text, 'diff-pagename-than-title') self.assert_(filecabinet.GetAlternateLink().href is not None) self.assertEqual(filecabinet.Kind(), 'filecabinet') # Upload a file to the filecabinet filepath = conf.options.get_value('imgpath') attachment = self.client.UploadAttachment( filepath, filecabinet, content_type='image/jpeg', title='TestImageFile', description='description here') self.assertEqual(attachment.title.text, 'TestImageFile') self.assertEqual(attachment.FindParentLink(), filecabinet.GetSelfLink().href) # Delete the test filecabinet and attachment from the Site. self.client.delete(attachment) self.client.delete(filecabinet) def suite(): return conf.build_suite([SitesClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python __author__ = "James Sams <sams.james@gmail.com>" import unittest import getpass import atom import gdata.books import gdata.books.service from gdata import test_data username = "" password = "" class BookCRUDTests(unittest.TestCase): def setUp(self): self.service = gdata.books.service.BookService(email=username, password=password, source="Google-PythonGdataTest-1") if username and password: self.authenticated = True self.service.ProgrammaticLogin() else: self.authenticated = False def testPublicSearch(self): entry = self.service.get_by_google_id("b7GZr5Btp30C") self.assertEquals((entry.creator[0].text, entry.dc_title[0].text), ('John Rawls', 'A theory of justice')) feed = self.service.search_by_keyword(isbn="9780198250548") feed1 = self.service.search("9780198250548") self.assertEquals(len(feed.entry), 1) self.assertEquals(len(feed1.entry), 1) def testLibraryCrd(self): """ the success of the create operations assumes the book was not already in the library. if it was, there will not be a failure, but a successful add will not actually be tested. """ if not self.authenticated: return entry = self.service.get_by_google_id("b7GZr5Btp30C") entry = self.service.add_item_to_library(entry) lib = list(self.service.get_library()) self.assert_(entry.to_dict()['title'] in [x.to_dict()['title'] for x in lib]) self.service.remove_item_from_library(entry) lib = list(self.service.get_library()) self.assert_(entry.to_dict()['title'] not in [x.to_dict()['title'] for x in lib]) def testAnnotations(self): "annotations do not behave as expected" pass if __name__ == "__main__": print "Please use a test account. May cause data loss." username = raw_input("Google Username: ").strip() password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.eric@google.com (Eric Bidelman)' import getpass import unittest from gdata import test_data import gdata.health import gdata.health.service username = '' password = '' class HealthQueryProfileListTest(unittest.TestCase): def setUp(self): self.health = gdata.health.service.HealthService() self.health.ClientLogin(username, password, source='Health Client Unit Tests') self.profile_list_feed = self.health.GetProfileListFeed() def testGetProfileListFeed(self): self.assert_(isinstance(self.profile_list_feed, gdata.health.ProfileListFeed)) self.assertEqual(self.profile_list_feed.id.text, 'https://www.google.com/health/feeds/profile/list') first_entry = self.profile_list_feed.entry[0] self.assert_(isinstance(first_entry, gdata.health.ProfileListEntry)) self.assert_(first_entry.GetProfileId() is not None) self.assert_(first_entry.GetProfileName() is not None) query = gdata.health.service.HealthProfileListQuery() profile_list = self.health.GetProfileListFeed(query) self.assertEqual(first_entry.GetProfileId(), profile_list.entry[0].GetProfileId()) self.assertEqual(profile_list.id.text, 'https://www.google.com/health/feeds/profile/list') class H9QueryProfileListTest(unittest.TestCase): def setUp(self): self.h9 = gdata.health.service.HealthService(use_h9_sandbox=True) self.h9.ClientLogin(username, password, source='H9 Client Unit Tests') self.profile_list_feed = self.h9.GetProfileListFeed() def testGetProfileListFeed(self): self.assert_(isinstance(self.profile_list_feed, gdata.health.ProfileListFeed)) self.assertEqual(self.profile_list_feed.id.text, 'https://www.google.com/h9/feeds/profile/list') first_entry = self.profile_list_feed.entry[0] self.assert_(isinstance(first_entry, gdata.health.ProfileListEntry)) self.assert_(first_entry.GetProfileId() is not None) self.assert_(first_entry.GetProfileName() is not None) query = gdata.health.service.HealthProfileListQuery() profile_list = self.h9.GetProfileListFeed(query) self.assertEqual(first_entry.GetProfileId(), profile_list.entry[0].GetProfileId()) self.assertEqual(profile_list.id.text, 'https://www.google.com/h9/feeds/profile/list') class HealthQueryProfileTest(unittest.TestCase): def setUp(self): self.health = gdata.health.service.HealthService() self.health.ClientLogin(username, password, source='Health Client Unit Tests') self.profile_list_feed = self.health.GetProfileListFeed() self.profile_id = self.profile_list_feed.entry[0].GetProfileId() def testGetProfileFeed(self): feed = self.health.GetProfileFeed(profile_id=self.profile_id) self.assert_(isinstance(feed, gdata.health.ProfileFeed)) self.assert_(isinstance(feed.entry[0].ccr, gdata.health.Ccr)) def testGetProfileFeedByQuery(self): query = gdata.health.service.HealthProfileQuery( projection='ui', profile_id=self.profile_id) feed = self.health.GetProfileFeed(query=query) self.assert_(isinstance(feed, gdata.health.ProfileFeed)) self.assert_(feed.entry[0].ccr is not None) def testGetProfileDigestFeed(self): query = gdata.health.service.HealthProfileQuery( projection='ui', profile_id=self.profile_id, params={'digest': 'true'}) feed = self.health.GetProfileFeed(query=query) self.assertEqual(len(feed.entry), 1) def testGetMedicationsAndConditions(self): query = gdata.health.service.HealthProfileQuery( projection='ui', profile_id=self.profile_id, params={'digest': 'true'}, categories=['medication|condition']) feed = self.health.GetProfileFeed(query=query) self.assertEqual(len(feed.entry), 1) if feed.entry[0].ccr.GetMedications() is not None: self.assert_(feed.entry[0].ccr.GetMedications()[0] is not None) self.assert_(feed.entry[0].ccr.GetConditions()[0] is not None) self.assert_(feed.entry[0].ccr.GetAllergies() is None) self.assert_(feed.entry[0].ccr.GetAlerts() is None) self.assert_(feed.entry[0].ccr.GetResults() is None) class H9QueryProfileTest(unittest.TestCase): def setUp(self): self.h9 = gdata.health.service.HealthService(use_h9_sandbox=True) self.h9.ClientLogin(username, password, source='H9 Client Unit Tests') self.profile_list_feed = self.h9.GetProfileListFeed() self.profile_id = self.profile_list_feed.entry[0].GetProfileId() def testGetProfileFeed(self): feed = self.h9.GetProfileFeed(profile_id=self.profile_id) self.assert_(isinstance(feed, gdata.health.ProfileFeed)) self.assert_(feed.entry[0].ccr is not None) def testGetProfileFeedByQuery(self): query = gdata.health.service.HealthProfileQuery( service='h9', projection='ui', profile_id=self.profile_id) feed = self.h9.GetProfileFeed(query=query) self.assert_(isinstance(feed, gdata.health.ProfileFeed)) self.assert_(feed.entry[0].ccr is not None) class HealthNoticeTest(unittest.TestCase): def setUp(self): self.health = gdata.health.service.HealthService() self.health.ClientLogin(username, password, source='Health Client Unit Tests') self.profile_list_feed = self.health.GetProfileListFeed() self.profile_id = self.profile_list_feed.entry[0].GetProfileId() def testSendNotice(self): subject_line = 'subject line' body = 'Notice <b>body</b>.' ccr_xml = test_data.HEALTH_CCR_NOTICE_PAYLOAD created_entry = self.health.SendNotice(subject_line, body, ccr=ccr_xml, profile_id=self.profile_id) self.assertEqual(created_entry.title.text, subject_line) self.assertEqual(created_entry.content.text, body) self.assertEqual(created_entry.content.type, 'html') problem = created_entry.ccr.GetProblems()[0] problem_desc = problem.FindChildren('Description')[0] name = problem_desc.FindChildren('Text')[0] self.assertEqual(name.text, 'Aortic valve disorders') class H9NoticeTest(unittest.TestCase): def setUp(self): self.h9 = gdata.health.service.HealthService(use_h9_sandbox=True) self.h9.ClientLogin(username, password, source='H9 Client Unit Tests') self.profile_list_feed = self.h9.GetProfileListFeed() self.profile_id = self.profile_list_feed.entry[0].GetProfileId() def testSendNotice(self): subject_line = 'subject line' body = 'Notice <b>body</b>.' ccr_xml = test_data.HEALTH_CCR_NOTICE_PAYLOAD created_entry = self.h9.SendNotice(subject_line, body, ccr=ccr_xml, profile_id=self.profile_id) self.assertEqual(created_entry.title.text, subject_line) self.assertEqual(created_entry.content.text, body) self.assertEqual(created_entry.content.type, 'html') problem = created_entry.ccr.GetProblems()[0] problem_desc = problem.FindChildren('Description')[0] name = problem_desc.FindChildren('Text')[0] self.assertEqual(name.text, 'Aortic valve disorders') if __name__ == '__main__': print ('Health API Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder@gmail.com (Jeff Scudder)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata from gdata import test_data import gdata.calendar class CalendarFeedTest(unittest.TestCase): def setUp(self): self.calendar_feed = gdata.calendar.CalendarListFeedFromString( test_data.CALENDAR_FEED) def testEntryCount(self): # Assert the number of items in the feed of calendars self.assertEquals(len(self.calendar_feed.entry),2) def testToAndFromString(self): # Assert the appropriate type for each entry for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry, gdata.calendar.CalendarListEntry), 'Entry must be an instance of CalendarListEntry') # Regenerate feed from xml text new_calendar_feed = ( gdata.calendar.CalendarListFeedFromString(str(self.calendar_feed))) for an_entry in new_calendar_feed.entry: self.assert_(isinstance(an_entry, gdata.calendar.CalendarListEntry), 'Entry in regenerated feed must be an instance of CalendarListEntry') def testAuthor(self): """Tests the existence of a <atom:author> and verifies the name and email""" # Assert that each element in the feed author list is an atom.Author for an_author in self.calendar_feed.author: self.assert_(isinstance(an_author, atom.Author), "Calendar feed <atom:author> element must be an instance of " + "atom.Author: %s" % an_author) # Assert the feed author name is as expected self.assertEquals(self.calendar_feed.author[0].name.text, 'GData Ops Demo') # Assert the feed author name is as expected self.assertEquals(self.calendar_feed.author[0].email.text, 'gdata.ops.demo@gmail.com') # Assert one of the values for an entry author self.assertEquals(self.calendar_feed.entry[0].author[0].name.text, 'GData Ops Demo') self.assertEquals(self.calendar_feed.entry[0].author[0].email.text, 'gdata.ops.demo@gmail.com') def testId(self): """Tests the existence of a <atom:id> in the feed and entries and verifies the value""" # Assert the feed id exists and is an atom.Id self.assert_(isinstance(self.calendar_feed.id, atom.Id), "Calendar feed <atom:id> element must be an instance of atom.Id: %s" % ( self.calendar_feed.id)) # Assert the feed id value is as expected self.assertEquals(self.calendar_feed.id.text, 'http://www.google.com/calendar/feeds/default') # Assert that each entry has an id which is an atom.Id for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.id, atom.Id), "Calendar entry <atom:id> element must be an instance of " + "atom.Id: %s" % an_entry.id) # Assert one of the values for an id self.assertEquals(self.calendar_feed.entry[1].id.text, 'http://www.google.com/calendar/feeds/default/' + 'jnh21ovnjgfph21h32gvms2758%40group.calendar.google.com') def testPublished(self): """Tests the existence of a <atom:published> in the entries and verifies the value""" # Assert that each entry has a published value which is an atom.Published for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.published, atom.Published), "Calendar entry <atom:published> element must be an instance of " + "atom.Published: %s" % an_entry.published) # Assert one of the values for published is as expected self.assertEquals(self.calendar_feed.entry[1].published.text, '2007-03-20T22:48:57.837Z') def testUpdated(self): """Tests the existence of a <atom:updated> in the feed and the entries and verifies the value""" # Assert that the feed updated element exists and is an atom.Updated self.assert_(isinstance(self.calendar_feed.updated, atom.Updated), "Calendar feed <atom:updated> element must be an instance of " + "atom.Updated: %s" % self.calendar_feed.updated) # Assert that each entry has a updated value which is an atom.Updated for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.updated, atom.Updated), "Calendar entry <atom:updated> element must be an instance of" + "atom.Updated: %s" % an_entry.updated) # Assert the feed updated value is as expected self.assertEquals(self.calendar_feed.updated.text, '2007-03-20T22:48:57.833Z') # Assert one of the values for updated self.assertEquals(self.calendar_feed.entry[0].updated.text, '2007-03-20T22:48:52.000Z') def testTitle(self): """Tests the existence of a <atom:title> in the feed and the entries and verifies the value""" # Assert that the feed title element exists and is an atom.Title self.assert_(isinstance(self.calendar_feed.title, atom.Title), "Calendar feed <atom:title> element must be an instance of " + "atom.Title: %s" % self.calendar_feed.title) # Assert that each entry has a title value which is an atom.Title for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.title, atom.Title), "Calendar entry <atom:title> element must be an instance of " + "atom.Title: %s" % an_entry.title) # Assert the feed title value is as expected self.assertEquals(self.calendar_feed.title.text, 'GData Ops Demo\'s Calendar List') # Assert one of the values for title self.assertEquals(self.calendar_feed.entry[0].title.text, 'GData Ops Demo') def testColor(self): """Tests the existence of a <gCal:color> and verifies the value""" # Assert the color is present and is a gdata.calendar.Color for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.color, gdata.calendar.Color), "Calendar feed <gCal:color> element must be an instance of " + "gdata.calendar.Color: %s" % an_entry.color) # Assert the color value is as expected self.assertEquals(self.calendar_feed.entry[0].color.value, '#2952A3') def testAccessLevel(self): """Tests the existence of a <gCal:accesslevel> element and verifies the value""" # Assert the access_level is present and is a gdata.calendar.AccessLevel for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.access_level, gdata.calendar.AccessLevel), "Calendar feed <gCal:accesslevel> element must be an instance of " + "gdata.calendar.AccessLevel: %s" % an_entry.access_level) # Assert the access_level value is as expected self.assertEquals(self.calendar_feed.entry[0].access_level.value, 'owner') def testTimezone(self): """Tests the existence of a <gCal:timezone> element and verifies the value""" # Assert the timezone is present and is a gdata.calendar.Timezone for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.timezone, gdata.calendar.Timezone), "Calendar feed <gCal:timezone> element must be an instance of " + "gdata.calendar.Timezone: %s" % an_entry.timezone) # Assert the timezone value is as expected self.assertEquals(self.calendar_feed.entry[0].timezone.value, 'America/Los_Angeles') def testHidden(self): """Tests the existence of a <gCal:hidden> element and verifies the value""" # Assert the hidden is present and is a gdata.calendar.Hidden for an_entry in self.calendar_feed.entry: self.assert_(isinstance(an_entry.hidden, gdata.calendar.Hidden), "Calendar feed <gCal:hidden> element must be an instance of " + "gdata.calendar.Hidden: %s" % an_entry.hidden) # Assert the hidden value is as expected self.assertEquals(self.calendar_feed.entry[0].hidden.value, 'false') def testOpenSearch(self): """Tests the existence of <openSearch:startIndex>""" # Assert that the elements exist and are the appropriate type self.assert_(isinstance(self.calendar_feed.start_index, gdata.StartIndex), "Calendar feed <openSearch:startIndex> element must be an " + "instance of gdata.StartIndex: %s" % self.calendar_feed.start_index) # Assert the values for each openSearch element are as expected self.assertEquals(self.calendar_feed.start_index.text, '1') def testGenerator(self): """Tests the existence of <atom:generator> and verifies the value""" # Assert that the element exists and is of the appropriate type self.assert_(isinstance(self.calendar_feed.generator, atom.Generator), "Calendar feed <atom:generator> element must be an instance of " + "atom.Generator: %s" % self.calendar_feed.generator) # Assert the generator version, uri and text are as expected self.assertEquals(self.calendar_feed.generator.text, 'Google Calendar') self.assertEquals(self.calendar_feed.generator.version, '1.0') self.assertEquals(self.calendar_feed.generator.uri, 'http://www.google.com/calendar') def testEntryLink(self): """Makes sure entry links in the private composite feed are parsed.""" entry = gdata.calendar.CalendarEventEntryFromString( test_data.RECURRENCE_EXCEPTION_ENTRY) self.assert_(isinstance(entry.recurrence_exception, list)) self.assert_(isinstance(entry.recurrence_exception[0].entry_link, gdata.EntryLink)) self.assert_(isinstance(entry.recurrence_exception[0].entry_link.entry, gdata.calendar.CalendarEventEntry)) self.assertEquals( entry.recurrence_exception[0].entry_link.entry.author[0].name.text, 'gdata ops') def testSequence(self): entry = gdata.calendar.CalendarEventEntry( sequence=gdata.calendar.Sequence(value='1')) entry2 = gdata.calendar.CalendarEventEntryFromString(str(entry)) self.assertEqual(entry.sequence.value, entry2.sequence.value) entry = gdata.calendar.CalendarEventEntryFromString( '<entry xmlns="%s"><sequence xmlns="%s" value="7" /></entry>' % ( atom.ATOM_NAMESPACE, gdata.calendar.GCAL_NAMESPACE)) self.assertEqual(entry.sequence.value, '7') def testOriginalEntry(self): """Make sure original entry in the private composite feed are parsed.""" entry = gdata.calendar.CalendarEventEntryFromString( test_data.RECURRENCE_EXCEPTION_ENTRY) self.assertEquals( entry.recurrence_exception[0].entry_link.entry.original_event.id, 'i7lgfj69mjqjgnodklif3vbm7g') class CalendarFeedTestRegenerated(CalendarFeedTest): def setUp(self): old_calendar_feed = ( gdata.calendar.CalendarListFeedFromString(test_data.CALENDAR_FEED)) self.calendar_feed = ( gdata.calendar.CalendarListFeedFromString(str(old_calendar_feed))) tree = ElementTree.fromstring(str(old_calendar_feed)) class CalendarEventFeedTest(unittest.TestCase): def setUp(self): self.calendar_event_feed = ( gdata.calendar.CalendarEventFeedFromString( test_data.CALENDAR_FULL_EVENT_FEED)) def testEntryCount(self): # Assert the number of items in the feed of events self.assertEquals(len(self.calendar_event_feed.entry),11) def testToAndFromString(self): # Assert the appropriate type for each entry for an_entry in self.calendar_event_feed.entry: self.assert_(isinstance(an_entry, gdata.calendar.CalendarEventEntry), "Entry must be an instance of a CalendarEventEntry") # Regenerate feed from xml text new_calendar_event_feed = gdata.calendar.CalendarEventFeedFromString( str(self.calendar_event_feed)) for an_entry in new_calendar_event_feed.entry: self.assert_(isinstance(an_entry, gdata.calendar.CalendarEventEntry), "Entry in regenerated feed must be an instance of CalendarEventEntry") def testAuthor(self): """Tests the existence of a <atom:author> and verifies the name and email""" # Assert that each element in the feed author list is an atom.Author for an_author in self.calendar_event_feed.author: self.assert_(isinstance(an_author, atom.Author), "Calendar event feed <atom:author> element must be an instance of " + "atom.Author: %s" % an_author) # Assert the feed author name is as expected self.assertEquals(self.calendar_event_feed.author[0].name.text, 'GData Ops Demo') # Assert the feed author name is as expected self.assertEquals(self.calendar_event_feed.author[0].email.text, 'gdata.ops.demo@gmail.com') # Assert one of the values for an entry author self.assertEquals(self.calendar_event_feed.entry[0].author[0].name.text, 'GData Ops Demo') self.assertEquals(self.calendar_event_feed.entry[0].author[0].email.text, 'gdata.ops.demo@gmail.com') def testId(self): """Tests the existence of a <atom:id> in the feed and entries and verifies the value""" # Assert the feed id exists and is an atom.Id self.assert_(isinstance(self.calendar_event_feed.id, atom.Id), "Calendar event feed <atom:id> element must be an instance of " + "atom.Id: %s" % self.calendar_event_feed.id) # Assert the feed id value is as expected self.assertEquals(self.calendar_event_feed.id.text, 'http://www.google.com/calendar/feeds/default/private/full') # Assert that each entry has an id which is an atom.Id for an_entry in self.calendar_event_feed.entry: self.assert_(isinstance(an_entry.id, atom.Id), "Calendar event entry <atom:id> element must be an " + "instance of atom.Id: %s" % an_entry.id) # Assert one of the values for an id self.assertEquals(self.calendar_event_feed.entry[1].id.text, 'http://www.google.com/calendar/feeds/default/private/full/' + '2qt3ao5hbaq7m9igr5ak9esjo0') def testPublished(self): """Tests the existence of a <atom:published> in the entries and verifies the value""" # Assert that each entry has a published value which is an atom.Published for an_entry in self.calendar_event_feed.entry: self.assert_(isinstance(an_entry.published, atom.Published), "Calendar event entry <atom:published> element must be an instance " + "of atom.Published: %s" % an_entry.published) # Assert one of the values for published is as expected self.assertEquals(self.calendar_event_feed.entry[1].published.text, '2007-03-20T21:26:04.000Z') def testUpdated(self): """Tests the existence of a <atom:updated> in the feed and the entries and verifies the value""" # Assert that the feed updated element exists and is an atom.Updated self.assert_(isinstance(self.calendar_event_feed.updated, atom.Updated), "Calendar feed <atom:updated> element must be an instance of " + "atom.Updated: %s" % self.calendar_event_feed.updated) # Assert that each entry has a updated value which is an atom.Updated for an_entry in self.calendar_event_feed.entry: self.assert_(isinstance(an_entry.updated, atom.Updated), "Calendar event entry <atom:updated> element must be an instance " + "of atom.Updated: %s" % an_entry.updated) # Assert the feed updated value is as expected self.assertEquals(self.calendar_event_feed.updated.text, '2007-03-20T21:29:57.000Z') # Assert one of the values for updated self.assertEquals(self.calendar_event_feed.entry[3].updated.text, '2007-03-20T21:25:46.000Z') def testTitle(self): """Tests the existence of a <atom:title> in the feed and the entries and verifies the value""" # Assert that the feed title element exists and is an atom.Title self.assert_(isinstance(self.calendar_event_feed.title, atom.Title), "Calendar feed <atom:title> element must be an instance of " + "atom.Title: %s" % self.calendar_event_feed.title) # Assert that each entry has a title value which is an atom.Title for an_entry in self.calendar_event_feed.entry: self.assert_(isinstance(an_entry.title, atom.Title), "Calendar event entry <atom:title> element must be an instance of " + "atom.Title: %s" % an_entry.title) # Assert the feed title value is as expected self.assertEquals(self.calendar_event_feed.title.text, 'GData Ops Demo') # Assert one of the values for title self.assertEquals(self.calendar_event_feed.entry[0].title.text, 'test deleted') def testPostLink(self): """Tests the existence of a <atom:link> with a rel='...#post' and verifies the value""" # Assert that each link in the feed is an atom.Link for a_link in self.calendar_event_feed.link: self.assert_(isinstance(a_link, atom.Link), "Calendar event entry <atom:link> element must be an instance of " + "atom.Link: %s" % a_link) # Assert post link exists self.assert_(self.calendar_event_feed.GetPostLink() is not None) # Assert the post link value is as expected self.assertEquals(self.calendar_event_feed.GetPostLink().href, 'http://www.google.com/calendar/feeds/default/private/full') def testEditLink(self): """Tests the existence of a <atom:link> with a rel='edit' in each entry and verifies the value""" # Assert that each link in the feed is an atom.Link for a_link in self.calendar_event_feed.link: self.assert_(isinstance(a_link, atom.Link), "Calendar event entry <atom:link> element must be an instance of " + "atom.Link: %s" % a_link) # Assert edit link exists for a_entry in self.calendar_event_feed.entry: self.assert_(a_entry.GetEditLink() is not None) # Assert the edit link value is as expected self.assertEquals(self.calendar_event_feed.entry[0].GetEditLink().href, 'http://www.google.com/calendar/feeds/default/private/full/o99flmgm' + 'kfkfrr8u745ghr3100/63310109397') self.assertEquals(self.calendar_event_feed.entry[0].GetEditLink().type, 'application/atom+xml') def testOpenSearch(self): """Tests the existence of <openSearch:totalResults>, <openSearch:startIndex>, <openSearch:itemsPerPage>""" # Assert that the elements exist and are the appropriate type self.assert_(isinstance(self.calendar_event_feed.total_results, gdata.TotalResults), "Calendar event feed <openSearch:totalResults> element must be an " + "instance of gdata.TotalResults: %s" % ( self.calendar_event_feed.total_results)) self.assert_( isinstance(self.calendar_event_feed.start_index, gdata.StartIndex), "Calendar event feed <openSearch:startIndex> element must be an " + "instance of gdata.StartIndex: %s" % ( self.calendar_event_feed.start_index)) self.assert_( isinstance(self.calendar_event_feed.items_per_page, gdata.ItemsPerPage), "Calendar event feed <openSearch:itemsPerPage> element must be an " + "instance of gdata.ItemsPerPage: %s" % ( self.calendar_event_feed.items_per_page)) # Assert the values for each openSearch element are as expected self.assertEquals(self.calendar_event_feed.total_results.text, '10') self.assertEquals(self.calendar_event_feed.start_index.text, '1') self.assertEquals(self.calendar_event_feed.items_per_page.text, '25') def testGenerator(self): """Tests the existence of <atom:generator> and verifies the value""" # Assert that the element exists and is of the appropriate type self.assert_(isinstance(self.calendar_event_feed.generator, atom.Generator), "Calendar event feed <atom:generator> element must be an instance " + "of atom.Generator: %s" % self.calendar_event_feed.generator) # Assert the generator version, uri and text are as expected self.assertEquals(self.calendar_event_feed.generator.text, 'Google Calendar') self.assertEquals(self.calendar_event_feed.generator.version, '1.0') self.assertEquals(self.calendar_event_feed.generator.uri, 'http://www.google.com/calendar') def testCategory(self): """Tests the existence of <atom:category> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for a_category in self.calendar_event_feed.category: self.assert_(isinstance(a_category, atom.Category), "Calendar event feed <atom:category> element must be an instance " + "of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(a_category.term, 'http://schemas.google.com/g/2005#event') for an_event in self.calendar_event_feed.entry: for a_category in an_event.category: self.assert_(isinstance(a_category, atom.Category), "Calendar event feed entry <atom:category> element must be an " + "instance of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(a_category.term, 'http://schemas.google.com/g/2005#event') def testSendEventNotifications(self): """Test the existence of <gCal:sendEventNotifications> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for an_event in self.calendar_event_feed.entry: self.assert_(isinstance(an_event.send_event_notifications, gdata.calendar.SendEventNotifications), ("Calendar event feed entry <gCal:sendEventNotifications> element " + "must be an instance of gdata.calendar.SendEventNotifications: %s") % ( an_event.send_event_notifications,)) # Assert the <gCal:sendEventNotifications> are as expected self.assertEquals( self.calendar_event_feed.entry[0].send_event_notifications.value, 'false') self.assertEquals( self.calendar_event_feed.entry[2].send_event_notifications.value, 'true') def testQuickAdd(self): """Test the existence of <gCal:quickadd> and verifies the value""" entry = gdata.calendar.CalendarEventEntry() entry.quick_add = gdata.calendar.QuickAdd(value='true') unmarshalled_entry = entry.ToString() tag = '{%s}quickadd' % (gdata.calendar.GCAL_NAMESPACE) marshalled_entry = ElementTree.fromstring(unmarshalled_entry).find(tag) self.assert_(marshalled_entry.attrib['value'],'true') self.assert_(marshalled_entry.tag,tag) def testEventStatus(self): """Test the existence of <gd:eventStatus> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for an_event in self.calendar_event_feed.entry: self.assert_(isinstance(an_event.event_status, gdata.calendar.EventStatus), ("Calendar event feed entry <gd:eventStatus> element " + "must be an instance of gdata.calendar.EventStatus: %s") % ( an_event.event_status,)) # Assert the <gd:eventStatus> are as expected self.assertEquals( self.calendar_event_feed.entry[0].event_status.value, 'CANCELED') self.assertEquals( self.calendar_event_feed.entry[1].event_status.value, 'CONFIRMED') def testComments(self): """Tests the existence of <atom:comments> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for an_event in self.calendar_event_feed.entry: self.assert_(an_event.comments is None or isinstance(an_event.comments, gdata.calendar.Comments), ("Calendar event feed entry <gd:comments> element " + "must be an instance of gdata.calendar.Comments: %s") % ( an_event.comments,)) def testVisibility(self): """Test the existence of <gd:visibility> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for an_event in self.calendar_event_feed.entry: self.assert_(isinstance(an_event.visibility, gdata.calendar.Visibility), ("Calendar event feed entry <gd:visibility> element " + "must be an instance of gdata.calendar.Visibility: %s") % ( an_event.visibility,)) # Assert the <gd:visibility> are as expected self.assertEquals( self.calendar_event_feed.entry[0].visibility.value, 'DEFAULT') self.assertEquals( self.calendar_event_feed.entry[1].visibility.value, 'PRIVATE') self.assertEquals( self.calendar_event_feed.entry[2].visibility.value, 'PUBLIC') def testTransparency(self): """Test the existence of <gd:transparency> and verifies the value""" # Assert that the element exists and is of the appropriate type and value for an_event in self.calendar_event_feed.entry: self.assert_(isinstance(an_event.transparency, gdata.calendar.Transparency), ("Calendar event feed entry <gd:transparency> element " + "must be an instance of gdata.calendar.Transparency: %s") % ( an_event.transparency,)) # Assert the <gd:transparency> are as expected self.assertEquals( self.calendar_event_feed.entry[0].transparency.value, 'OPAQUE') self.assertEquals( self.calendar_event_feed.entry[1].transparency.value, 'OPAQUE') self.assertEquals( self.calendar_event_feed.entry[2].transparency.value, 'OPAQUE') # TODO: TEST VALUES OF VISIBILITY OTHER THAN OPAQUE def testWhere(self): """Tests the existence of a <gd:where> in the entries and verifies the value""" # Assert that each entry has a where value which is an gdata.calendar.Where for an_entry in self.calendar_event_feed.entry: for a_where in an_entry.where: self.assert_(isinstance(a_where, gdata.calendar.Where), "Calendar event entry <gd:where> element must be an instance of " + "gdata.calendar.Where: %s" % a_where) # Assert one of the values for where is as expected self.assertEquals(self.calendar_event_feed.entry[1].where[0].value_string, 'Dolores Park with Kim') def testWhenAndReminder(self): """Tests the existence of a <gd:when> and <gd:reminder> in the entries and verifies the values""" # Assert that each entry's when value is a gdata.calendar.When # Assert that each reminder is a gdata.calendar.Reminder for an_entry in self.calendar_event_feed.entry: for a_when in an_entry.when: self.assert_(isinstance(a_when, gdata.calendar.When), "Calendar event entry <gd:when> element must be an instance " + "of gdata.calendar.When: %s" % a_when) for a_reminder in a_when.reminder: self.assert_(isinstance(a_reminder, gdata.calendar.Reminder), "Calendar event entry <gd:reminder> element must be an " + "instance of gdata.calendar.Reminder: %s" % a_reminder) # Assert one of the values for when is as expected self.assertEquals(self.calendar_event_feed.entry[0].when[0].start_time, '2007-03-23T12:00:00.000-07:00') self.assertEquals(self.calendar_event_feed.entry[0].when[0].end_time, '2007-03-23T13:00:00.000-07:00') # Assert the reminder child of when is as expected self.assertEquals( self.calendar_event_feed.entry[0].when[0].reminder[0].minutes, '10') self.assertEquals( self.calendar_event_feed.entry[1].when[0].reminder[0].minutes, '20') def testBatchRequestParsing(self): batch_request = gdata.calendar.CalendarEventFeedFromString( test_data.CALENDAR_BATCH_REQUEST) self.assertEquals(len(batch_request.entry), 4) # Iterate over the batch request entries and match the operation with # the batch id. These values are hard coded to match the test data. for entry in batch_request.entry: if entry.batch_id.text == '1': self.assertEquals(entry.batch_operation.type, 'insert') if entry.batch_id.text == '2': self.assertEquals(entry.batch_operation.type, 'query') if entry.batch_id.text == '3': self.assertEquals(entry.batch_operation.type, 'update') self.assertEquals(entry.title.text, 'Event updated via batch') if entry.batch_id.text == '4': self.assertEquals(entry.batch_operation.type, 'delete') self.assertEquals(entry.id.text, 'http://www.google.com/calendar/feeds/default/' 'private/full/d8qbg9egk1n6lhsgq1sjbqffqc') self.assertEquals(entry.GetEditLink().href, 'http://www.google.com/calendar/feeds/default/' 'private/full/d8qbg9egk1n6lhsgq1sjbqffqc/' '63326018324') def testBatchResponseParsing(self): batch_response = gdata.calendar.CalendarEventFeedFromString( test_data.CALENDAR_BATCH_RESPONSE) self.assertEquals(len(batch_response.entry), 4) for entry in batch_response.entry: if entry.batch_id.text == '1': self.assertEquals(entry.batch_operation.type, 'insert') self.assertEquals(entry.batch_status.code, '201') self.assertEquals(entry.batch_status.reason, 'Created') self.assertEquals(entry.id.text, 'http://www.google.com/calendar/' 'feeds/default/private/full/' 'n9ug78gd9tv53ppn4hdjvk68ek') if entry.batch_id.text == '2': self.assertEquals(entry.batch_operation.type, 'query') if entry.batch_id.text == '3': self.assertEquals(entry.batch_operation.type, 'update') if entry.batch_id.text == '4': self.assertEquals(entry.batch_operation.type, 'delete') self.assertEquals(entry.id.text, 'http://www.google.com/calendar/' 'feeds/default/private/full/' 'd8qbg9egk1n6lhsgq1sjbqffqc') # TODO add reminder tests for absolute_time and hours/seconds (if possible) # TODO test recurrence and recurrenceexception # TODO test originalEvent class CalendarWebContentTest(unittest.TestCase): def setUp(self): self.calendar_event_feed = ( gdata.calendar.CalendarEventFeedFromString( test_data.CALENDAR_FULL_EVENT_FEED)) def testAddSimpleWebContentEventEntry(self): """Verifies that we can add a web content link to an event entry.""" title = "Al Einstein's Birthday!" href = 'http://gdata.ops.demo.googlepages.com/birthdayicon.gif' type = 'image/jpeg' url = 'http://gdata.ops.demo.googlepages.com/einstein.jpg' width = '300' height = '225' # Create a web content event event = gdata.calendar.CalendarEventEntry() web_content = gdata.calendar.WebContent(url=url, width=width, height=height) web_content_link = gdata.calendar.WebContentLink(title=title, href=href, link_type=type, web_content=web_content) event.link.append(web_content_link) # Verify the web content link exists and contains the expected data web_content_link = event.GetWebContentLink() self.assertValidWebContentLink(title, href, type, web_content_link) # Verify the web content element exists and contains the expected data web_content_element = web_content_link.web_content self.assertValidSimpleWebContent(url, width, height, web_content_element) def testAddWebContentGadgetEventEntry(self): """Verifies that we can add a web content gadget link to an event entry.""" title = "Date and Time Gadget" href = 'http://gdata.ops.demo.googlepages.com/birthdayicon.gif' url = 'http://google.com/ig/modules/datetime.xml' type = 'application/x-google-gadgets+xml' width = '300' height = '200' pref_name = 'color' pref_value = 'green' # Create a web content event event = gdata.calendar.CalendarEventEntry() web_content = gdata.calendar.WebContent(url=url, width=width, height=height) web_content.gadget_pref.append( gdata.calendar.WebContentGadgetPref(name=pref_name, value=pref_value)) web_content_link = gdata.calendar.WebContentLink(title=title, href=href, web_content=web_content, link_type=type) event.link.append(web_content_link) # Verify the web content link exists and contains the expected data web_content_link = event.GetWebContentLink() self.assertValidWebContentLink(title, href, type, web_content_link) # Verify the web content element exists and contains the expected data web_content_element = web_content_link.web_content self.assertValidWebContentGadget(url, width, height, pref_name, pref_value, web_content_element) def testFromXmlToSimpleWebContent(self): """Verifies that we can read a web content link from an event entry.""" # Expected values (from test_data.py file) title = 'World Cup' href = 'http://www.google.com/calendar/images/google-holiday.gif' type = 'image/gif' url = 'http://www.google.com/logos/worldcup06.gif' width = '276' height = '120' # Note: The tenth event entry contains web content web_content_event = self.calendar_event_feed.entry[9] # Verify the web content link exists and contains the expected data web_content_link = web_content_event.GetWebContentLink() self.assertValidWebContentLink(title, href, type, web_content_link) # Verify the web content element exists and contains the expected data web_content_element = web_content_link.web_content self.assertValidSimpleWebContent(url, width, height, web_content_element) def testFromXmlToWebContentGadget(self): """Verifies that we can read a web content link from an event entry.""" # Expected values (from test_data.py file) title = 'Date and Time Gadget' href = 'http://gdata.ops.demo.googlepages.com/birthdayicon.gif' url = 'http://google.com/ig/modules/datetime.xml' type = 'application/x-google-gadgets+xml' width = '300' height = '136' pref_name = 'color' pref_value = 'green' # Note: The eleventh event entry contains web content web_content_event = self.calendar_event_feed.entry[10] # Verify the web content link exists and contains the expected data web_content_link = web_content_event.GetWebContentLink() self.assertValidWebContentLink(title, href, type, web_content_link) # Verify the web content element exists and contains the expected data web_content_element = web_content_link.web_content self.assertValidWebContentGadget(url, width, height, pref_name, pref_value, web_content_element) def assertValidWebContentLink(self, expected_title=None, expected_href=None, expected_type=None, web_content_link=None): """Asserts that the web content link is the correct type and contains the expected values""" self.assert_(isinstance(web_content_link, gdata.calendar.WebContentLink), "Web content link element must be an " + "instance of gdata.calendar.WebContentLink: %s" % web_content_link) expected_rel = '%s/%s' % (gdata.calendar.GCAL_NAMESPACE, 'webContent') self.assertEquals(expected_rel, web_content_link.rel) self.assertEqual(expected_title, web_content_link.title) self.assertEqual(expected_href, web_content_link.href) self.assertEqual(expected_type, web_content_link.type) def assertValidSimpleWebContent(self, expected_url=None, expected_width=None, expected_height=None, web_content_element=None): """Asserts that the web content element is the correct type and contains the expected values""" self.assert_(isinstance(web_content_element, gdata.calendar.WebContent), "Calendar event entry <gCal:webContent> element must be an " + "instance of gdata.calendar.WebContent: %s" % web_content_element) self.assertEquals(expected_width, web_content_element.width) self.assertEquals(expected_height, web_content_element.height) self.assertEquals(expected_url, web_content_element.url) def assertValidWebContentGadget(self, expected_url=None, expected_width=None, expected_height=None, expected_pref_name=None, expected_pref_value=None, web_content_element=None): """Asserts that the web content element is the correct type and contains the expected values""" self.assert_(isinstance(web_content_element, gdata.calendar.WebContent), "Calendar event entry <gCal:webContent> element must be an " + "instance of gdata.calendar.WebContent: %s" % web_content_element) self.assertEquals(expected_width, web_content_element.width) self.assertEquals(expected_height, web_content_element.height) self.assertEquals(expected_url, web_content_element.url) self.assertEquals(expected_pref_name, web_content_element.gadget_pref[0].name) self.assertEquals(expected_pref_value, web_content_element.gadget_pref[0].value) def testSampleCode(self): # From http://code.google.com/apis/calendar/gadgets/event/ wc = gdata.calendar.WebContent() wc.url = 'http://www.thefreedictionary.com/_/WoD/wod-module.xml' wc.width = '300' wc.height = '136' wc.gadget_pref.append(gdata.calendar.WebContentGadgetPref(name='Days', value='1')) wc.gadget_pref.append(gdata.calendar.WebContentGadgetPref(name='Format', value='0')) wcl = gdata.calendar.WebContentLink() wcl.title = 'Word of the Day' wcl.href = 'http://www.thefreedictionary.com/favicon.ico' wcl.type = 'application/x-google-gadgets+xml' wcl.web_content = wc self.assertEqual(wcl.web_content.url, 'http://www.thefreedictionary.com/_/WoD/wod-module.xml') self.assertEqual(wcl.type, 'application/x-google-gadgets+xml') self.assertEqual(wcl.web_content.height, '136') class ExtendedPropertyTest(unittest.TestCase): def testExtendedPropertyToAndFromXml(self): ep = gdata.calendar.ExtendedProperty(name='test') ep.value = 'val' xml_string = ep.ToString() ep2 = gdata.ExtendedPropertyFromString(xml_string) self.assertEquals(ep.name, ep2.name) self.assertEquals(ep.value, ep2.value) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'jlapenna@google.com (Joe LaPenna)' import unittest from gdata import test_data import gdata.projecthosting.data import atom.core import gdata.test_config as conf ISSUE_ENTRY = """\ <entry xmlns='http://www.w3.org/2005/Atom' xmlns:issues='http://schemas.google.com/projecthosting/issues/2009'> <id>http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/1</id> <updated>2009-09-09T20:34:35.365Z</updated> <title>This is updated issue summary</title> <content type='html'>This is issue description</content> <link rel='self' type='application/atom+xml' href='http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/3'/> <link rel='edit' type='application/atom+xml' href='http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/3'/> <author> <name>elizabeth.bennet</name> <uri>/u/elizabeth.bennet/</uri> </author> <issues:cc> <issues:uri>/u/@UBhTQl1UARRAVga7/</issues:uri> <issues:username>mar...@domain.com</issues:username> </issues:cc> <issues:cc> <issues:uri>/u/fitzwilliam.darcy/</issues:uri> <issues:username>fitzwilliam.darcy</issues:username> </issues:cc> <issues:label>Type-Enhancement</issues:label> <issues:label>Priority-Low</issues:label> <issues:owner> <issues:uri>/u/charlotte.lucas/</issues:uri> <issues:username>charlotte.lucas</issues:username> </issues:owner> <issues:stars>0</issues:stars> <issues:state>open</issues:state> <issues:status>Started</issues:status> </entry> """ ISSUES_FEED = """\ <?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom'> <id>http://code.google.com/feeds/issues/p/android-test2/issues/full</id> <link href="http://code.google.com/feeds/issues/p/android-test2/issues/full" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" /> <link href="http://code.google.com/feeds/issues/p/android-test2/issues/full" rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" /> <link href="http://code.google.com/feeds/issues/p/android-test2/issues/full" rel="self" type="application/atom+xml" /> <updated>2009-09-22T04:06:32.794Z</updated> %s </feed> """ % ISSUE_ENTRY COMMENT_ENTRY = """\ <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:issues='http://schemas.google.com/projecthosting/issues/2009'> <content type='html'>This is comment - update issue</content> <author> <name>elizabeth.bennet</name> </author> <issues:updates> <issues:summary>This is updated issue summary</issues:summary> <issues:status>Started</issues:status> <issues:ownerUpdate>charlotte.lucas</issues:ownerUpdate> <issues:label>-Type-Defect</issues:label> <issues:label>Type-Enhancement</issues:label> <issues:label>-Milestone-2009</issues:label> <issues:label>-Priority-Medium</issues:label> <issues:label>Priority-Low</issues:label> <issues:ccUpdate>-fitzwilliam.darcy</issues:ccUpdate> <issues:ccUpdate>marialucas@domain.com</issues:ccUpdate> </issues:updates> </entry> """ class CommentEntryTest(unittest.TestCase): def testParsing(self): entry = atom.core.parse(COMMENT_ENTRY, gdata.projecthosting.data.CommentEntry) updates = entry.updates self.assertEquals(updates.summary.text, 'This is updated issue summary') self.assertEquals(updates.status.text, 'Started') self.assertEquals(updates.ownerUpdate.text, 'charlotte.lucas') self.assertEquals(len(updates.label), 5) self.assertEquals(updates.label[0].text, '-Type-Defect') self.assertEquals(updates.label[1].text, 'Type-Enhancement') self.assertEquals(updates.label[2].text, '-Milestone-2009') self.assertEquals(updates.label[3].text, '-Priority-Medium') self.assertEquals(updates.label[4].text, 'Priority-Low') self.assertEquals(len(updates.ccUpdate), 2) self.assertEquals(updates.ccUpdate[0].text, '-fitzwilliam.darcy') self.assertEquals(updates.ccUpdate[1].text, 'marialucas@domain.com') class IssueEntryTest(unittest.TestCase): def testParsing(self): entry = atom.core.parse(ISSUE_ENTRY, gdata.projecthosting.data.IssueEntry) self.assertEquals(entry.owner.uri.text, '/u/charlotte.lucas/') self.assertEqual(entry.owner.username.text, 'charlotte.lucas') self.assertEquals(len(entry.cc), 2) cc_0 = entry.cc[0] self.assertEquals(cc_0.uri.text, '/u/@UBhTQl1UARRAVga7/') self.assertEquals(cc_0.username.text, 'mar...@domain.com') cc_1 = entry.cc[1] self.assertEquals(cc_1.uri.text, '/u/fitzwilliam.darcy/') self.assertEquals(cc_1.username.text, 'fitzwilliam.darcy') self.assertEquals(len(entry.label), 2) self.assertEquals(entry.label[0].text, 'Type-Enhancement') self.assertEquals(entry.label[1].text, 'Priority-Low') self.assertEquals(entry.stars.text, '0') self.assertEquals(entry.state.text, 'open') self.assertEquals(entry.status.text, 'Started') class DataClassSanityTest(unittest.TestCase): def test_basic_element_structure(self): conf.check_data_classes(self, [ gdata.projecthosting.data.Uri, gdata.projecthosting.data.Username, gdata.projecthosting.data.Cc, gdata.projecthosting.data.Label, gdata.projecthosting.data.Owner, gdata.projecthosting.data.Stars, gdata.projecthosting.data.State, gdata.projecthosting.data.Status, gdata.projecthosting.data.Summary, gdata.projecthosting.data.Updates, gdata.projecthosting.data.IssueEntry, gdata.projecthosting.data.IssuesFeed, gdata.projecthosting.data.CommentEntry, gdata.projecthosting.data.CommentsFeed]) def suite(): return conf.build_suite([IssueEntryTest, DataClassSanityTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'jlapenna@google.com (Joe LaPenna)' import unittest import gdata.projecthosting.client import gdata.projecthosting.data import gdata.gauth import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data import gdata.test_config as conf conf.options.register_option(conf.PROJECT_NAME_OPTION) conf.options.register_option(conf.ISSUE_ASSIGNEE_OPTION) class ProjectHostingClientTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.projecthosting.client.ProjectHostingClient() conf.configure_client(self.client, 'ProjectHostingClientTest', 'code') self.project_name = conf.options.get_value('project_name') self.assignee = conf.options.get_value('issue_assignee') self.owner = conf.options.get_value('username') def tearDown(self): conf.close_client(self.client) def create_issue(self): # Add an issue created = self.client.add_issue( self.project_name, 'my title', 'my summary', self.owner, labels=['label0']) self.assertEqual(created.title.text, 'my title') self.assertEqual(created.content.text, 'my summary') self.assertEqual(len(created.label), 1) self.assertEqual(created.label[0].text, 'label0') return created def test_create_update_close(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') # Create the issue: created = self.create_issue() # Change the issue we just added. issue_id = created.id.text.split('/')[-1] update_response = self.client.update_issue( self.project_name, issue_id, self.owner, comment='My comment here.', summary='New Summary', status='Accepted', owner=self.assignee, labels=['-label0', 'label1'], ccs=[self.owner]) updates = update_response.updates # Make sure it changed our status, summary, and added the comment. self.assertEqual(update_response.content.text, 'My comment here.') self.assertEqual(updates.summary.text, 'New Summary') self.assertEqual(updates.status.text, 'Accepted') # Make sure it got all our label change requests. self.assertEquals(len(updates.label), 2) self.assertEquals(updates.label[0].text, '-label0') self.assertEquals(updates.label[1].text, 'label1') # Be sure it saw our CC change. We can't check the specific values (yet) # because ccUpdate and ownerUpdate responses are mungled. self.assertEquals(len(updates.ccUpdate), 1) self.assert_(updates.ownerUpdate.text) def test_get_issues(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') # Create an issue so we have something to look up. created = self.create_issue() # The fully qualified id is a url, we just want the number. issue_id = created.id.text.split('/')[-1] # Get the specific issue in our issues feed. You could use label, # canned_query and others just the same. query = gdata.projecthosting.client.Query(label='label0') feed = self.client.get_issues(self.project_name, query=query) # Make sure we at least find the entry we created with that label. self.assert_(len(feed.entry) > 0) for issue in feed.entry: label_texts = [label.text for label in issue.label] self.assert_('label0' in label_texts, 'Issue does not have label label0') def test_get_comments(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') # Create an issue so we have something to look up. created = self.create_issue() # The fully qualified id is a url, we just want the number. issue_id = created.id.text.split('/')[-1] # Now lets add two comments to that issue. for i in range(2): update_response = self.client.update_issue( self.project_name, issue_id, self.owner, comment='My comment here %s' % i) # We have an issue that has several comments. Lets get them. comments_feed = self.client.get_comments(self.project_name, issue_id) # It has 2 comments. self.assertEqual(2, len(comments_feed.entry)) class ProjectHostingDocExamplesTest(unittest.TestCase): def setUp(self): self.project_name = conf.options.get_value('project_name') self.assignee = conf.options.get_value('issue_assignee') self.owner = conf.options.get_value('username') self.password = conf.options.get_value('password') def test_doc_examples(self): if not conf.options.get_value('runlive') == 'true': return issues_client = gdata.projecthosting.client.ProjectHostingClient() self.authenticating_client(issues_client, self.owner, self.password) issue = self.creating_issues(issues_client, self.project_name, self.owner) issue_id = issue.id.text.split('/')[-1] self.retrieving_all_issues(issues_client, self.project_name) self.retrieving_issues_using_query_parameters( issues_client, self.project_name) self.modifying_an_issue_or_creating_issue_comments( issues_client, self.project_name, issue_id, self.owner, self.assignee) self.retrieving_issues_comments_for_an_issue( issues_client, self.project_name, issue_id) def authenticating_client(self, client, username, password): return client.client_login( username, password, source='your-client-name', service='code') def creating_issues(self, client, project_name, owner): """Create an issue.""" return client.add_issue( project_name, 'my title', 'my summary', owner, labels=['label0']) def retrieving_all_issues(self, client, project_name): """Retrieve all the issues in a project.""" feed = client.get_issues(project_name) for issue in feed.entry: self.assert_(issue.title.text is not None) def retrieving_issues_using_query_parameters(self, client, project_name): """Retrieve a set of issues in a project.""" query = gdata.projecthosting.client.Query(label='label0', max_results=1000) feed = client.get_issues(project_name, query=query) for issue in feed.entry: self.assert_(issue.title.text is not None) return feed def retrieving_issues_comments_for_an_issue(self, client, project_name, issue_id): """Retrieve all issue comments for an issue.""" comments_feed = client.get_comments(project_name, issue_id) for comment in comments_feed.entry: self.assert_(comment.content is not None) return comments_feed def modifying_an_issue_or_creating_issue_comments(self, client, project_name, issue_id, owner, assignee): """Add a comment and update metadata in an issue.""" return client.update_issue( project_name, issue_id, owner, comment='My comment here.', summary='New Summary', status='Accepted', owner=assignee, labels=['-label0', 'label1'], ccs=[owner]) def suite(): return conf.build_suite([ProjectHostingClientTest, ProjectHostingDocExamplesTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.core import gdata.test_config as conf PLAYLIST_EXAMPLE = ( '{"apiVersion": "2.0","data": {"totalResults": 347,"startIndex": 1,"it' 'emsPerPage": 2,"items": [{"id": "4DAEFAF23BB3CDD0","created": "2008-1' '2-09T20:23:06.000Z","updated": "2010-01-04T02:56:19.000Z","author": "' 'GoogleDevelopers","title": "Google Web Toolkit Developers","descripti' 'on": "Developers talk about using Google Web Toolkit ...","tags": ["g' 'oogle","web","toolkit","developers","gwt"],"size": 12},{"id": "586D32' '2B5E2764CF","created": "2007-11-13T19:41:21.000Z","updated": "2010-01' '-04T17:41:16.000Z","author": "GoogleDevelopers","title": "Android","d' 'escription": "Demos and tutorials about the new Android platform.","t' 'ags": ["android","google","developers","mobile"],"size": 32}]}}') VIDEO_EXAMPLE = ( '{"apiVersion": "2.0","data": {"updated": "2010-01-07T19:58:42.949Z","' 'totalItems": 800,"startIndex": 1,"itemsPerPage": 1, "items": [{"id": ' '"hYB0mn5zh2c","uploaded": "2007-06-05T22:07:03.000Z","updated": "2010' '-01-07T13:26:50.000Z","uploader": "GoogleDeveloperDay","category": "N' 'ews","title": "Google Developers Day US - Maps API Introduction","des' 'cription": "Google Maps API Introduction ...","tags": ["GDD07","GDD07' 'US","Maps"],"thumbnail": {"default": "http://i.ytimg.com/vi/hYB0mn5zh' '2c/default.jpg","hqDefault": "http://i.ytimg.com/vi/hYB0mn5zh2c/hqdef' 'ault.jpg"},"player": {"default": "http://www.youtube.com/watch?v' '\u003dhYB0mn5zh2c"},"content": {"1": "rtsp://v5.cache3.c.youtube.com/' 'CiILENy.../0/0/0/video.3gp","5": "http://www.youtube.com/v/hYB0mn5zh2' 'c?f...","6": "rtsp://v1.cache1.c.youtube.com/CiILENy.../0/0/0/video.3' 'gp"},"duration": 2840,"rating": 4.63,"ratingCount": 68,"viewCount": 2' '20101,"favoriteCount": 201,"commentCount": 22}]}}') class JsoncConversionTest(unittest.TestCase): # See http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html def test_from_and_to_old_json(self): json = ('{"media$group":{"media$credit":[{"$t":"GoogleDevelopers", ' '"role":"uploader", "scheme":"urn:youtube"}]}}') jsonc_obj = gdata.core.parse_json(json) self.assert_(isinstance(jsonc_obj, gdata.core.Jsonc)) raw = gdata.core._convert_to_object(jsonc_obj) self.assertEqual(raw['media$group']['media$credit'][0]['$t'], 'GoogleDevelopers') def test_to_and_from_jsonc(self): x = {'a': 1} jsonc_obj = gdata.core._convert_to_jsonc(x) self.assertEqual(jsonc_obj.a, 1) # Convert the json_obj back to a dict and compare. self.assertEqual(x, gdata.core._convert_to_object(jsonc_obj)) def test_from_and_to_new_json(self): x = gdata.core.parse_json(PLAYLIST_EXAMPLE) self.assertEqual(x._dict['apiVersion'], '2.0') self.assertEqual(x._dict['data']._dict['items'][0]._dict['id'], '4DAEFAF23BB3CDD0') self.assertEqual(x._dict['data']._dict['items'][1]._dict['id'], '586D322B5E2764CF') x = gdata.core.parse_json(VIDEO_EXAMPLE) self.assertEqual(x._dict['apiVersion'], '2.0') self.assertEqual(x.data._dict['totalItems'], 800) self.assertEqual(x.data.items[0]._dict['viewCount'], 220101) def test_pretty_print(self): x = gdata.core.Jsonc(x=1, y=2, z=3) pretty = gdata.core.prettify_jsonc(x) self.assert_(isinstance(pretty, (str, unicode))) pretty = gdata.core.prettify_jsonc(x, 4) self.assert_(isinstance(pretty, (str, unicode))) class MemberNameConversionTest(unittest.TestCase): def test_member_to_jsonc(self): self.assertEqual(gdata.core._to_jsonc_name(''), '') self.assertEqual(gdata.core._to_jsonc_name('foo'), 'foo') self.assertEqual(gdata.core._to_jsonc_name('Foo'), 'Foo') self.assertEqual(gdata.core._to_jsonc_name('test_x'), 'testX') self.assertEqual(gdata.core._to_jsonc_name('test_x_y_zabc'), 'testXYZabc') def build_test_object(): return gdata.core.Jsonc( api_version='2.0', data=gdata.core.Jsonc( total_items=800, items=[ gdata.core.Jsonc( view_count=220101, comment_count=22, favorite_count=201, content={ '1': ('rtsp://v5.cache3.c.youtube.com' '/CiILENy.../0/0/0/video.3gp')})])) class JsoncObjectTest(unittest.TestCase): def check_video_json(self, x): """Validates a JsoncObject similar to VIDEO_EXAMPLE.""" self.assert_(isinstance(x._dict, dict)) self.assert_(isinstance(x.data, gdata.core.Jsonc)) self.assert_(isinstance(x._dict['data'], gdata.core.Jsonc)) self.assert_(isinstance(x.data._dict, dict)) self.assert_(isinstance(x._dict['data']._dict, dict)) self.assert_(isinstance(x._dict['apiVersion'], (str, unicode))) self.assert_(isinstance(x.api_version, (str, unicode))) self.assert_(isinstance(x.data._dict['items'], list)) self.assert_(isinstance(x.data.items[0]._dict['commentCount'], (int, long))) self.assert_(isinstance(x.data.items[0].favorite_count, (int, long))) self.assertEqual(x.data.total_items, 800) self.assertEqual(x._dict['data']._dict['totalItems'], 800) self.assertEqual(x.data.items[0].view_count, 220101) self.assertEqual(x._dict['data']._dict['items'][0]._dict['viewCount'], 220101) self.assertEqual(x.data.items[0].comment_count, 22) self.assertEqual(x.data.items[0]._dict['commentCount'], 22) self.assertEqual(x.data.items[0].favorite_count, 201) self.assertEqual(x.data.items[0]._dict['favoriteCount'], 201) self.assertEqual( x.data.items[0].content._dict['1'], 'rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp') self.assertEqual(x.api_version, '2.0') self.assertEqual(x.api_version, x._dict['apiVersion']) def test_convert_to_jsonc(self): x = gdata.core._convert_to_jsonc(1) self.assert_(isinstance(x, (int, long))) self.assertEqual(x, 1) x = gdata.core._convert_to_jsonc([1, 'a']) self.assert_(isinstance(x, list)) self.assertEqual(len(x), 2) self.assert_(isinstance(x[0], (int, long))) self.assertEqual(x[0], 1) self.assert_(isinstance(x[1], (str, unicode))) self.assertEqual(x[1], 'a') x = gdata.core._convert_to_jsonc([{'b': 1}, 'a']) self.assert_(isinstance(x, list)) self.assertEqual(len(x), 2) self.assert_(isinstance(x[0], gdata.core.Jsonc)) self.assertEqual(x[0].b, 1) def test_non_json_members(self): x = gdata.core.Jsonc(alpha=1, _beta=2, deep={'_bbb': 3, 'aaa': 2}) x.test = 'a' x._bar = 'bacon' # Should be able to access the _beta member. self.assertEqual(x._beta, 2) self.assertEqual(getattr(x, '_beta'), 2) try: self.assertEqual(getattr(x.deep, '_bbb'), 3) except AttributeError: pass # There should not be a letter 'B' anywhere in the generated JSON. self.assertEqual(gdata.core.jsonc_to_string(x).find('B'), -1) # We should find a 'b' becuse we don't consider names of dict keys in # the constructor as aliases to camelCase names. self.assert_(not gdata.core.jsonc_to_string(x).find('b') == -1) def test_constructor(self): x = gdata.core.Jsonc(a=[{'x': 'y'}, 2]) self.assert_(isinstance(x, gdata.core.Jsonc)) self.assert_(isinstance(x.a, list)) self.assert_(isinstance(x.a[0], gdata.core.Jsonc)) self.assertEqual(x.a[0].x, 'y') self.assertEqual(x.a[1], 2) def test_read_json(self): x = gdata.core.parse_json(PLAYLIST_EXAMPLE) self.assert_(isinstance(x._dict, dict)) self.assertEqual(x._dict['apiVersion'], '2.0') self.assertEqual(x.api_version, '2.0') x = gdata.core.parse_json(VIDEO_EXAMPLE) self.assert_(isinstance(x._dict, dict)) self.assertEqual(x._dict['apiVersion'], '2.0') self.assertEqual(x.api_version, '2.0') x = gdata.core.parse_json(VIDEO_EXAMPLE) self.check_video_json(x) def test_write_json(self): x = gdata.core.Jsonc() x._dict['apiVersion'] = '2.0' x.data = {'totalItems': 800} x.data.items = [] x.data.items.append(gdata.core.Jsonc(view_count=220101)) x.data.items[0]._dict['favoriteCount'] = 201 x.data.items[0].comment_count = 22 x.data.items[0].content = { '1': 'rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp'} self.check_video_json(x) def test_build_using_contructor(self): x = build_test_object() self.check_video_json(x) def test_to_dict(self): x = build_test_object() self.assertEqual( gdata.core._convert_to_object(x), {'data': {'totalItems': 800, 'items': [ {'content': { '1': 'rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp'}, 'viewCount': 220101, 'commentCount': 22, 'favoriteCount': 201}]}, 'apiVersion': '2.0'}) def test_try_json_syntax(self): x = build_test_object() self.assertEqual(x.data.items[0].commentCount, 22) x.data.items[0].commentCount = 33 self.assertEqual(x.data.items[0].commentCount, 33) self.assertEqual(x.data.items[0].comment_count, 33) self.assertEqual(x.data.items[0]._dict['commentCount'], 33) def test_to_string(self): self.check_video_json( gdata.core.parse_json( gdata.core.jsonc_to_string( gdata.core._convert_to_object( build_test_object())))) def test_del_attr(self): x = build_test_object() self.assertEqual(x.data.items[0].commentCount, 22) del x.data.items[0].comment_count try: x.data.items[0].commentCount self.fail('Should not be able to access commentCount after deletion') except AttributeError: pass self.assertEqual(x.data.items[0].favorite_count, 201) del x.data.items[0].favorite_count try: x.data.items[0].favorite_count self.fail('Should not be able to access favorite_count after deletion') except AttributeError: pass try: x.data.items[0]._dict['favoriteCount'] self.fail('Should not see [\'favoriteCount\'] after deletion') except KeyError: pass self.assertEqual(x.data.items[0].view_count, 220101) del x.data.items[0]._dict['viewCount'] try: x.data.items[0].view_count self.fail('Should not be able to access view_count after deletion') except AttributeError: pass try: del x.data.missing self.fail('Should not delete a missing attribute') except AttributeError: pass def test_del_protected_attribute(self): x = gdata.core.Jsonc(public='x', _private='y') self.assertEqual(x.public, 'x') self.assertEqual(x._private, 'y') self.assertEqual(x['public'], 'x') try: x['_private'] self.fail('Should not be able to getitem with _name') except KeyError: pass del x._private try: x._private self.fail('Should not be able to access deleted member') except AttributeError: pass def test_get_set_del_item(self): x = build_test_object() # Check for expected members using different access patterns. self.assert_(isinstance(x._dict, dict)) self.assert_(isinstance(x['data'], gdata.core.Jsonc)) self.assert_(isinstance(x._dict['data'], gdata.core.Jsonc)) self.assert_(isinstance(x['data']._dict, dict)) self.assert_(isinstance(x._dict['data']._dict, dict)) self.assert_(isinstance(x['apiVersion'], (str, unicode))) try: x['api_version'] self.fail('Should not find using Python style name') except KeyError: pass self.assert_(isinstance(x.data['items'], list)) self.assert_(isinstance(x.data['items'][0]._dict['commentCount'], (int, long))) self.assert_(isinstance(x['data'].items[0]['favoriteCount'], (int, long))) self.assertEqual(x['data'].total_items, 800) self.assertEqual(x['data']['totalItems'], 800) self.assertEqual(x.data['items'][0]['viewCount'], 220101) self.assertEqual(x._dict['data'].items[0]._dict['viewCount'], 220101) self.assertEqual(x['data'].items[0].comment_count, 22) self.assertEqual(x.data.items[0]['commentCount'], 22) self.assertEqual(x.data.items[0]['favoriteCount'], 201) self.assertEqual(x.data.items[0]._dict['favoriteCount'], 201) self.assertEqual( x.data.items[0].content['1'], 'rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp') self.assertEqual( x.data.items[0]['content']['1'], 'rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp') self.assertEqual(x.api_version, '2.0') self.assertEqual(x['apiVersion'], x._dict['apiVersion']) # Set properties using setitem x['apiVersion'] = '3.2' self.assertEqual(x.api_version, '3.2') x.data['totalItems'] = 500 self.assertEqual(x['data'].total_items, 500) self.assertEqual(x['data'].items[0].favoriteCount, 201) try: del x['data']['favoriteCount'] self.fail('Should not be able to delete missing item') except KeyError: pass del x.data['items'][0]['favoriteCount'] try: x['data'].items[0].favoriteCount self.fail('Should not find favoriteCount removed using del item') except AttributeError: pass def suite(): return conf.build_suite([JsoncConversionTest, MemberNameConversionTest, JsoncObjectTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jhartmann@gmail.com (Jochen Hartmann)' import getpass import time import StringIO import random import unittest import atom import gdata.youtube import gdata.youtube.service YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' class YouTubeServiceTest(unittest.TestCase): def setUp(self): self.client = gdata.youtube.service.YouTubeService() self.client.email = username self.client.password = password self.client.source = YOUTUBE_TEST_CLIENT_ID self.client.developer_key = developer_key self.client.client_id = YOUTUBE_TEST_CLIENT_ID self.client.ProgrammaticLogin() def testRetrieveVideoFeed(self): feed = self.client.GetYouTubeVideoFeed( 'http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured'); self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) for entry in feed.entry: self.assert_(entry.title.text != '') def testRetrieveTopRatedVideoFeed(self): feed = self.client.GetTopRatedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostViewedVideoFeed(self): feed = self.client.GetMostViewedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveRecentlyFeaturedVideoFeed(self): feed = self.client.GetRecentlyFeaturedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveWatchOnMobileVideoFeed(self): feed = self.client.GetWatchOnMobileVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveTopFavoritesVideoFeed(self): feed = self.client.GetTopFavoritesVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostRecentVideoFeed(self): feed = self.client.GetMostRecentVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostDiscussedVideoFeed(self): feed = self.client.GetMostDiscussedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostLinkedVideoFeed(self): feed = self.client.GetMostLinkedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveMostRespondedVideoFeed(self): feed = self.client.GetMostRespondedVideoFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 10) def testRetrieveVideoEntryByUri(self): entry = self.client.GetYouTubeVideoEntry( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k') self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry)) self.assert_(entry.title.text != '') def testRetrieveVideoEntryByVideoId(self): entry = self.client.GetYouTubeVideoEntry(video_id='Ncakifd_16k') self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry)) self.assert_(entry.title.text != '') def testRetrieveUserVideosbyUri(self): feed = self.client.GetYouTubeUserFeed( 'http://gdata.youtube.com/feeds/users/gdpython/uploads') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveUserVideosbyUsername(self): feed = self.client.GetYouTubeUserFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testSearchWithVideoQuery(self): query = gdata.youtube.service.YouTubeVideoQuery() query.vq = 'google' query.max_results = 8 feed = self.client.YouTubeQuery(query) self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assertEquals(len(feed.entry), 8) def testDirectVideoUploadStatusUpdateAndDeletion(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos'), player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) # Set Geo location to 37,-122 lat, long where = gdata.geo.Where() where.set_location((37.0,-122.0)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group, geo=where) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) new_entry = self.client.InsertVideoEntry(video_entry, video_file_location) self.assert_(isinstance(new_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(new_entry.title.text, test_video_title) self.assertEquals(new_entry.media.description.text, test_video_description) self.assert_(new_entry.id.text) # check upload status also upload_status = self.client.CheckUploadStatus(new_entry) self.assert_(upload_status[0] != '') # test updating entry meta-data new_video_description = 'description ' + str(random.randint(1000,5000)) new_entry.media.description.text = new_video_description updated_entry = self.client.UpdateVideoEntry(new_entry) self.assert_(isinstance(updated_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(updated_entry.media.description.text, new_video_description) # sleep for 10 seconds time.sleep(10) # test to delete the entry value = self.client.DeleteVideoEntry(updated_entry) if not value: # sleep more and try again time.sleep(20) # test to delete the entry value = self.client.DeleteVideoEntry(updated_entry) self.assert_(value == True) def testDirectVideoUploadWithDeveloperTags(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) test_developer_tag_01 = 'tag' + str(random.randint(1000,5000)) test_developer_tag_02 = 'tag' + str(random.randint(1000,5000)) test_developer_tag_03 = 'tag' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = [gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos')], player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) original_developer_tags = [test_developer_tag_01, test_developer_tag_02, test_developer_tag_03] dev_tags = video_entry.AddDeveloperTags(original_developer_tags) for dev_tag in dev_tags: self.assert_(dev_tag.text in original_developer_tags) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) new_entry = self.client.InsertVideoEntry(video_entry, video_file_location) self.assert_(isinstance(new_entry, gdata.youtube.YouTubeVideoEntry)) self.assertEquals(new_entry.title.text, test_video_title) self.assertEquals(new_entry.media.description.text, test_video_description) self.assert_(new_entry.id.text) developer_tags_from_new_entry = new_entry.GetDeveloperTags() for dev_tag in developer_tags_from_new_entry: self.assert_(dev_tag.text in original_developer_tags) self.assertEquals(len(developer_tags_from_new_entry), len(original_developer_tags)) # sleep for 10 seconds time.sleep(10) # test to delete the entry value = self.client.DeleteVideoEntry(new_entry) if not value: # sleep more and try again time.sleep(20) # test to delete the entry value = self.client.DeleteVideoEntry(new_entry) self.assert_(value == True) def testBrowserBasedVideoUpload(self): self.assertEquals(self.client.developer_key, developer_key) self.assertEquals(self.client.client_id, YOUTUBE_TEST_CLIENT_ID) self.assertEquals(self.client.additional_headers['X-GData-Key'], 'key=' + developer_key) self.assertEquals(self.client.additional_headers['X-Gdata-Client'], YOUTUBE_TEST_CLIENT_ID) test_video_title = 'my cool video ' + str(random.randint(1000,5000)) test_video_description = 'description ' + str(random.randint(1000,5000)) my_media_group = gdata.media.Group( title = gdata.media.Title(text=test_video_title), description = gdata.media.Description(description_type='plain', text=test_video_description), keywords = gdata.media.Keywords(text='video, foo'), category = gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos'), player=None ) self.assert_(isinstance(my_media_group, gdata.media.Group)) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) self.assert_(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) response = self.client.GetFormUploadToken(video_entry) self.assert_(response[0].startswith( 'http://uploads.gdata.youtube.com/action/FormDataUpload/')) self.assert_(len(response[0]) > 55) self.assert_(len(response[1]) > 100) def testRetrieveRelatedVideoFeedByUri(self): feed = self.client.GetYouTubeRelatedVideoFeed( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k/related') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveRelatedVideoFeedById(self): feed = self.client.GetYouTubeRelatedVideoFeed(video_id = 'Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveResponseVideoFeedByUri(self): feed = self.client.GetYouTubeVideoResponseFeed( 'http://gdata.youtube.com/feeds/videos/Ncakifd_16k/responses') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoResponseFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveResponseVideoFeedById(self): feed = self.client.GetYouTubeVideoResponseFeed(video_id='Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoResponseFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveVideoCommentFeedByUri(self): feed = self.client.GetYouTubeVideoCommentFeed( 'http://gdata.youtube.com/feeds/api/videos/Ncakifd_16k/comments') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoCommentFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveVideoCommentFeedByVideoId(self): feed = self.client.GetYouTubeVideoCommentFeed(video_id='Ncakifd_16k') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoCommentFeed)) self.assert_(len(feed.entry) > 0) def testAddComment(self): video_id = '9g6buYJTt_g' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id) random_comment_text = 'test_comment_' + str(random.randint(1000,50000)) self.client.AddComment(comment_text=random_comment_text, video_entry=video_entry) comment_feed = self.client.GetYouTubeVideoCommentFeed(video_id=video_id) comment_found = False for item in comment_feed.entry: if (item.content.text == random_comment_text): comment_found = True self.assertEquals(comment_found, True) def testAddRating(self): video_id_to_rate = 'Ncakifd_16k' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id_to_rate) response = self.client.AddRating(3, video_entry) self.assert_(isinstance(response, gdata.GDataEntry)) def testRetrievePlaylistFeedByUri(self): feed = self.client.GetYouTubePlaylistFeed( 'http://gdata.youtube.com/feeds/users/gdpython/playlists') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistFeed)) self.assert_(len(feed.entry) > 0) def testRetrievePlaylistListFeedByUsername(self): feed = self.client.GetYouTubePlaylistFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistFeed)) self.assert_(len(feed.entry) > 0) def testRetrievePlaylistVideoFeed(self): feed = self.client.GetYouTubePlaylistVideoFeed( 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505') self.assert_(isinstance(feed, gdata.youtube.YouTubePlaylistVideoFeed)) self.assert_(len(feed.entry) > 0) self.assert_(isinstance(feed.entry[0], gdata.youtube.YouTubePlaylistVideoEntry)) def testAddUpdateAndDeletePlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) new_playlist_title = 'my updated playlist ' + str(random.randint(1000,4000)) new_playlist_description = 'my updated playlist ' playlist_entry_id = response.id.text.split('/')[-1] updated_playlist = self.client.UpdatePlaylist(playlist_entry_id, new_playlist_title, new_playlist_description) playlist_feed = self.client.GetYouTubePlaylistFeed() update_successful = False for playlist_entry in playlist_feed.entry: if playlist_entry.title.text == new_playlist_title: update_successful = True break self.assertEquals(update_successful, True) # wait time.sleep(10) # delete it playlist_uri = updated_playlist.id.text response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testAddUpdateAndDeletePrivatePlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description, playlist_private=True) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) new_playlist_title = 'my updated playlist ' + str(random.randint(1000,4000)) new_playlist_description = 'my updated playlist ' playlist_entry_id = response.id.text.split('/')[-1] updated_playlist = self.client.UpdatePlaylist(playlist_entry_id, new_playlist_title, new_playlist_description, playlist_private=True) playlist_feed = self.client.GetYouTubePlaylistFeed() update_successful = False playlist_still_private = False for playlist_entry in playlist_feed.entry: if playlist_entry.title.text == new_playlist_title: update_successful = True if playlist_entry.private is not None: playlist_still_private = True self.assertEquals(update_successful, True) self.assertEquals(playlist_still_private, True) # wait time.sleep(10) # delete it playlist_uri = updated_playlist.id.text response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testAddEditAndDeleteVideoFromPlaylist(self): test_playlist_title = 'my test playlist ' + str(random.randint(1000,3000)) test_playlist_description = 'test playlist ' response = self.client.AddPlaylist(test_playlist_title, test_playlist_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistEntry)) custom_video_title = 'my test video on my test playlist' custom_video_description = 'this is a test video on my test playlist' video_id = 'Ncakifd_16k' playlist_uri = response.feed_link[0].href time.sleep(10) response = self.client.AddPlaylistVideoEntryToPlaylist( playlist_uri, video_id, custom_video_title, custom_video_description) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistVideoEntry)) playlist_entry_id = response.id.text.split('/')[-1] playlist_uri = response.id.text.split(playlist_entry_id)[0][:-1] new_video_title = 'video number ' + str(random.randint(1000,3000)) new_video_description = 'test video' time.sleep(10) response = self.client.UpdatePlaylistVideoEntryMetaData( playlist_uri, playlist_entry_id, new_video_title, new_video_description, 1) self.assert_(isinstance(response, gdata.youtube.YouTubePlaylistVideoEntry)) time.sleep(10) playlist_entry_id = response.id.text.split('/')[-1] # remove video from playlist response = self.client.DeletePlaylistVideoEntry(playlist_uri, playlist_entry_id) self.assertEquals(response, True) time.sleep(10) # delete the playlist response = self.client.DeletePlaylist(playlist_uri) self.assertEquals(response, True) def testRetrieveSubscriptionFeedByUri(self): feed = self.client.GetYouTubeSubscriptionFeed( 'http://gdata.youtube.com/feeds/users/gdpython/subscriptions') self.assert_(isinstance(feed, gdata.youtube.YouTubeSubscriptionFeed)) self.assert_(len(feed.entry) == 3) subscription_to_channel_found = False subscription_to_favorites_found = False subscription_to_query_found = False all_types_found = False for entry in feed.entry: self.assert_(isinstance(entry, gdata.youtube.YouTubeSubscriptionEntry)) subscription_type = entry.GetSubscriptionType() if subscription_type == 'channel': subscription_to_channel_found = True elif subscription_type == 'favorites': subscription_to_favorites_found = True elif subscription_type == 'query': subscription_to_query_found = True if (subscription_to_channel_found and subscription_to_favorites_found and subscription_to_query_found): all_types_found = True self.assertEquals(all_types_found, True) def testRetrieveSubscriptionFeedByUsername(self): feed = self.client.GetYouTubeSubscriptionFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeSubscriptionFeed)) self.assert_(len(feed.entry) == 3) subscription_to_channel_found = False subscription_to_favorites_found = False subscription_to_query_found = False all_types_found = False for entry in feed.entry: self.assert_(isinstance(entry, gdata.youtube.YouTubeSubscriptionEntry)) subscription_type = entry.GetSubscriptionType() if subscription_type == 'channel': subscription_to_channel_found = True elif subscription_type == 'favorites': subscription_to_favorites_found = True elif subscription_type == 'query': subscription_to_query_found = True if (subscription_to_channel_found and subscription_to_favorites_found and subscription_to_query_found): all_types_found = True self.assertEquals(all_types_found, True) def testRetrieveUserProfileByUri(self): user = self.client.GetYouTubeUserEntry( 'http://gdata.youtube.com/feeds/users/gdpython') self.assert_(isinstance(user, gdata.youtube.YouTubeUserEntry)) self.assertEquals(user.location.text, 'US') def testRetrieveUserProfileByUsername(self): user = self.client.GetYouTubeUserEntry(username='gdpython') self.assert_(isinstance(user, gdata.youtube.YouTubeUserEntry)) self.assertEquals(user.location.text, 'US') def testRetrieveUserFavoritesFeed(self): feed = self.client.GetUserFavoritesFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testRetrieveDefaultUserFavoritesFeed(self): feed = self.client.GetUserFavoritesFeed() self.assert_(isinstance(feed, gdata.youtube.YouTubeVideoFeed)) self.assert_(len(feed.entry) > 0) def testAddAndDeleteVideoFromFavorites(self): video_id = 'Ncakifd_16k' video_entry = self.client.GetYouTubeVideoEntry(video_id=video_id) response = self.client.AddVideoEntryToFavorites(video_entry) self.assert_(isinstance(response, gdata.GDataEntry)) time.sleep(10) response = self.client.DeleteVideoEntryFromFavorites(video_id) self.assertEquals(response, True) def testRetrieveContactFeedByUri(self): feed = self.client.GetYouTubeContactFeed( 'http://gdata.youtube.com/feeds/users/gdpython/contacts') self.assert_(isinstance(feed, gdata.youtube.YouTubeContactFeed)) self.assertEquals(len(feed.entry), 1) def testRetrieveContactFeedByUsername(self): feed = self.client.GetYouTubeContactFeed(username='gdpython') self.assert_(isinstance(feed, gdata.youtube.YouTubeContactFeed)) self.assertEquals(len(feed.entry), 1) if __name__ == '__main__': print ('NOTE: Please run these tests only with a test account. ' 'The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() developer_key = raw_input('Please enter your developer key: ') video_file_location = raw_input( 'Please enter the absolute path to a video file: ') unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 's@google.com (John Skidgel)' # Python imports. import unittest import urllib import urllib2 # Google Data APIs imports. import gdata.youtube.client import gdata.youtube.data import gdata.gauth import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data import gdata.test_config as conf # Constants #DEVELOPER_KEY = 'AI39si4DTx4tY1ZCnIiZJrxtaxzfYuomY20SKDSfIAYrehKForeoHVgAgJZdNcYhmugD103wciae6TRI6M96nSymS8TV1kNP7g' #CLIENT_ID = 'ytapi-Google-CaptionTube-2rj5q0oh-0' conf.options.register_option(conf.YT_DEVELOPER_KEY_OPTION) conf.options.register_option(conf.YT_CLIENT_ID_OPTION) conf.options.register_option(conf.YT_VIDEO_ID_OPTION) TRACK_BODY_SRT = """1 00:00:04,0 --> 00:00:05,75 My other computer is a data center """ class YouTubeClientTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.youtube.client.YouTubeClient() conf.configure_client(self.client, 'YouTubeTest', 'youtube') def tearDown(self): conf.close_client(self.client) def test_retrieve_video_entry(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_retrieve_video_entry') entry = self.client.get_video_entry(video_id=conf.options.get_value('videoid')) self.assertTrue(entry.etag) def test_retrieve_video_feed(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_retrieve_video_has_entries') entries = self.client.get_videos() self.assertTrue(len(entries.entry) > 0) def test_retrieve_user_feed(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_retrieve_video_has_entries') entries = self.client.get_user_feed(username='joegregoriotest') self.assertTrue(len(entries.entry) > 0) def test_create_update_delete_captions(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete_captions') # Add a track. created = self.client.create_track(conf.options.get_value('videoid'), 'Test', 'en', TRACK_BODY_SRT, conf.options.get_value('clientid'), conf.options.get_value('developerkey')) self.assertEqual(created.__class__, gdata.youtube.data.TrackEntry) # Update the contents of a track. Language and title cannot be # updated due to limitations. A workaround is to delete the original # track and replace it with captions that have the desired contents, # title, and name. # @see 'Updating a caption track' in the protocol guide for captions: # http://code.google.com/intl/en/apis/youtube/2.0/ # developers_guide_protocol_captions.html updated = self.client.update_track(conf.options.get_value('videoid'), created, TRACK_BODY_SRT, conf.options.get_value('clientid'), conf.options.get_value('developerkey')) self.assertEqual(updated.__class__, gdata.youtube.data.TrackEntry) # Retrieve the captions for the track for comparision testing. track_url = updated.content.src track = self.client.get_caption_track( track_url, conf.options.get_value('clientid'), conf.options.get_value('developerkey')) track_contents = track.read() self.assertEqual(track_contents, TRACK_BODY_SRT) # Delete a track. resp = self.client.delete_track(conf.options.get_value('videoid'), created, conf.options.get_value('clientid'), conf.options.get_value('developerkey')) self.assertEqual(200, resp.status) def suite(): return conf.build_suite([YouTubeClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata from gdata import test_data import gdata.apps class AppsEmailListRecipientFeedTest(unittest.TestCase): def setUp(self): self.rcpt_feed = gdata.apps.EmailListRecipientFeedFromString( test_data.EMAIL_LIST_RECIPIENT_FEED) def testEmailListRecipientEntryCount(self): """Count EmailListRecipient entries in EmailListRecipientFeed""" self.assertEquals(len(self.rcpt_feed.entry), 2) def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.rcpt_feed.GetSelfLink() is not None) self.assert_(self.rcpt_feed.GetNextLink() is not None) self.assert_(self.rcpt_feed.GetEditLink() is None) self.assert_(self.rcpt_feed.GetHtmlLink() is None) def testStartItem(self): """Tests the existence of <openSearch:startIndex> in EmailListRecipientFeed and verifies the value""" self.assert_(isinstance(self.rcpt_feed.start_index, gdata.StartIndex), "EmailListRecipient feed <openSearch:startIndex> element must be " + "an instance of gdata.OpenSearch: %s" % self.rcpt_feed.start_index) self.assertEquals(self.rcpt_feed.start_index.text, "1") def testEmailListRecipientEntries(self): """Tests the existence of <atom:entry> in EmailListRecipientFeed and simply verifies the value""" for a_entry in self.rcpt_feed.entry: self.assert_(isinstance(a_entry, gdata.apps.EmailListRecipientEntry), "EmailListRecipient Feed <atom:entry> must be an instance of " + "apps.EmailListRecipientEntry: %s" % a_entry) self.assertEquals(self.rcpt_feed.entry[0].who.email, "joe@example.com") self.assertEquals(self.rcpt_feed.entry[1].who.email, "susan@example.com") class AppsEmailListFeedTest(unittest.TestCase): def setUp(self): self.list_feed = gdata.apps.EmailListFeedFromString( test_data.EMAIL_LIST_FEED) def testEmailListEntryCount(self): """Count EmailList entries in EmailListFeed""" self.assertEquals(len(self.list_feed.entry), 2) def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.list_feed.GetSelfLink() is not None) self.assert_(self.list_feed.GetNextLink() is not None) self.assert_(self.list_feed.GetEditLink() is None) self.assert_(self.list_feed.GetHtmlLink() is None) def testStartItem(self): """Tests the existence of <openSearch:startIndex> in EmailListFeed and verifies the value""" self.assert_(isinstance(self.list_feed.start_index, gdata.StartIndex), "EmailList feed <openSearch:startIndex> element must be an instance " + "of gdata.OpenSearch: %s" % self.list_feed.start_index) self.assertEquals(self.list_feed.start_index.text, "1") def testUserEntries(self): """Tests the existence of <atom:entry> in EmailListFeed and simply verifies the value""" for a_entry in self.list_feed.entry: self.assert_(isinstance(a_entry, gdata.apps.EmailListEntry), "EmailList Feed <atom:entry> must be an instance of " + "apps.EmailListEntry: %s" % a_entry) self.assertEquals(self.list_feed.entry[0].email_list.name, "us-sales") self.assertEquals(self.list_feed.entry[1].email_list.name, "us-eng") class AppsUserFeedTest(unittest.TestCase): def setUp(self): self.user_feed = gdata.apps.UserFeedFromString(test_data.USER_FEED) def testUserEntryCount(self): """Count User entries in UserFeed""" self.assertEquals(len(self.user_feed.entry), 2) def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.user_feed.GetSelfLink() is not None) self.assert_(self.user_feed.GetNextLink() is not None) self.assert_(self.user_feed.GetEditLink() is None) self.assert_(self.user_feed.GetHtmlLink() is None) def testStartItem(self): """Tests the existence of <openSearch:startIndex> in UserFeed and verifies the value""" self.assert_(isinstance(self.user_feed.start_index, gdata.StartIndex), "User feed <openSearch:startIndex> element must be an instance " + "of gdata.OpenSearch: %s" % self.user_feed.start_index) self.assertEquals(self.user_feed.start_index.text, "1") def testUserEntries(self): """Tests the existence of <atom:entry> in UserFeed and simply verifies the value""" for a_entry in self.user_feed.entry: self.assert_(isinstance(a_entry, gdata.apps.UserEntry), "User Feed <atom:entry> must be an instance of " + "apps.UserEntry: %s" % a_entry) self.assertEquals(self.user_feed.entry[0].login.user_name, "TestUser") self.assertEquals(self.user_feed.entry[0].who.email, "TestUser@example.com") self.assertEquals(self.user_feed.entry[1].login.user_name, "JohnSmith") self.assertEquals(self.user_feed.entry[1].who.email, "JohnSmith@example.com") class AppsNicknameFeedTest(unittest.TestCase): def setUp(self): self.nick_feed = gdata.apps.NicknameFeedFromString(test_data.NICK_FEED) def testNicknameEntryCount(self): """Count Nickname entries in NicknameFeed""" self.assertEquals(len(self.nick_feed.entry), 2) def testId(self): """Tests the existence of <atom:id> in NicknameFeed and verifies the value""" self.assert_(isinstance(self.nick_feed.id, atom.Id), "Nickname feed <atom:id> element must be an instance of " + "atom.Id: %s" % self.nick_feed.id) self.assertEquals(self.nick_feed.id.text, "http://apps-apis.google.com/a/feeds/example.com/nickname/2.0") def testStartItem(self): """Tests the existence of <openSearch:startIndex> in NicknameFeed and verifies the value""" self.assert_(isinstance(self.nick_feed.start_index, gdata.StartIndex), "Nickname feed <openSearch:startIndex> element must be an instance " + "of gdata.OpenSearch: %s" % self.nick_feed.start_index) self.assertEquals(self.nick_feed.start_index.text, "1") def testItemsPerPage(self): """Tests the existence of <openSearch:itemsPerPage> in NicknameFeed and verifies the value""" self.assert_(isinstance(self.nick_feed.items_per_page, gdata.ItemsPerPage), "Nickname feed <openSearch:itemsPerPage> element must be an " + "instance of gdata.ItemsPerPage: %s" % self.nick_feed.items_per_page) self.assertEquals(self.nick_feed.items_per_page.text, "2") def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.nick_feed.GetSelfLink() is not None) self.assert_(self.nick_feed.GetEditLink() is None) self.assert_(self.nick_feed.GetHtmlLink() is None) def testNicknameEntries(self): """Tests the existence of <atom:entry> in NicknameFeed and simply verifies the value""" for a_entry in self.nick_feed.entry: self.assert_(isinstance(a_entry, gdata.apps.NicknameEntry), "Nickname Feed <atom:entry> must be an instance of " + "apps.NicknameEntry: %s" % a_entry) self.assertEquals(self.nick_feed.entry[0].nickname.name, "Foo") self.assertEquals(self.nick_feed.entry[1].nickname.name, "Bar") class AppsEmailListRecipientEntryTest(unittest.TestCase): def setUp(self): self.rcpt_entry = gdata.apps.EmailListRecipientEntryFromString( test_data.EMAIL_LIST_RECIPIENT_ENTRY) def testId(self): """Tests the existence of <atom:id> in EmailListRecipientEntry and verifies the value""" self.assert_( isinstance(self.rcpt_entry.id, atom.Id), "EmailListRecipient entry <atom:id> element must be an instance of " + "atom.Id: %s" % self.rcpt_entry.id) self.assertEquals( self.rcpt_entry.id.text, 'https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/' + 'recipient/TestUser%40example.com') def testUpdated(self): """Tests the existence of <atom:updated> in EmailListRecipientEntry and verifies the value""" self.assert_( isinstance(self.rcpt_entry.updated, atom.Updated), "EmailListRecipient entry <atom:updated> element must be an instance " + "of atom.Updated: %s" % self.rcpt_entry.updated) self.assertEquals(self.rcpt_entry.updated.text, '1970-01-01T00:00:00.000Z') def testCategory(self): """Tests the existence of <atom:category> in EmailListRecipientEntry and verifies the value""" for a_category in self.rcpt_entry.category: self.assert_( isinstance(a_category, atom.Category), "EmailListRecipient entry <atom:category> element must be an " + "instance of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, "http://schemas.google.com/g/2005#kind") self.assertEquals(a_category.term, "http://schemas.google.com/apps/2006#" + "emailList.recipient") def testTitle(self): """Tests the existence of <atom:title> in EmailListRecipientEntry and verifies the value""" self.assert_( isinstance(self.rcpt_entry.title, atom.Title), "EmailListRecipient entry <atom:title> element must be an instance of " + "atom.Title: %s" % self.rcpt_entry.title) self.assertEquals(self.rcpt_entry.title.text, 'TestUser') def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.rcpt_entry.GetSelfLink() is not None) self.assert_(self.rcpt_entry.GetEditLink() is not None) self.assert_(self.rcpt_entry.GetHtmlLink() is None) def testWho(self): """Tests the existence of a <gdata:who> in EmailListRecipientEntry and verifies the value""" self.assert_(isinstance(self.rcpt_entry.who, gdata.apps.Who), "EmailListRecipient entry <gdata:who> must be an instance of " + "apps.Who: %s" % self.rcpt_entry.who) self.assertEquals(self.rcpt_entry.who.email, 'TestUser@example.com') class AppsEmailListEntryTest(unittest.TestCase): def setUp(self): self.list_entry = gdata.apps.EmailListEntryFromString( test_data.EMAIL_LIST_ENTRY) def testId(self): """Tests the existence of <atom:id> in EmailListEntry and verifies the value""" self.assert_( isinstance(self.list_entry.id, atom.Id), "EmailList entry <atom:id> element must be an instance of atom.Id: %s" % self.list_entry.id) self.assertEquals( self.list_entry.id.text, 'https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist') def testUpdated(self): """Tests the existence of <atom:updated> in EmailListEntry and verifies the value""" self.assert_( isinstance(self.list_entry.updated, atom.Updated), "EmailList entry <atom:updated> element must be an instance of " + "atom.Updated: %s" % self.list_entry.updated) self.assertEquals(self.list_entry.updated.text, '1970-01-01T00:00:00.000Z') def testCategory(self): """Tests the existence of <atom:category> in EmailListEntry and verifies the value""" for a_category in self.list_entry.category: self.assert_( isinstance(a_category, atom.Category), "EmailList entry <atom:category> element must be an instance " + "of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, "http://schemas.google.com/g/2005#kind") self.assertEquals(a_category.term, "http://schemas.google.com/apps/2006#emailList") def testTitle(self): """Tests the existence of <atom:title> in EmailListEntry and verifies the value""" self.assert_( isinstance(self.list_entry.title, atom.Title), "EmailList entry <atom:title> element must be an instance of " + "atom.Title: %s" % self.list_entry.title) self.assertEquals(self.list_entry.title.text, 'testlist') def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.list_entry.GetSelfLink() is not None) self.assert_(self.list_entry.GetEditLink() is not None) self.assert_(self.list_entry.GetHtmlLink() is None) def testEmailList(self): """Tests the existence of a <apps:emailList> in EmailListEntry and verifies the value""" self.assert_(isinstance(self.list_entry.email_list, gdata.apps.EmailList), "EmailList entry <apps:emailList> must be an instance of " + "apps.EmailList: %s" % self.list_entry.email_list) self.assertEquals(self.list_entry.email_list.name, 'testlist') def testFeedLink(self): """Test the existence of a <gdata:feedLink> in EmailListEntry and verifies the value""" for an_feed_link in self.list_entry.feed_link: self.assert_(isinstance(an_feed_link, gdata.FeedLink), "EmailList entry <gdata:feedLink> must be an instance of " + "gdata.FeedLink: %s" % an_feed_link) self.assertEquals(self.list_entry.feed_link[0].rel, 'http://schemas.google.com/apps/2006#' + 'emailList.recipients') self.assertEquals(self.list_entry.feed_link[0].href, 'http://apps-apis.google.com/a/feeds/example.com/emailList/' + '2.0/testlist/recipient/') class AppsNicknameEntryTest(unittest.TestCase): def setUp(self): self.nick_entry = gdata.apps.NicknameEntryFromString(test_data.NICK_ENTRY) def testId(self): """Tests the existence of <atom:id> in NicknameEntry and verifies the value""" self.assert_( isinstance(self.nick_entry.id, atom.Id), "Nickname entry <atom:id> element must be an instance of atom.Id: %s" % self.nick_entry.id) self.assertEquals( self.nick_entry.id.text, 'https://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo') def testCategory(self): """Tests the existence of <atom:category> in NicknameEntry and verifies the value""" for a_category in self.nick_entry.category: self.assert_( isinstance(a_category, atom.Category), "Nickname entry <atom:category> element must be an instance " + "of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, "http://schemas.google.com/g/2005#kind") self.assertEquals(a_category.term, "http://schemas.google.com/apps/2006#nickname") def testTitle(self): """Tests the existence of <atom:title> in NicknameEntry and verifies the value""" self.assert_(isinstance(self.nick_entry.title, atom.Title), "Nickname entry <atom:title> element must be an instance " + "of atom.Title: %s" % self.nick_entry.title) self.assertEquals(self.nick_entry.title.text, "Foo") def testLogin(self): """Tests the existence of <apps:login> in NicknameEntry and verifies the value""" self.assert_(isinstance(self.nick_entry.login, gdata.apps.Login), "Nickname entry <apps:login> element must be an instance " + "of apps.Login: %s" % self.nick_entry.login) self.assertEquals(self.nick_entry.login.user_name, "TestUser") def testNickname(self): """Tests the existence of <apps:nickname> in NicknameEntry and verifies the value""" self.assert_(isinstance(self.nick_entry.nickname, gdata.apps.Nickname), "Nickname entry <apps:nickname> element must be an instance " + "of apps.Nickname: %s" % self.nick_entry.nickname) self.assertEquals(self.nick_entry.nickname.name, "Foo") def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.nick_entry.GetSelfLink() is not None) self.assert_(self.nick_entry.GetEditLink() is not None) self.assert_(self.nick_entry.GetHtmlLink() is None) class AppsUserEntryTest(unittest.TestCase): def setUp(self): self.user_entry = gdata.apps.UserEntryFromString(test_data.USER_ENTRY) def testId(self): """Tests the existence of <atom:id> in UserEntry and verifies the value""" self.assert_( isinstance(self.user_entry.id, atom.Id), "User entry <atom:id> element must be an instance of atom.Id: %s" % self.user_entry.id) self.assertEquals( self.user_entry.id.text, 'https://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser') def testUpdated(self): """Tests the existence of <atom:updated> in UserEntry and verifies the value""" self.assert_( isinstance(self.user_entry.updated, atom.Updated), "User entry <atom:updated> element must be an instance of " + "atom.Updated: %s" % self.user_entry.updated) self.assertEquals(self.user_entry.updated.text, '1970-01-01T00:00:00.000Z') def testCategory(self): """Tests the existence of <atom:category> in UserEntry and verifies the value""" for a_category in self.user_entry.category: self.assert_( isinstance(a_category, atom.Category), "User entry <atom:category> element must be an instance " + "of atom.Category: %s" % a_category) self.assertEquals(a_category.scheme, "http://schemas.google.com/g/2005#kind") self.assertEquals(a_category.term, "http://schemas.google.com/apps/2006#user") def testTitle(self): """Tests the existence of <atom:title> in UserEntry and verifies the value""" self.assert_( isinstance(self.user_entry.title, atom.Title), "User entry <atom:title> element must be an instance of atom.Title: %s" % self.user_entry.title) self.assertEquals(self.user_entry.title.text, 'TestUser') def testLinkFinderFindsHtmlLink(self): """Tests the return value of GetXXXLink() methods""" self.assert_(self.user_entry.GetSelfLink() is not None) self.assert_(self.user_entry.GetEditLink() is not None) self.assert_(self.user_entry.GetHtmlLink() is None) def testLogin(self): """Tests the existence of <apps:login> in UserEntry and verifies the value""" self.assert_(isinstance(self.user_entry.login, gdata.apps.Login), "User entry <apps:login> element must be an instance of apps.Login: %s" % self.user_entry.login) self.assertEquals(self.user_entry.login.user_name, 'TestUser') self.assertEquals(self.user_entry.login.password, 'password') self.assertEquals(self.user_entry.login.suspended, 'false') self.assertEquals(self.user_entry.login.ip_whitelisted, 'false') self.assertEquals(self.user_entry.login.hash_function_name, 'SHA-1') def testName(self): """Tests the existence of <apps:name> in UserEntry and verifies the value""" self.assert_(isinstance(self.user_entry.name, gdata.apps.Name), "User entry <apps:name> element must be an instance of apps.Name: %s" % self.user_entry.name) self.assertEquals(self.user_entry.name.family_name, 'Test') self.assertEquals(self.user_entry.name.given_name, 'User') def testQuota(self): """Tests the existence of <apps:quota> in UserEntry and verifies the value""" self.assert_(isinstance(self.user_entry.quota, gdata.apps.Quota), "User entry <apps:quota> element must be an instance of apps.Quota: %s" % self.user_entry.quota) self.assertEquals(self.user_entry.quota.limit, '1024') def testFeedLink(self): """Test the existence of a <gdata:feedLink> in UserEntry and verifies the value""" for an_feed_link in self.user_entry.feed_link: self.assert_(isinstance(an_feed_link, gdata.FeedLink), "User entry <gdata:feedLink> must be an instance of gdata.FeedLink" + ": %s" % an_feed_link) self.assertEquals(self.user_entry.feed_link[0].rel, 'http://schemas.google.com/apps/2006#user.nicknames') self.assertEquals(self.user_entry.feed_link[0].href, 'https://apps-apis.google.com/a/feeds/example.com/nickname/' + '2.0?username=Test-3121') self.assertEquals(self.user_entry.feed_link[1].rel, 'http://schemas.google.com/apps/2006#user.emailLists') self.assertEquals(self.user_entry.feed_link[1].href, 'https://apps-apis.google.com/a/feeds/example.com/emailList/' + '2.0?recipient=testlist@example.com') def testUpdate(self): """Tests for modifing attributes of UserEntry""" self.user_entry.name.family_name = 'ModifiedFamilyName' self.user_entry.name.given_name = 'ModifiedGivenName' self.user_entry.quota.limit = '2048' self.user_entry.login.password = 'ModifiedPassword' self.user_entry.login.suspended = 'true' modified = gdata.apps.UserEntryFromString(self.user_entry.ToString()) self.assertEquals(modified.name.family_name, 'ModifiedFamilyName') self.assertEquals(modified.name.given_name, 'ModifiedGivenName') self.assertEquals(modified.quota.limit, '2048') self.assertEquals(modified.login.password, 'ModifiedPassword') self.assertEquals(modified.login.suspended, 'true') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder@gmail.com (Jeff Scudder)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata from gdata import test_data import gdata.base class LabelTest(unittest.TestCase): def setUp(self): self.label = gdata.base.Label() def testToAndFromString(self): self.label.text = 'test label' self.assert_(self.label.text == 'test label') new_label = gdata.base.LabelFromString(self.label.ToString()) self.assert_(self.label.text == new_label.text) class ItemTypeTest(unittest.TestCase): def setUp(self): self.item_type = gdata.base.ItemType() def testToAndFromString(self): self.item_type.text = 'product' self.item_type.type = 'text' self.assert_(self.item_type.text == 'product') self.assert_(self.item_type.type == 'text') new_item_type = gdata.base.ItemTypeFromString(self.item_type.ToString()) self.assert_(self.item_type.text == new_item_type.text) self.assert_(self.item_type.type == new_item_type.type) class GBaseItemTest(unittest.TestCase): def setUp(self): self.item = gdata.base.GBaseItem() def testToAndFromString(self): self.item.label.append(gdata.base.Label(text='my label')) self.assert_(self.item.label[0].text == 'my label') self.item.item_type = gdata.base.ItemType(text='products') self.assert_(self.item.item_type.text == 'products') self.item.item_attributes.append(gdata.base.ItemAttribute('extra', text='foo')) self.assert_(self.item.item_attributes[0].text == 'foo') self.assert_(self.item.item_attributes[0].name == 'extra') new_item = gdata.base.GBaseItemFromString(self.item.ToString()) self.assert_(self.item.label[0].text == new_item.label[0].text) self.assert_(self.item.item_type.text == new_item.item_type.text) self.assert_(self.item.item_attributes[0].text == new_item.item_attributes[0].text) def testCustomItemAttributes(self): self.item.AddItemAttribute('test_attrib', 'foo') self.assert_(self.item.FindItemAttribute('test_attrib') == 'foo') self.item.SetItemAttribute('test_attrib', 'bar') self.assert_(self.item.FindItemAttribute('test_attrib') == 'bar') self.item.RemoveItemAttribute('test_attrib') self.assert_(self.item.FindItemAttribute('test_attrib') is None) def testConvertActualData(self): feed = gdata.base.GBaseSnippetFeedFromString(test_data.GBASE_FEED) for an_entry in feed.entry: if an_entry.author[0].email.text == 'anon-szot0wdsq0at@base.google.com': for attrib in an_entry.item_attributes: if attrib.name == 'payment_notes': self.assert_(attrib.text == 'PayPal & Bill Me Later credit available online only.') if attrib.name == 'condition': self.assert_(attrib.text == 'new') # self.assert_(an_entry.item_attributes['condition'].text == 'new') def testModifyCustomItemAttributes(self): self.item.AddItemAttribute('test_attrib', 'foo', value_type='test1') self.item.AddItemAttribute('test_attrib', 'bar', value_type='test2') self.assertEquals(self.item.item_attributes[0].name, 'test_attrib') self.assertEquals(self.item.item_attributes[1].name, 'test_attrib') self.assertEquals(self.item.item_attributes[0].text, 'foo') self.assertEquals(self.item.item_attributes[1].text, 'bar') # Get one of the custom attributes from the item. attributes = self.item.GetItemAttributes('test_attrib') self.assertEquals(len(attributes), 2) self.assertEquals(attributes[0].text, 'foo') # Change the contents of the found item attribute. attributes[0].text = 'new foo' self.assertEquals(attributes[0].text, 'new foo') # Make sure that the change is reflected in the item. self.assertEquals(self.item.item_attributes[0].text, 'new foo') class GBaseItemFeedTest(unittest.TestCase): def setUp(self): self.item_feed = gdata.base.GBaseItemFeedFromString(test_data.GBASE_FEED) def testToAndFromString(self): self.assert_(len(self.item_feed.entry) == 3) for an_entry in self.item_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseItem)) new_item_feed = gdata.base.GBaseItemFeedFromString(str(self.item_feed)) for an_entry in new_item_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseItem)) #self.item_feed.label.append(gdata.base.Label(text='my label')) #self.assert_(self.item.label[0].text == 'my label') #self.item.item_type = gdata.base.ItemType(text='products') #self.assert_(self.item.item_type.text == 'products') #new_item = gdata.base.GBaseItemFromString(self.item.ToString()) #self.assert_(self.item.label[0].text == new_item.label[0].text) #self.assert_(self.item.item_type.text == new_item.item_type.text) def testLinkFinderFindsHtmlLink(self): for entry in self.item_feed.entry: # All Base entries should have a self link self.assert_(entry.GetSelfLink() is not None) # All Base items should have an HTML link self.assert_(entry.GetHtmlLink() is not None) # None of the Base items should have an edit link self.assert_(entry.GetEditLink() is None) class GBaseSnippetFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.base.GBaseItemFeed() self.snippet_feed = gdata.base.GBaseSnippetFeedFromString(test_data.GBASE_FEED) def testToAndFromString(self): self.assert_(len(self.snippet_feed.entry) == 3) for an_entry in self.snippet_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseSnippet)) new_snippet_feed = gdata.base.GBaseSnippetFeedFromString(str(self.snippet_feed)) for an_entry in new_snippet_feed.entry: self.assert_(isinstance(an_entry, gdata.base.GBaseSnippet)) class ItemAttributeTest(unittest.TestCase): def testToAndFromStirng(self): attrib = gdata.base.ItemAttribute('price') attrib.type = 'float' self.assert_(attrib.name == 'price') self.assert_(attrib.type == 'float') new_attrib = gdata.base.ItemAttributeFromString(str(attrib)) self.assert_(new_attrib.name == attrib.name) self.assert_(new_attrib.type == attrib.type) def testClassConvertsActualData(self): attrib = gdata.base.ItemAttributeFromString(test_data.TEST_GBASE_ATTRIBUTE) self.assert_(attrib.name == 'brand') self.assert_(attrib.type == 'text') self.assert_(len(attrib.extension_elements) == 0) # Test conversion to en ElementTree element = attrib._ToElementTree() self.assert_(element.tag == gdata.base.GBASE_TEMPLATE % 'brand') class AttributeTest(unittest.TestCase): def testAttributeToAndFromString(self): attrib = gdata.base.Attribute() attrib.type = 'float' attrib.count = '44000' attrib.name = 'test attribute' attrib.bucket.append(gdata.base.Bucket('30', text='test', low='5')) attrib.bucket[0].high = '11' attrib.value.append(gdata.base.Value(count='500', text='a value')) self.assert_(attrib.type == 'float') self.assert_(attrib.count == '44000') self.assert_(attrib.name == 'test attribute') self.assert_(attrib.value[0].count == '500') self.assert_(attrib.value[0].text == 'a value') self.assert_(attrib.bucket[0].text == 'test') self.assert_(attrib.bucket[0].count == '30') self.assert_(attrib.bucket[0].high == '11') self.assert_(attrib.bucket[0].low == '5') new_attrib = gdata.base.AttributeFromString(str(attrib)) self.assert_(attrib.type == new_attrib.type) self.assert_(attrib.count == new_attrib.count) self.assert_(attrib.value[0].count == new_attrib.value[0].count) self.assert_(attrib.value[0].text == new_attrib.value[0].text) self.assert_(attrib.bucket[0].text == new_attrib.bucket[0].text) self.assert_(attrib.bucket[0].count == new_attrib.bucket[0].count) self.assert_(attrib.bucket[0].high == new_attrib.bucket[0].high) self.assert_(attrib.bucket[0].low == new_attrib.bucket[0].low) self.assert_(attrib.name == new_attrib.name) class ValueTest(unittest.TestCase): def testValueToAndFromString(self): value = gdata.base.Value() value.count = '5123' value.text = 'super great' self.assert_(value.count == '5123') self.assert_(value.text == 'super great') new_value = gdata.base.ValueFromString(str(value)) self.assert_(new_value.count == value.count) self.assert_(new_value.text == value.text) class AttributeEntryTest(unittest.TestCase): def testAttributeEntryToAndFromString(self): value = gdata.base.Value(count='500', text='happy') attribute = gdata.base.Attribute(count='600', value=[value]) a_entry = gdata.base.GBaseAttributeEntry(attribute=[attribute]) self.assert_(a_entry.attribute[0].count == '600') self.assert_(a_entry.attribute[0].value[0].count == '500') self.assert_(a_entry.attribute[0].value[0].text == 'happy') new_entry = gdata.base.GBaseAttributeEntryFromString(str(a_entry)) self.assert_(new_entry.attribute[0].count == '600') self.assert_(new_entry.attribute[0].value[0].count == '500') self.assert_(new_entry.attribute[0].value[0].text == 'happy') class GBaseAttributeEntryTest(unittest.TestCase): def testAttribteEntryFromExampleData(self): entry = gdata.base.GBaseAttributeEntryFromString( test_data.GBASE_ATTRIBUTE_ENTRY) self.assert_(len(entry.attribute) == 1) self.assert_(len(entry.attribute[0].value) == 10) self.assert_(entry.attribute[0].name == 'job industry') for val in entry.attribute[0].value: if val.text == 'it internet': self.assert_(val.count == '380772') elif val.text == 'healthcare': self.assert_(val.count == '261565') class GBaseAttributesFeedTest(unittest.TestCase): def testAttributesFeedExampleData(self): feed = gdata.base.GBaseAttributesFeedFromString(test_data.GBASE_ATTRIBUTE_FEED) self.assert_(len(feed.entry) == 1) self.assert_(isinstance(feed.entry[0], gdata.base.GBaseAttributeEntry)) def testAttributesFeedToAndFromString(self): value = gdata.base.Value(count='500', text='happy') attribute = gdata.base.Attribute(count='600', value=[value]) a_entry = gdata.base.GBaseAttributeEntry(attribute=[attribute]) feed = gdata.base.GBaseAttributesFeed(entry=[a_entry]) self.assert_(feed.entry[0].attribute[0].count == '600') self.assert_(feed.entry[0].attribute[0].value[0].count == '500') self.assert_(feed.entry[0].attribute[0].value[0].text == 'happy') new_feed = gdata.base.GBaseAttributesFeedFromString(str(feed)) self.assert_(new_feed.entry[0].attribute[0].count == '600') self.assert_(new_feed.entry[0].attribute[0].value[0].count == '500') self.assert_(new_feed.entry[0].attribute[0].value[0].text == 'happy') class GBaseLocalesFeedTest(unittest.TestCase): def testLocatesFeedWithExampleData(self): feed = gdata.base.GBaseLocalesFeedFromString(test_data.GBASE_LOCALES_FEED) self.assert_(len(feed.entry) == 3) self.assert_(feed.GetSelfLink().href == 'http://www.google.com/base/feeds/locales/') for an_entry in feed.entry: if an_entry.title.text == 'en_US': self.assert_(an_entry.category[0].term == 'en_US') self.assert_(an_entry.title.text == an_entry.category[0].term) class GBaseItemTypesFeedAndEntryTest(unittest.TestCase): def testItemTypesFeedToAndFromString(self): feed = gdata.base.GBaseItemTypesFeed() entry = gdata.base.GBaseItemTypeEntry() entry.attribute.append(gdata.base.Attribute(name='location', attribute_type='location')) entry.item_type = gdata.base.ItemType(text='jobs') feed.entry.append(entry) self.assert_(len(feed.entry) == 1) self.assert_(feed.entry[0].attribute[0].name == 'location') new_feed = gdata.base.GBaseItemTypesFeedFromString(str(feed)) self.assert_(len(new_feed.entry) == 1) self.assert_(new_feed.entry[0].attribute[0].name == 'location') class GBaseImageLinkTest(unittest.TestCase): def testImageLinkToAndFromString(self): image_link = gdata.base.ImageLink() image_link.type = 'url' image_link.text = 'example.com' thumbnail = gdata.base.Thumbnail() thumbnail.width = '60' thumbnail.height = '80' thumbnail.text = 'example text' image_link.thumbnail.append(thumbnail) xml = image_link.ToString() parsed = gdata.base.ImageLinkFromString(xml) self.assert_(parsed.type == image_link.type) self.assert_(parsed.text == image_link.text) self.assert_(len(parsed.thumbnail) == 1) self.assert_(parsed.thumbnail[0].width == thumbnail.width) self.assert_(parsed.thumbnail[0].height == thumbnail.height) self.assert_(parsed.thumbnail[0].text == thumbnail.text) class GBaseItemAttributeAccessElement(unittest.TestCase): def testItemAttributeAccessAttribute(self): item = gdata.base.GBaseItem() item.AddItemAttribute('test', '1', value_type='int', access='private') private_attribute = item.GetItemAttributes('test')[0] self.assert_(private_attribute.access == 'private') xml = item.ToString() new_item = gdata.base.GBaseItemFromString(xml) new_attributes = new_item.GetItemAttributes('test') self.assert_(len(new_attributes) == 1) #self.assert_(new_attributes[0].access == 'private') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.gauth import atom.http_core import gdata.test_config as conf PRIVATE_TEST_KEY = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY-----""" class AuthSubTest(unittest.TestCase): def test_generate_request_url(self): url = gdata.gauth.generate_auth_sub_url('http://example.com', ['http://example.net/scope1']) self.assert_(isinstance(url, atom.http_core.Uri)) self.assertEqual(url.query['secure'], '0') self.assertEqual(url.query['session'], '1') self.assertEqual(url.query['scope'], 'http://example.net/scope1') self.assertEqual(atom.http_core.Uri.parse_uri( url.query['next']).query['auth_sub_scopes'], 'http://example.net/scope1') self.assertEqual(atom.http_core.Uri.parse_uri(url.query['next']).path, '/') self.assertEqual(atom.http_core.Uri.parse_uri(url.query['next']).host, 'example.com') def test_from_url(self): token_str = gdata.gauth.auth_sub_string_from_url( 'http://example.com/?token=123abc')[0] self.assertEqual(token_str, '123abc') def test_from_http_body(self): token_str = gdata.gauth.auth_sub_string_from_body('Something\n' 'Token=DQAA...7DCTN\n' 'Expiration=20061004T123456Z\n') self.assertEqual(token_str, 'DQAA...7DCTN') def test_modify_request(self): token = gdata.gauth.AuthSubToken('tval') request = atom.http_core.HttpRequest() token.modify_request(request) self.assertEqual(request.headers['Authorization'], 'AuthSub token=tval') def test_create_and_upgrade_tokens(self): token = gdata.gauth.AuthSubToken.from_url( 'http://example.com/?token=123abc') self.assert_(isinstance(token, gdata.gauth.AuthSubToken)) self.assertEqual(token.token_string, '123abc') self.assertEqual(token.scopes, []) token._upgrade_token('Token=456def') self.assertEqual(token.token_string, '456def') self.assertEqual(token.scopes, []) class SecureAuthSubTest(unittest.TestCase): def test_build_data(self): request = atom.http_core.HttpRequest(method='PUT') request.uri = atom.http_core.Uri.parse_uri('http://example.com/foo?a=1') data = gdata.gauth.build_auth_sub_data(request, 1234567890, 'mynonce') self.assertEqual(data, 'PUT http://example.com/foo?a=1 1234567890 mynonce') def test_generate_signature(self): request = atom.http_core.HttpRequest( method='GET', uri=atom.http_core.Uri(host='example.com', path='/foo', query={'a': '1'})) data = gdata.gauth.build_auth_sub_data(request, 1134567890, 'p234908') self.assertEqual(data, 'GET http://example.com/foo?a=1 1134567890 p234908') self.assertEqual( gdata.gauth.generate_signature(data, PRIVATE_TEST_KEY), 'GeBfeIDnT41dvLquPgDB4U5D4hfxqaHk/5LX1kccNBnL4BjsHWU1djbEp7xp3BL9ab' 'QtLrK7oa/aHEHtGRUZGg87O+ND8iDPR76WFXAruuN8O8GCMqCDdPduNPY++LYO4MdJ' 'BZNY974Nn0m6Hc0/T4M1ElqvPhl61fkXMm+ElSM=') class TokensToAndFromBlobsTest(unittest.TestCase): def test_client_login_conversion(self): token = gdata.gauth.ClientLoginToken('test|key') copy = gdata.gauth.token_from_blob(gdata.gauth.token_to_blob(token)) self.assertEqual(token.token_string, copy.token_string) self.assert_(isinstance(copy, gdata.gauth.ClientLoginToken)) def test_authsub_conversion(self): token = gdata.gauth.AuthSubToken('test|key') copy = gdata.gauth.token_from_blob(gdata.gauth.token_to_blob(token)) self.assertEqual(token.token_string, copy.token_string) self.assert_(isinstance(copy, gdata.gauth.AuthSubToken)) scopes = ['http://example.com', 'http://other||test', 'thir|d'] token = gdata.gauth.AuthSubToken('key-=', scopes) copy = gdata.gauth.token_from_blob(gdata.gauth.token_to_blob(token)) self.assertEqual(token.token_string, copy.token_string) self.assert_(isinstance(copy, gdata.gauth.AuthSubToken)) self.assertEqual(token.scopes, scopes) def test_join_and_split(self): token_string = gdata.gauth._join_token_parts('1x', 'test|string', '%x%', '', None) self.assertEqual(token_string, '1x|test%7Cstring|%25x%25||') token_type, a, b, c, d = gdata.gauth._split_token_parts(token_string) self.assertEqual(token_type, '1x') self.assertEqual(a, 'test|string') self.assertEqual(b, '%x%') self.assert_(c is None) self.assert_(d is None) def test_secure_authsub_conversion(self): token = gdata.gauth.SecureAuthSubToken( '%^%', 'myRsaKey', ['http://example.com', 'http://example.org']) copy = gdata.gauth.token_from_blob(gdata.gauth.token_to_blob(token)) self.assertEqual(copy.token_string, '%^%') self.assertEqual(copy.rsa_private_key, 'myRsaKey') self.assertEqual(copy.scopes, ['http://example.com', 'http://example.org']) token = gdata.gauth.SecureAuthSubToken(rsa_private_key='f', token_string='b') blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1s|b|f') copy = gdata.gauth.token_from_blob(blob) self.assertEqual(copy.token_string, 'b') self.assertEqual(copy.rsa_private_key, 'f') self.assertEqual(copy.scopes, []) token = gdata.gauth.SecureAuthSubToken(None, '') blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1s||') copy = gdata.gauth.token_from_blob(blob) self.assertEqual(copy.token_string, None) self.assertEqual(copy.rsa_private_key, None) self.assertEqual(copy.scopes, []) token = gdata.gauth.SecureAuthSubToken('', None) blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1s||') copy = gdata.gauth.token_from_blob(blob) self.assertEqual(copy.token_string, None) self.assertEqual(copy.rsa_private_key, None) self.assertEqual(copy.scopes, []) token = gdata.gauth.SecureAuthSubToken( None, None, ['http://example.net', 'http://google.com']) blob = gdata.gauth.token_to_blob(token) self.assertEqual( blob, '1s|||http%3A%2F%2Fexample.net|http%3A%2F%2Fgoogle.com') copy = gdata.gauth.token_from_blob(blob) self.assert_(copy.token_string is None) self.assert_(copy.rsa_private_key is None) self.assertEqual(copy.scopes, ['http://example.net', 'http://google.com']) def test_oauth_rsa_conversion(self): token = gdata.gauth.OAuthRsaToken( 'consumerKey', 'myRsa', 't', 'secret', gdata.gauth.AUTHORIZED_REQUEST_TOKEN, 'http://example.com/next', 'verifier') blob = gdata.gauth.token_to_blob(token) self.assertEqual( blob, '1r|consumerKey|myRsa|t|secret|2|http%3A%2F%2Fexample.com' '%2Fnext|verifier') copy = gdata.gauth.token_from_blob(blob) self.assert_(isinstance(copy, gdata.gauth.OAuthRsaToken)) self.assertEqual(copy.consumer_key, token.consumer_key) self.assertEqual(copy.rsa_private_key, token.rsa_private_key) self.assertEqual(copy.token, token.token) self.assertEqual(copy.token_secret, token.token_secret) self.assertEqual(copy.auth_state, token.auth_state) self.assertEqual(copy.next, token.next) self.assertEqual(copy.verifier, token.verifier) token = gdata.gauth.OAuthRsaToken( '', 'myRsa', 't', 'secret', 0) blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1r||myRsa|t|secret|0||') copy = gdata.gauth.token_from_blob(blob) self.assert_(isinstance(copy, gdata.gauth.OAuthRsaToken)) self.assert_(copy.consumer_key != token.consumer_key) self.assert_(copy.consumer_key is None) self.assertEqual(copy.rsa_private_key, token.rsa_private_key) self.assertEqual(copy.token, token.token) self.assertEqual(copy.token_secret, token.token_secret) self.assertEqual(copy.auth_state, token.auth_state) self.assertEqual(copy.next, token.next) self.assert_(copy.next is None) self.assertEqual(copy.verifier, token.verifier) self.assert_(copy.verifier is None) token = gdata.gauth.OAuthRsaToken( rsa_private_key='myRsa', token='t', token_secret='secret', auth_state=gdata.gauth.ACCESS_TOKEN, verifier='v', consumer_key=None) blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1r||myRsa|t|secret|3||v') copy = gdata.gauth.token_from_blob(blob) self.assertEqual(copy.consumer_key, token.consumer_key) self.assert_(copy.consumer_key is None) self.assertEqual(copy.rsa_private_key, token.rsa_private_key) self.assertEqual(copy.token, token.token) self.assertEqual(copy.token_secret, token.token_secret) self.assertEqual(copy.auth_state, token.auth_state) self.assertEqual(copy.next, token.next) self.assert_(copy.next is None) self.assertEqual(copy.verifier, token.verifier) def test_oauth_hmac_conversion(self): token = gdata.gauth.OAuthHmacToken( 'consumerKey', 'consumerSecret', 't', 'secret', gdata.gauth.REQUEST_TOKEN, 'http://example.com/next', 'verifier') blob = gdata.gauth.token_to_blob(token) self.assertEqual( blob, '1h|consumerKey|consumerSecret|t|secret|1|http%3A%2F%2F' 'example.com%2Fnext|verifier') copy = gdata.gauth.token_from_blob(blob) self.assert_(isinstance(copy, gdata.gauth.OAuthHmacToken)) self.assertEqual(copy.consumer_key, token.consumer_key) self.assertEqual(copy.consumer_secret, token.consumer_secret) self.assertEqual(copy.token, token.token) self.assertEqual(copy.token_secret, token.token_secret) self.assertEqual(copy.auth_state, token.auth_state) self.assertEqual(copy.next, token.next) self.assertEqual(copy.verifier, token.verifier) token = gdata.gauth.OAuthHmacToken( consumer_secret='c,s', token='t', token_secret='secret', auth_state=7, verifier='v', consumer_key=None) blob = gdata.gauth.token_to_blob(token) self.assertEqual(blob, '1h||c%2Cs|t|secret|7||v') copy = gdata.gauth.token_from_blob(blob) self.assert_(isinstance(copy, gdata.gauth.OAuthHmacToken)) self.assertEqual(copy.consumer_key, token.consumer_key) self.assert_(copy.consumer_key is None) self.assertEqual(copy.consumer_secret, token.consumer_secret) self.assertEqual(copy.token, token.token) self.assertEqual(copy.token_secret, token.token_secret) self.assertEqual(copy.auth_state, token.auth_state) self.assertEqual(copy.next, token.next) self.assert_(copy.next is None) self.assertEqual(copy.verifier, token.verifier) def test_illegal_token_types(self): class MyToken(object): pass token = MyToken() self.assertRaises(gdata.gauth.UnsupportedTokenType, gdata.gauth.token_to_blob, token) blob = '~~z' self.assertRaises(gdata.gauth.UnsupportedTokenType, gdata.gauth.token_from_blob, blob) class OAuthHmacTokenTests(unittest.TestCase): def test_build_base_string(self): request = atom.http_core.HttpRequest('http://example.com/', 'GET') base_string = gdata.gauth.build_oauth_base_string( request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0') self.assertEqual( base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%2' '6oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_sig' 'nature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_ve' 'rsion%3D1.0') # Test using example from documentation. request = atom.http_core.HttpRequest( 'http://www.google.com/calendar/feeds/default/allcalendars/full' '?orderby=starttime', 'GET') base_string = gdata.gauth.build_oauth_base_string( request, 'example.com', '4572616e48616d6d65724c61686176', gdata.gauth.RSA_SHA1, 137131200, '1.0', token='1%2Fab3cd9j4ks73hf7g', next='http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual( base_string, 'GET&http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2Fd' 'efault%2Fallcalendars%2Ffull&oauth_callback%3Dhttp%253A%252F%252Fgo' 'oglecodesamples.com%252Foauth_playground%252Findex.php%26oauth_cons' 'umer_key%3Dexample.com%26oauth_nonce%3D4572616e48616d6d65724c616861' '76%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D13713120' '0%26oauth_token%3D1%25252Fab3cd9j4ks73hf7g%26oauth_version%3D1.0%26' 'orderby%3Dstarttime') # Test various defaults. request = atom.http_core.HttpRequest('http://eXample.COM', 'get') base_string = gdata.gauth.build_oauth_base_string( request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0') self.assertEqual( base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%2' '6oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_sig' 'nature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_ve' 'rsion%3D1.0') request = atom.http_core.HttpRequest('https://eXample.COM:443', 'get') base_string = gdata.gauth.build_oauth_base_string( request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0', 'http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual( base_string, 'GET&https%3A%2F%2Fexample.com%2F&oauth_callback%3Dhttp' '%253A%252F%252Fgooglecodesamples.com%252Foauth_playground%252Findex' '.php%26oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oau' 'th_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oa' 'uth_version%3D1.0') request = atom.http_core.HttpRequest('http://eXample.COM:443', 'get') base_string = gdata.gauth.build_oauth_base_string( request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0') self.assertEqual( base_string, 'GET&http%3A%2F%2Fexample.com%3A443%2F&oauth_callback%3' 'Doob%26oauth_consumer_key%3De' 'xample.org%26oauth_nonce%3D12345%26oauth_signature_method%3DHMAC-SH' 'A1%26oauth_timestamp%3D1246301653%26oauth_version%3D1.0') request = atom.http_core.HttpRequest( atom.http_core.Uri(host='eXample.COM'), 'GET') base_string = gdata.gauth.build_oauth_base_string( request, 'example.org', '12345', gdata.gauth.HMAC_SHA1, 1246301653, '1.0', next='oob') self.assertEqual( base_string, 'GET&http%3A%2F%2Fexample.com%2F&oauth_callback%3Doob%2' '6oauth_consumer_key%3Dexample.org%26oauth_nonce%3D12345%26oauth_sig' 'nature_method%3DHMAC-SHA1%26oauth_timestamp%3D1246301653%26oauth_ve' 'rsion%3D1.0') request = atom.http_core.HttpRequest( 'https://www.google.com/accounts/OAuthGetRequestToken', 'GET') request.uri.query['scope'] = ('https://docs.google.com/feeds/' ' http://docs.google.com/feeds/') base_string = gdata.gauth.build_oauth_base_string( request, 'anonymous', '48522759', gdata.gauth.HMAC_SHA1, 1246489532, '1.0', 'http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual( base_string, 'GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGet' 'RequestToken&oauth_callback%3Dhttp%253A%252F%252Fgooglecodesamples.' 'com%252Foauth_playground%252Findex.php%26oauth_consumer_key%3Danony' 'mous%26oauth_nonce%3D4852275' '9%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D12464895' '32%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fdocs.google.' 'com%252Ffeeds%252F%2520http%253A%252F%252Fdocs.google.com%252Ffeeds' '%252F') def test_generate_hmac_signature(self): # Use the example from the OAuth playground: # http://googlecodesamples.com/oauth_playground/ request = atom.http_core.HttpRequest( 'https://www.google.com/accounts/OAuthGetRequestToken?' 'scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F', 'GET') signature = gdata.gauth.generate_hmac_signature( request, 'anonymous', 'anonymous', '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual(signature, '5a2GPdtAY3LWYv8IdiT3wp1Coeg=') # Try the same request but with a non escaped Uri object. request = atom.http_core.HttpRequest( 'https://www.google.com/accounts/OAuthGetRequestToken', 'GET') request.uri.query['scope'] = 'http://www.blogger.com/feeds/' signature = gdata.gauth.generate_hmac_signature( request, 'anonymous', 'anonymous', '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', 'http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual(signature, '5a2GPdtAY3LWYv8IdiT3wp1Coeg=') # A different request also checked against the OAuth playground. request = atom.http_core.HttpRequest( 'https://www.google.com/accounts/OAuthGetRequestToken', 'GET') request.uri.query['scope'] = ('https://www.google.com/analytics/feeds/ ' 'http://www.google.com/base/feeds/ ' 'http://www.google.com/calendar/feeds/') signature = gdata.gauth.generate_hmac_signature( request, 'anonymous', 'anonymous', 1246491797, '33209c4d7a09be4eb1d6ff18e00f8548', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual(signature, 'kFAgTTFDIWz4/xAabIlrcZZMTq8=') class OAuthRsaTokenTests(unittest.TestCase): def test_generate_rsa_signature(self): request = atom.http_core.HttpRequest( 'https://www.google.com/accounts/OAuthGetRequestToken?' 'scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F', 'GET') signature = gdata.gauth.generate_rsa_signature( request, 'anonymous', PRIVATE_TEST_KEY, '1246491360', 'c0155b3f28697c029e7a62efff44bd46', '1.0', next='http://googlecodesamples.com/oauth_playground/index.php') self.assertEqual( signature, 'bfMantdttKaTrwoxU87JiXmMeXhAiXPiq79a5XmLlOYwwlX06Pu7CafMp7hW1fPeZtL' '4o9Sz3NvPI8GECCaZk7n5vi1EJ5/wfIQbddrC8j45joBG6gFSf4tRJct82dSyn6bd71' 'knwPZH1sKK46Y0ePJvEIDI3JDd7pRZuMM2sN8=') class OAuthHeaderTest(unittest.TestCase): def test_generate_auth_header(self): header = gdata.gauth.generate_auth_header( 'consumerkey', 1234567890, 'mynonce', 'unknown_sig_type', 'sig') self.assert_(header.startswith('OAuth')) self.assert_(header.find('oauth_nonce="mynonce"') > -1) self.assert_(header.find('oauth_timestamp="1234567890"') > -1) self.assert_(header.find('oauth_consumer_key="consumerkey"') > -1) self.assert_( header.find('oauth_signature_method="unknown_sig_type"') > -1) self.assert_(header.find('oauth_version="1.0"') > -1) self.assert_(header.find('oauth_signature="sig"') > -1) header = gdata.gauth.generate_auth_header( 'consumer/key', 1234567890, 'ab%&33', '', 'ab/+-_=') self.assert_(header.find('oauth_nonce="ab%25%2633"') > -1) self.assert_(header.find('oauth_consumer_key="consumer%2Fkey"') > -1) self.assert_(header.find('oauth_signature_method=""') > -1) self.assert_(header.find('oauth_signature="ab%2F%2B-_%3D"') > -1) class OAuthGetRequestToken(unittest.TestCase): def test_request_hmac_request_token(self): request = gdata.gauth.generate_request_for_request_token( 'anonymous', gdata.gauth.HMAC_SHA1, ['http://www.blogger.com/feeds/', 'http://www.google.com/calendar/feeds/'], consumer_secret='anonymous') request_uri = str(request.uri) self.assert_('http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F' in request_uri) self.assert_( 'http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F' in request_uri) auth_header = request.headers['Authorization'] self.assert_('oauth_consumer_key="anonymous"' in auth_header) self.assert_('oauth_signature_method="HMAC-SHA1"' in auth_header) self.assert_('oauth_version="1.0"' in auth_header) self.assert_('oauth_signature="' in auth_header) self.assert_('oauth_nonce="' in auth_header) self.assert_('oauth_timestamp="' in auth_header) def test_request_rsa_request_token(self): request = gdata.gauth.generate_request_for_request_token( 'anonymous', gdata.gauth.RSA_SHA1, ['http://www.blogger.com/feeds/', 'http://www.google.com/calendar/feeds/'], rsa_key=PRIVATE_TEST_KEY) request_uri = str(request.uri) self.assert_('http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F' in request_uri) self.assert_( 'http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F' in request_uri) auth_header = request.headers['Authorization'] self.assert_('oauth_consumer_key="anonymous"' in auth_header) self.assert_('oauth_signature_method="RSA-SHA1"' in auth_header) self.assert_('oauth_version="1.0"' in auth_header) self.assert_('oauth_signature="' in auth_header) self.assert_('oauth_nonce="' in auth_header) self.assert_('oauth_timestamp="' in auth_header) def test_extract_token_from_body(self): body = ('oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=' '%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true') token, secret = gdata.gauth.oauth_token_info_from_body(body) self.assertEqual(token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG') self.assertEqual(secret, '+4O49V9WUOkjXgpOobAtgYzy') def test_hmac_request_token_from_body(self): body = ('oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=' '%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true') request_token = gdata.gauth.hmac_token_from_body(body, 'myKey', 'mySecret', True) self.assertEqual(request_token.consumer_key, 'myKey') self.assertEqual(request_token.consumer_secret, 'mySecret') self.assertEqual(request_token.token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG') self.assertEqual(request_token.token_secret, '+4O49V9WUOkjXgpOobAtgYzy') self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN) def test_rsa_request_token_from_body(self): body = ('oauth_token=4%2F5bNFM_efIu3yN-E9RrF1KfZzOAZG&oauth_token_secret=' '%2B4O49V9WUOkjXgpOobAtgYzy&oauth_callback_confirmed=true') request_token = gdata.gauth.rsa_token_from_body(body, 'myKey', 'rsaKey', True) self.assertEqual(request_token.consumer_key, 'myKey') self.assertEqual(request_token.rsa_private_key, 'rsaKey') self.assertEqual(request_token.token, '4/5bNFM_efIu3yN-E9RrF1KfZzOAZG') self.assertEqual(request_token.token_secret, '+4O49V9WUOkjXgpOobAtgYzy') self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN) class OAuthAuthorizeToken(unittest.TestCase): def test_generate_authorization_url(self): url = gdata.gauth.generate_oauth_authorization_url('/+=aosdpikk') self.assert_(str(url).startswith( 'https://www.google.com/accounts/OAuthAuthorizeToken')) self.assert_('oauth_token=%2F%2B%3Daosdpikk' in str(url)) def test_extract_auth_token(self): url = ('http://www.example.com/test?oauth_token=' 'CKF50YzIHxCT85KMAg&oauth_verifier=123zzz') token = gdata.gauth.oauth_token_info_from_url(url) self.assertEqual(token[0], 'CKF50YzIHxCT85KMAg') self.assertEqual(token[1], '123zzz') class FindScopesForService(unittest.TestCase): def test_find_all_scopes(self): count = 0 for key, scopes in gdata.gauth.AUTH_SCOPES.iteritems(): count += len(scopes) self.assertEqual(count, len(gdata.gauth.find_scopes_for_services())) def test_single_service(self): self.assertEqual( gdata.gauth.FindScopesForServices(('codesearch',)), ['http://www.google.com/codesearch/feeds/']) def test_multiple_services(self): self.assertEqual( gdata.gauth.find_scopes_for_services(('jotspot', 'wise')), ['http://sites.google.com/feeds/', 'https://sites.google.com/feeds/', 'https://spreadsheets.google.com/feeds/', 'http://spreadsheets.google.com/feeds/']) def suite(): return conf.build_suite([AuthSubTest, TokensToAndFromBlobsTest, OAuthHmacTokenTests, OAuthRsaTokenTests, OAuthHeaderTest, OAuthGetRequestToken, OAuthAuthorizeToken, FindScopesForService]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.data from gdata import test_data import gdata.test_config as conf import atom.core import atom.data SIMPLE_V2_FEED_TEST_DATA = """<feed xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"CUMBRHo_fip7ImA9WxRbGU0."'> <title>Elizabeth Bennet's Contacts</title> <link rel='next' type='application/atom+xml' href='http://www.google.com/m8/feeds/contacts/.../more' /> <entry gd:etag='"Qn04eTVSLyp7ImA9WxRbGEUORAQ."'> <id>http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/c9e</id> <title>Fitzwilliam</title> <link rel='http://schemas.google.com/contacts/2008/rel#photo' type='image/*' href='http://www.google.com/m8/feeds/photos/media/liz%40gmail.com/c9e' gd:etag='"KTlcZWs1bCp7ImBBPV43VUV4LXEZCXERZAc."' /> <link rel='self' type='application/atom+xml' href='Changed to ensure we are really getting the edit URL.'/> <link rel='edit' type='application/atom+xml' href='http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9e'/> </entry> <entry gd:etag='&quot;123456&quot;'> <link rel='edit' href='http://example.com/1' /> </entry> </feed>""" XML_ENTRY_1 = """<?xml version='1.0'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:g='http://base.google.com/ns/1.0'> <category scheme="http://base.google.com/categories/itemtypes" term="products"/> <id> http://www.google.com/test/id/url </id> <title type='text'>Testing 2000 series laptop</title> <content type='xhtml'> <div xmlns='http://www.w3.org/1999/xhtml'>A Testing Laptop</div> </content> <link rel='alternate' type='text/html' href='http://www.provider-host.com/123456789'/> <link rel='license' href='http://creativecommons.org/licenses/by-nc/2.5/rdf'/> <g:label>Computer</g:label> <g:label>Laptop</g:label> <g:label>testing laptop</g:label> <g:item_type>products</g:item_type> </entry>""" def parse(xml_string, target_class): """Convenience wrapper for converting an XML string to an XmlElement.""" return atom.core.xml_element_from_string(xml_string, target_class) class StartIndexTest(unittest.TestCase): def setUp(self): self.start_index = gdata.data.StartIndex() def testToAndFromString(self): self.start_index.text = '1' self.assert_(self.start_index.text == '1') new_start_index = parse(self.start_index.ToString(), gdata.data.StartIndex) self.assert_(self.start_index.text == new_start_index.text) class ItemsPerPageTest(unittest.TestCase): def setUp(self): self.items_per_page = gdata.data.ItemsPerPage() def testToAndFromString(self): self.items_per_page.text = '10' self.assert_(self.items_per_page.text == '10') new_items_per_page = parse(self.items_per_page.ToString(), gdata.data.ItemsPerPage) self.assert_(self.items_per_page.text == new_items_per_page.text) class GDataEntryTest(unittest.TestCase): def testIdShouldBeCleaned(self): entry = parse(XML_ENTRY_1, gdata.data.GDEntry) tree = parse(XML_ENTRY_1, atom.core.XmlElement) self.assert_(tree.get_elements('id', 'http://www.w3.org/2005/Atom')[0].text != entry.get_id()) self.assertEqual(entry.get_id(), 'http://www.google.com/test/id/url') def testGeneratorShouldBeCleaned(self): feed = parse(test_data.GBASE_FEED, gdata.data.GDFeed) tree = parse(test_data.GBASE_FEED, atom.core.XmlElement) self.assert_(tree.get_elements('generator', 'http://www.w3.org/2005/Atom')[0].text != feed.get_generator()) self.assertEqual(feed.get_generator(), 'GoogleBase') def testAllowsEmptyId(self): entry = gdata.data.GDEntry() try: entry.id = atom.data.Id() except AttributeError: self.fail('Empty id should not raise an attribute error.') class LinkFinderTest(unittest.TestCase): def setUp(self): self.entry = parse(XML_ENTRY_1, gdata.data.GDEntry) def testLinkFinderGetsLicenseLink(self): self.assertEquals(isinstance(self.entry.FindLicenseLink(), str), True) self.assertEquals(self.entry.FindLicenseLink(), 'http://creativecommons.org/licenses/by-nc/2.5/rdf') def testLinkFinderGetsAlternateLink(self): self.assert_(isinstance(self.entry.FindAlternateLink(), str)) self.assertEquals(self.entry.FindAlternateLink(), 'http://www.provider-host.com/123456789') def testFindAclLink(self): entry = gdata.data.GDEntry() self.assert_(entry.get_acl_link() is None) self.assert_(entry.find_acl_link() is None) entry.link.append(atom.data.Link( rel=gdata.data.ACL_REL, href='http://example.com/acl')) self.assertEqual(entry.get_acl_link().href, 'http://example.com/acl') self.assertEqual(entry.find_acl_link(), 'http://example.com/acl') del entry.link[0] self.assert_(entry.get_acl_link() is None) self.assert_(entry.find_acl_link() is None) # We should also find an ACL link which is a feed_link. entry.feed_link = [gdata.data.FeedLink( rel=gdata.data.ACL_REL, href='http://example.com/acl2')] self.assertEqual(entry.get_acl_link().href, 'http://example.com/acl2') self.assertEqual(entry.find_acl_link(), 'http://example.com/acl2') class GDataFeedTest(unittest.TestCase): def testCorrectConversionToElementTree(self): test_feed = parse(test_data.GBASE_FEED, gdata.data.GDFeed) self.assert_(test_feed.total_results is not None) self.assert_(test_feed.get_elements('totalResults', 'http://a9.com/-/spec/opensearchrss/1.0/') is not None) self.assert_(len(test_feed.get_elements('totalResults', 'http://a9.com/-/spec/opensearchrss/1.0/')) > 0) def testAllowsEmptyId(self): feed = gdata.data.GDFeed() try: feed.id = atom.data.Id() except AttributeError: self.fail('Empty id should not raise an attribute error.') class BatchEntryTest(unittest.TestCase): def testCorrectConversionFromAndToString(self): batch_entry = parse(test_data.BATCH_ENTRY, gdata.data.BatchEntry) self.assertEquals(batch_entry.batch_id.text, 'itemB') self.assertEquals(batch_entry.id.text, 'http://www.google.com/base/feeds/items/' '2173859253842813008') self.assertEquals(batch_entry.batch_operation.type, 'insert') self.assertEquals(batch_entry.batch_status.code, '201') self.assertEquals(batch_entry.batch_status.reason, 'Created') new_entry = parse(str(batch_entry), gdata.data.BatchEntry) self.assertEquals(batch_entry.batch_id.text, new_entry.batch_id.text) self.assertEquals(batch_entry.id.text, new_entry.id.text) self.assertEquals(batch_entry.batch_operation.type, new_entry.batch_operation.type) self.assertEquals(batch_entry.batch_status.code, new_entry.batch_status.code) self.assertEquals(batch_entry.batch_status.reason, new_entry.batch_status.reason) class BatchFeedTest(unittest.TestCase): def setUp(self): self.batch_feed = gdata.data.BatchFeed() self.example_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/1'), text='This is a test') def testConvertRequestFeed(self): batch_feed = parse(test_data.BATCH_FEED_REQUEST, gdata.data.BatchFeed) self.assertEquals(len(batch_feed.entry), 4) for entry in batch_feed.entry: self.assert_(isinstance(entry, gdata.data.BatchEntry)) self.assertEquals(batch_feed.title.text, 'My Batch Feed') new_feed = parse(batch_feed.to_string(), gdata.data.BatchFeed) self.assertEquals(len(new_feed.entry), 4) for entry in new_feed.entry: self.assert_(isinstance(entry, gdata.data.BatchEntry)) self.assertEquals(new_feed.title.text, 'My Batch Feed') def testConvertResultFeed(self): batch_feed = parse(test_data.BATCH_FEED_RESULT, gdata.data.BatchFeed) self.assertEquals(len(batch_feed.entry), 4) for entry in batch_feed.entry: self.assert_(isinstance(entry, gdata.data.BatchEntry)) if entry.id.text == ('http://www.google.com/base/feeds/items/' '2173859253842813008'): self.assertEquals(entry.batch_operation.type, 'insert') self.assertEquals(entry.batch_id.text, 'itemB') self.assertEquals(entry.batch_status.code, '201') self.assertEquals(entry.batch_status.reason, 'Created') self.assertEquals(batch_feed.title.text, 'My Batch') new_feed = parse(str(batch_feed), gdata.data.BatchFeed) self.assertEquals(len(new_feed.entry), 4) for entry in new_feed.entry: self.assert_(isinstance(entry, gdata.data.BatchEntry)) if entry.id.text == ('http://www.google.com/base/feeds/items/' '2173859253842813008'): self.assertEquals(entry.batch_operation.type, 'insert') self.assertEquals(entry.batch_id.text, 'itemB') self.assertEquals(entry.batch_status.code, '201') self.assertEquals(entry.batch_status.reason, 'Created') self.assertEquals(new_feed.title.text, 'My Batch') def testAddBatchEntry(self): try: self.batch_feed.AddBatchEntry(batch_id_string='a') self.fail('AddBatchEntry with neither entry or URL should raise Error') except gdata.data.MissingRequiredParameters: pass new_entry = self.batch_feed.AddBatchEntry( id_url_string='http://example.com/1') self.assertEquals(len(self.batch_feed.entry), 1) self.assertEquals(self.batch_feed.entry[0].get_id(), 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0') self.assertEquals(new_entry.id.text, 'http://example.com/1') self.assertEquals(new_entry.batch_id.text, '0') to_add = gdata.data.BatchEntry(id=atom.data.Id(text='originalId')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, batch_id_string='foo') self.assertEquals(new_entry.batch_id.text, 'foo') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.data.BatchEntry(id=atom.data.Id(text='originalId'), batch_id=gdata.data.BatchId(text='bar')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId', batch_id_string='foo') self.assertEquals(new_entry.batch_id.text, 'foo') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.data.BatchEntry(id=atom.data.Id(text='originalId'), batch_id=gdata.data.BatchId(text='bar')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId') self.assertEquals(new_entry.batch_id.text, 'bar') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.data.BatchEntry(id=atom.data.Id(text='originalId'), batch_id=gdata.data.BatchId(text='bar'), batch_operation=gdata.data.BatchOperation( type=gdata.data.BATCH_INSERT)) self.assertEquals(to_add.batch_operation.type, gdata.data.BATCH_INSERT) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId', batch_id_string='foo', operation_string=gdata.data.BATCH_UPDATE) self.assertEquals(new_entry.batch_operation.type, gdata.data.BATCH_UPDATE) def testAddInsert(self): first_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/1'), text='This is a test1') self.batch_feed.AddInsert(first_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0') second_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/2'), text='This is a test2') self.batch_feed.AddInsert(second_entry, batch_id_string='foo') self.assertEquals(self.batch_feed.entry[1].batch_operation.type, gdata.data.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[1].batch_id.text, 'foo') third_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/3'), text='This is a test3') third_entry.batch_operation = gdata.data.BatchOperation( type=gdata.data.BATCH_DELETE) # Add an entry with a delete operation already assigned. self.batch_feed.AddInsert(third_entry) # The batch entry should not have the original operation, it should # have been changed to an insert. self.assertEquals(self.batch_feed.entry[2].batch_operation.type, gdata.data.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[2].batch_id.text, '2') def testAddDelete(self): # Try deleting an entry delete_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/1'), text='This is a test') self.batch_feed.AddDelete(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_DELETE) self.assertEquals(self.batch_feed.entry[0].get_id(), 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].text, 'This is a test') # Try deleting a URL self.batch_feed.AddDelete(url_string='http://example.com/2') self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_DELETE) self.assertEquals(self.batch_feed.entry[1].id.text, 'http://example.com/2') self.assert_(self.batch_feed.entry[1].text is None) def testAddQuery(self): # Try querying with an existing batch entry delete_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/1')) self.batch_feed.AddQuery(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_QUERY) self.assertEquals(self.batch_feed.entry[0].get_id(), 'http://example.com/1') # Try querying a URL self.batch_feed.AddQuery(url_string='http://example.com/2') self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_QUERY) self.assertEquals(self.batch_feed.entry[1].id.text, 'http://example.com/2') def testAddUpdate(self): # Try updating an entry delete_entry = gdata.data.BatchEntry( id=atom.data.Id(text='http://example.com/1'), text='This is a test') self.batch_feed.AddUpdate(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.data.BATCH_UPDATE) self.assertEquals(self.batch_feed.entry[0].get_id(), 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].text, 'This is a test') class ExtendedPropertyTest(unittest.TestCase): def testXmlBlobRoundTrip(self): ep = gdata.data.ExtendedProperty(name='blobby') ep.SetXmlBlob('<some_xml attr="test"/>') extension = ep.GetXmlBlob() self.assertEquals(extension.tag, 'some_xml') self.assert_(extension.namespace is None) self.assertEquals(extension.attributes['attr'], 'test') ep2 = parse(ep.ToString(), gdata.data.ExtendedProperty) extension = ep2.GetXmlBlob() self.assertEquals(extension.tag, 'some_xml') self.assert_(extension.namespace is None) self.assertEquals(extension.attributes['attr'], 'test') def testGettersShouldReturnNoneWithNoBlob(self): ep = gdata.data.ExtendedProperty(name='no blob') self.assert_(ep.GetXmlBlob() is None) def testGettersReturnCorrectTypes(self): ep = gdata.data.ExtendedProperty(name='has blob') ep.SetXmlBlob('<some_xml attr="test"/>') self.assert_(isinstance(ep.GetXmlBlob(), atom.core.XmlElement)) self.assert_(isinstance(ep.GetXmlBlob().to_string(), str)) class FeedLinkTest(unittest.TestCase): def testCorrectFromStringType(self): link = parse( '<feedLink xmlns="http://schemas.google.com/g/2005" countHint="5"/>', gdata.data.FeedLink) self.assert_(isinstance(link, gdata.data.FeedLink)) self.assertEqual(link.count_hint, '5') class SimpleV2FeedTest(unittest.TestCase): def test_parsing_etags_and_edit_url(self): feed = atom.core.parse(SIMPLE_V2_FEED_TEST_DATA, gdata.data.GDFeed) # General parsing assertions. self.assertEqual(feed.get_elements('title')[0].text, 'Elizabeth Bennet\'s Contacts') self.assertEqual(len(feed.entry), 2) for entry in feed.entry: self.assert_(isinstance(entry, gdata.data.GDEntry)) self.assertEqual(feed.entry[0].GetElements('title')[0].text, 'Fitzwilliam') self.assertEqual(feed.entry[0].get_elements('id')[0].text, 'http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base/c9e') # ETags checks. self.assertEqual(feed.etag, 'W/"CUMBRHo_fip7ImA9WxRbGU0."') self.assertEqual(feed.entry[0].etag, '"Qn04eTVSLyp7ImA9WxRbGEUORAQ."') self.assertEqual(feed.entry[1].etag, '"123456"') # Look for Edit URLs. self.assertEqual(feed.entry[0].find_edit_link(), 'http://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/c9e') self.assertEqual(feed.entry[1].FindEditLink(), 'http://example.com/1') # Look for Next URLs. self.assertEqual(feed.find_next_link(), 'http://www.google.com/m8/feeds/contacts/.../more') def test_constructor_defauls(self): feed = gdata.data.GDFeed() self.assert_(feed.etag is None) self.assertEqual(feed.link, []) self.assertEqual(feed.entry, []) entry = gdata.data.GDEntry() self.assert_(entry.etag is None) self.assertEqual(entry.link, []) link = atom.data.Link() self.assert_(link.href is None) self.assert_(link.rel is None) link1 = atom.data.Link(href='http://example.com', rel='test') self.assertEqual(link1.href, 'http://example.com') self.assertEqual(link1.rel, 'test') link2 = atom.data.Link(href='http://example.org/', rel='alternate') entry = gdata.data.GDEntry(etag='foo', link=[link1, link2]) feed = gdata.data.GDFeed(etag='12345', entry=[entry]) self.assertEqual(feed.etag, '12345') self.assertEqual(len(feed.entry), 1) self.assertEqual(feed.entry[0].etag, 'foo') self.assertEqual(len(feed.entry[0].link), 2) class DataClassSanityTest(unittest.TestCase): def test_basic_element_structure(self): conf.check_data_classes(self, [ gdata.data.TotalResults, gdata.data.StartIndex, gdata.data.ItemsPerPage, gdata.data.ExtendedProperty, gdata.data.GDEntry, gdata.data.GDFeed, gdata.data.BatchId, gdata.data.BatchOperation, gdata.data.BatchStatus, gdata.data.BatchEntry, gdata.data.BatchInterrupted, gdata.data.BatchFeed, gdata.data.EntryLink, gdata.data.FeedLink, gdata.data.AdditionalName, gdata.data.Comments, gdata.data.Country, gdata.data.Email, gdata.data.FamilyName, gdata.data.Im, gdata.data.GivenName, gdata.data.NamePrefix, gdata.data.NameSuffix, gdata.data.FullName, gdata.data.Name, gdata.data.OrgDepartment, gdata.data.OrgName, gdata.data.OrgSymbol, gdata.data.OrgTitle, gdata.data.Organization, gdata.data.When, gdata.data.Who, gdata.data.OriginalEvent, gdata.data.PhoneNumber, gdata.data.PostalAddress, gdata.data.Rating, gdata.data.Recurrence, gdata.data.RecurrenceException, gdata.data.Reminder, gdata.data.Agent, gdata.data.HouseName, gdata.data.Street, gdata.data.PoBox, gdata.data.Neighborhood, gdata.data.City, gdata.data.Subregion, gdata.data.Region, gdata.data.Postcode, gdata.data.Country, gdata.data.FormattedAddress, gdata.data.StructuredPostalAddress, gdata.data.Where, gdata.data.AttendeeType, gdata.data.AttendeeStatus]) def test_member_values(self): self.assertEqual( gdata.data.TotalResults._qname, ('{http://a9.com/-/spec/opensearchrss/1.0/}totalResults', '{http://a9.com/-/spec/opensearch/1.1/}totalResults')) self.assertEqual( gdata.data.RecurrenceException._qname, '{http://schemas.google.com/g/2005}recurrenceException') self.assertEqual(gdata.data.RecurrenceException.specialized, 'specialized') def suite(): return conf.build_suite([StartIndexTest, StartIndexTest, GDataEntryTest, LinkFinderTest, GDataFeedTest, BatchEntryTest, BatchFeedTest, ExtendedPropertyTest, FeedLinkTest, SimpleV2FeedTest, DataClassSanityTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata import gdata.spreadsheet SPREADSHEETS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <id>http://spreadsheets.google.com/feeds/spreadsheets/private/full</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Available Spreadsheets</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:totalResults>1</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>1</openSearch:itemsPerPage> <entry> <id>http://spreadsheets.google.com/feeds/spreadsheets/private/full/key</id> <updated>2006-11-17T18:24:18.231Z</updated> <title type="text">Groceries R Us</title> <content type="text">Groceries R Us</content> <link rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/spreadsheets/private/full/key"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> </entry> </feed> """ WORKSHEETS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <id>http://spreadsheets.google.com/feeds/worksheets/key/private/full</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Groceries R Us</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:totalResults>1</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>1</openSearch:itemsPerPage> <entry> <id>http://spreadsheets.google.com/feeds/worksheets/key/private/full/od6</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Sheet1</title> <content type="text">Sheet1</content> <link rel="http://schemas.google.com/spreadsheets/2006#listfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full"/> <link rel="http://schemas.google.com/spreadsheets/2006#cellsfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full/od6"/> <gs:rowCount>100</gs:rowCount> <gs:colCount>20</gs:colCount> </entry> </feed> """ CELLS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <id>http://spreadsheets.google.com/feeds/cells/key/od6/private/full</id> <updated>2006-11-17T18:27:32.543Z</updated> <title type="text">Sheet1</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full"/> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>1</openSearch:itemsPerPage> <gs:rowCount>100</gs:rowCount> <gs:colCount>20</gs:colCount> <entry> <id>http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C1</id> <updated>2006-11-17T18:27:32.543Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell"/> <title type="text">A1</title> <content type="text">Name</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C1"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C1/bgvjf"/> <gs:cell row="1" col="1" inputValue="Name">Name</gs:cell> </entry> <entry> <id>http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C2</id> <updated>2006-11-17T18:27:32.543Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell"/> <title type="text">B1</title> <content type="text">Hours</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C2"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/key/od6/private/full/R1C2/1pn567"/> <gs:cell row="1" col="2" inputValue="Hours">Hours</gs:cell> </entry> </feed> """ LIST_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <id>http://spreadsheets.google.com/feeds/list/key/od6/private/full</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Sheet1</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full"/> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:totalResults>2</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>2</openSearch:itemsPerPage> <entry> <id>http://spreadsheets.google.com/feeds/list/key/od6/private/full/cokwr</id> <updated>2006-11-17T18:23:45.173Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#list"/> <title type="text">Bingley</title> <content type="text">Hours: 10, Items: 2, IPM: 0.0033</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full/cokwr"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full/cokwr/2ehkc2oh7d"/> <gsx:name>Bingley</gsx:name> <gsx:hours>10</gsx:hours> <gsx:items>2</gsx:items> <gsx:ipm>0.0033</gsx:ipm> </entry> <entry> <id>http://spreadsheets.google.com/feeds/list/key/od6/private/full/cyevm</id> <updated>2006-11-17T18:23:45.173Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#list"/> <title type="text">Charlotte</title> <content type="text">Hours: 60, Items: 18000, IPM: 5</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full/cyevm"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/key/od6/private/full/cyevm/64rl27px3zyn"/> <gsx:name>Charlotte</gsx:name> <gsx:hours>60</gsx:hours> <gsx:items>18000</gsx:items> <gsx:ipm>5</gsx:ipm> </entry> </feed> """ class ColCountTest(unittest.TestCase): def setUp(self): self.col_count = gdata.spreadsheet.ColCount() def testToAndFromString(self): self.col_count.text = '20' self.assert_(self.col_count.text == '20') new_col_count = gdata.spreadsheet.ColCountFromString(self.col_count.ToString()) self.assert_(self.col_count.text == new_col_count.text) class RowCountTest(unittest.TestCase): def setUp(self): self.row_count = gdata.spreadsheet.RowCount() def testToAndFromString(self): self.row_count.text = '100' self.assert_(self.row_count.text == '100') new_row_count = gdata.spreadsheet.RowCountFromString(self.row_count.ToString()) self.assert_(self.row_count.text == new_row_count.text) class CellTest(unittest.TestCase): def setUp(self): self.cell = gdata.spreadsheet.Cell() def testToAndFromString(self): self.cell.text = 'test cell' self.assert_(self.cell.text == 'test cell') self.cell.row = '1' self.assert_(self.cell.row == '1') self.cell.col = '2' self.assert_(self.cell.col == '2') self.cell.inputValue = 'test input value' self.assert_(self.cell.inputValue == 'test input value') self.cell.numericValue = 'test numeric value' self.assert_(self.cell.numericValue == 'test numeric value') new_cell = gdata.spreadsheet.CellFromString(self.cell.ToString()) self.assert_(self.cell.text == new_cell.text) self.assert_(self.cell.row == new_cell.row) self.assert_(self.cell.col == new_cell.col) self.assert_(self.cell.inputValue == new_cell.inputValue) self.assert_(self.cell.numericValue == new_cell.numericValue) class CustomTest(unittest.TestCase): def setUp(self): self.custom = gdata.spreadsheet.Custom() def testToAndFromString(self): self.custom.text = 'value' self.custom.column = 'column_name' self.assert_(self.custom.text == 'value') self.assert_(self.custom.column == 'column_name') new_custom = gdata.spreadsheet.CustomFromString(self.custom.ToString()) self.assert_(self.custom.text == new_custom.text) self.assert_(self.custom.column == new_custom.column) class SpreadsheetsWorksheetTest(unittest.TestCase): def setUp(self): self.worksheet = gdata.spreadsheet.SpreadsheetsWorksheet() def testToAndFromString(self): self.worksheet.row_count = gdata.spreadsheet.RowCount(text='100') self.assert_(self.worksheet.row_count.text == '100') self.worksheet.col_count = gdata.spreadsheet.ColCount(text='20') self.assert_(self.worksheet.col_count.text == '20') new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheetFromString( self.worksheet.ToString()) self.assert_(self.worksheet.row_count.text == new_worksheet.row_count.text) self.assert_(self.worksheet.col_count.text == new_worksheet.col_count.text) class SpreadsheetsCellTest(unittest.TestCase): def setUp(self): self.entry = gdata.spreadsheet.SpreadsheetsCell() def testToAndFromString(self): self.entry.cell = gdata.spreadsheet.Cell(text='my cell', row='1', col='2', inputValue='my input value', numericValue='my numeric value') self.assert_(self.entry.cell.text == 'my cell') self.assert_(self.entry.cell.row == '1') self.assert_(self.entry.cell.col == '2') self.assert_(self.entry.cell.inputValue == 'my input value') self.assert_(self.entry.cell.numericValue == 'my numeric value') new_cell = gdata.spreadsheet.SpreadsheetsCellFromString(self.entry.ToString()) self.assert_(self.entry.cell.text == new_cell.cell.text) self.assert_(self.entry.cell.row == new_cell.cell.row) self.assert_(self.entry.cell.col == new_cell.cell.col) self.assert_(self.entry.cell.inputValue == new_cell.cell.inputValue) self.assert_(self.entry.cell.numericValue == new_cell.cell.numericValue) class SpreadsheetsListTest(unittest.TestCase): def setUp(self): self.row = gdata.spreadsheet.SpreadsheetsList() def testToAndFromString(self): self.row.custom['column_1'] = gdata.spreadsheet.Custom(column='column_1', text='my first column') self.row.custom['column_2'] = gdata.spreadsheet.Custom(column='column_2', text='my second column') self.assert_(self.row.custom['column_1'].column == 'column_1') self.assert_(self.row.custom['column_1'].text == 'my first column') self.assert_(self.row.custom['column_2'].column == 'column_2') self.assert_(self.row.custom['column_2'].text == 'my second column') new_row = gdata.spreadsheet.SpreadsheetsListFromString(self.row.ToString()) self.assert_(self.row.custom['column_1'].column == new_row.custom['column_1'].column) self.assert_(self.row.custom['column_1'].text == new_row.custom['column_1'].text) self.assert_(self.row.custom['column_2'].column == new_row.custom['column_2'].column) self.assert_(self.row.custom['column_2'].text == new_row.custom['column_2'].text) class SpreadsheetsSpreadsheetsFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.spreadsheet.SpreadsheetSpreadsheetsFeed() self.feed = gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString( SPREADSHEETS_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 1) for an_entry in self.feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsSpreadsheet)) new_feed = gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString( str(self.feed)) for an_entry in new_feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsSpreadsheet)) class SpreadsheetsWorksheetsFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.spreadsheet.SpreadsheetWorksheetsFeed() self.feed = gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString( WORKSHEETS_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 1) for an_entry in self.feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsWorksheet)) new_feed = gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString( str(self.feed)) for an_entry in new_feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsWorksheet)) class SpreadsheetsCellsFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.spreadsheet.SpreadsheetCellsFeed() self.feed = gdata.spreadsheet.SpreadsheetsCellsFeedFromString( CELLS_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 2) for an_entry in self.feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsCell)) new_feed = gdata.spreadsheet.SpreadsheetsCellsFeedFromString(str(self.feed)) self.assert_(isinstance(new_feed.row_count, gdata.spreadsheet.RowCount)) self.assert_(new_feed.row_count.text == '100') self.assert_(isinstance(new_feed.col_count, gdata.spreadsheet.ColCount)) self.assert_(new_feed.col_count.text == '20') for an_entry in new_feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsCell)) class SpreadsheetsListFeedTest(unittest.TestCase): def setUp(self): #self.item_feed = gdata.spreadsheet.SpreadsheetListFeed() self.feed = gdata.spreadsheet.SpreadsheetsListFeedFromString( LIST_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 2) for an_entry in self.feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsList)) new_feed = gdata.spreadsheet.SpreadsheetsListFeedFromString(str(self.feed)) for an_entry in new_feed.entry: self.assert_(isinstance(an_entry, gdata.spreadsheet.SpreadsheetsList)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2007, 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import re import unittest import urllib import gdata.auth CONSUMER_KEY = 'www.yourwebapp.com' CONSUMER_SECRET = 'qB1P2kCFDpRjF+/Iww4' RSA_KEY = """-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDVbOaFW+KXecfFJn1PIzYHnNXFxhaQ36QM0K5uSb0Y8NeQUlD2 6t8aKgnm6mcb4vaopHjjdIGWgAzM5Dt0oPIiDXo+jSQbvCIXRduuAt+0cFGb2d+L hALk4AwB8IVIkDJWwgo5Z2OLsP2r/wQlUYKm/tnvQaevK24jNYMLWVJl2QIDAQAB AoGAU93ERBlUVEPFjaJPUX67p4gotNvfWDSZiXOjZ7FQPnG9s3e1WyH2Y5irZXMs 61dnp+NhobfRiGtvHEB/YJgyLRk/CJDnMKslo95e7o65IE9VkcyY6Yvt7YTslsRX Eu7T0xLEA7ON46ypCwNLeWxpJ9SWisEKu2yZJnWauCXEsgUCQQD7b2ZuhGx3msoP YEnwvucp0UxneCvb68otfERZ1J6NfNP47QJw6OwD3r1sWCJ27QZmpvtQH1f8sCk9 t22anGG7AkEA2UzXdtQ8H1uLAN/XXX2qoLuvJK5jRswHS4GeOg4pnnDSiHg3Vbva AxmMIL93ufvIy/xdoENwDPfcI4CbYlrDewJAGWy7W+OSIEoLsqBW+bwkHetnIXNa ZAOkzxKoyrigS8hamupEe+xhqUaFuwXyfjobkpfCA+kXeZrKoM4CjEbR7wJAHMbf Vd4/ZAu0edYq6DenLAgO5rWtcge9A5PTx25utovMZcQ917273mM4unGAwoGEkvcF 0x57LUx5u73hVgIdFwJBAKWGuHRwGPgTWYvhpHM0qveH+8KdU9BUt/kV4ONxIVDB ftetEmJirqOGLECbImoLcUwQrgfMW4ZCxOioJMz/gY0= -----END RSA PRIVATE KEY----- """ class AuthModuleUtilitiesTest(unittest.TestCase): def testGenerateClientLoginRequestBody(self): body = gdata.auth.GenerateClientLoginRequestBody('jo@gmail.com', 'password', 'test service', 'gdata.auth test') expected_parameters = {'Email':r'jo%40gmail.com', 'Passwd':'password', 'service':'test+service', 'source':'gdata.auth+test', 'accountType':'HOSTED_OR_GOOGLE'} self.__matchBody(body, expected_parameters) body = gdata.auth.GenerateClientLoginRequestBody('jo@gmail.com', 'password', 'test service', 'gdata.auth test', account_type='A TEST', captcha_token='12345', captcha_response='test') expected_parameters['accountType'] = 'A+TEST' expected_parameters['logintoken'] = '12345' expected_parameters['logincaptcha'] = 'test' self.__matchBody(body, expected_parameters) def __matchBody(self, body, expected_name_value_pairs): parameters = body.split('&') for param in parameters: (name, value) = param.split('=') self.assert_(expected_name_value_pairs[name] == value) def testGenerateClientLoginAuthToken(self): http_body = ('SID=DQAAAGgA7Zg8CTN\r\n' 'LSID=DQAAAGsAlk8BBbG\r\n' 'Auth=DQAAAGgAdk3fA5N') self.assert_(gdata.auth.GenerateClientLoginAuthToken(http_body) == 'GoogleLogin auth=DQAAAGgAdk3fA5N') class GenerateClientLoginRequestBodyTest(unittest.TestCase): def testPostBodyShouldMatchShortExample(self): auth_body = gdata.auth.GenerateClientLoginRequestBody('johndoe@gmail.com', 'north23AZ', 'cl', 'Gulp-CalGulp-1.05') self.assert_(-1 < auth_body.find('Email=johndoe%40gmail.com')) self.assert_(-1 < auth_body.find('Passwd=north23AZ')) self.assert_(-1 < auth_body.find('service=cl')) self.assert_(-1 < auth_body.find('source=Gulp-CalGulp-1.05')) def testPostBodyShouldMatchLongExample(self): auth_body = gdata.auth.GenerateClientLoginRequestBody('johndoe@gmail.com', 'north23AZ', 'cl', 'Gulp-CalGulp-1.05', captcha_token='DQAAAGgA...dkI1', captcha_response='brinmar') self.assert_(-1 < auth_body.find('logintoken=DQAAAGgA...dkI1')) self.assert_(-1 < auth_body.find('logincaptcha=brinmar')) def testEquivalenceWithOldLogic(self): email = 'jo@gmail.com' password = 'password' account_type = 'HOSTED' service = 'test' source = 'auth test' old_request_body = urllib.urlencode({'Email': email, 'Passwd': password, 'accountType': account_type, 'service': service, 'source': source}) new_request_body = gdata.auth.GenerateClientLoginRequestBody(email, password, service, source, account_type=account_type) for parameter in old_request_body.split('&'): self.assert_(-1 < new_request_body.find(parameter)) class GenerateAuthSubUrlTest(unittest.TestCase): def testDefaultParameters(self): url = gdata.auth.GenerateAuthSubUrl('http://example.com/xyz?x=5', 'http://www.google.com/test/feeds') self.assert_(-1 < url.find( r'scope=http%3A%2F%2Fwww.google.com%2Ftest%2Ffeeds')) self.assert_(-1 < url.find( r'next=http%3A%2F%2Fexample.com%2Fxyz%3Fx%3D5')) self.assert_(-1 < url.find('secure=0')) self.assert_(-1 < url.find('session=1')) def testAllParameters(self): url = gdata.auth.GenerateAuthSubUrl('http://example.com/xyz?x=5', 'http://www.google.com/test/feeds', secure=True, session=False, request_url='https://example.com/auth') self.assert_(-1 < url.find( r'scope=http%3A%2F%2Fwww.google.com%2Ftest%2Ffeeds')) self.assert_(-1 < url.find( r'next=http%3A%2F%2Fexample.com%2Fxyz%3Fx%3D5')) self.assert_(-1 < url.find('secure=1')) self.assert_(-1 < url.find('session=0')) self.assert_(url.startswith('https://example.com/auth')) class GenerateOAuthRequestTokenUrlTest(unittest.TestCase): def testDefaultParameters(self): oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY) scopes = [ 'http://abcd.example.com/feeds', 'http://www.example.com/abcd/feeds' ] url = gdata.auth.GenerateOAuthRequestTokenUrl( oauth_input_params, scopes=scopes) self.assertEquals('https', url.protocol) self.assertEquals('www.google.com', url.host) self.assertEquals('/accounts/OAuthGetRequestToken', url.path) self.assertEquals('1.0', url.params['oauth_version']) self.assertEquals('RSA-SHA1', url.params['oauth_signature_method']) self.assert_(url.params['oauth_nonce']) self.assert_(url.params['oauth_timestamp']) actual_scopes = url.params['scope'].split(' ') self.assertEquals(2, len(actual_scopes)) for scope in actual_scopes: self.assert_(scope in scopes) self.assertEquals(CONSUMER_KEY, url.params['oauth_consumer_key']) self.assert_(url.params['oauth_signature']) def testAllParameters(self): oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) scopes = ['http://abcd.example.com/feeds'] url = gdata.auth.GenerateOAuthRequestTokenUrl( oauth_input_params, scopes=scopes, request_token_url='https://www.example.com/accounts/OAuthRequestToken', extra_parameters={'oauth_version': '2.0', 'my_param': 'my_value'}) self.assertEquals('https', url.protocol) self.assertEquals('www.example.com', url.host) self.assertEquals('/accounts/OAuthRequestToken', url.path) self.assertEquals('2.0', url.params['oauth_version']) self.assertEquals('HMAC-SHA1', url.params['oauth_signature_method']) self.assert_(url.params['oauth_nonce']) self.assert_(url.params['oauth_timestamp']) actual_scopes = url.params['scope'].split(' ') self.assertEquals(1, len(actual_scopes)) for scope in actual_scopes: self.assert_(scope in scopes) self.assertEquals(CONSUMER_KEY, url.params['oauth_consumer_key']) self.assert_(url.params['oauth_signature']) self.assertEquals('my_value', url.params['my_param']) class GenerateOAuthAuthorizationUrlTest(unittest.TestCase): def testDefaultParameters(self): token_key = 'ABCDDSFFDSG' token_secret = 'SDFDSGSDADADSAF' request_token = gdata.auth.OAuthToken(key=token_key, secret=token_secret) url = gdata.auth.GenerateOAuthAuthorizationUrl(request_token) self.assertEquals('https', url.protocol) self.assertEquals('www.google.com', url.host) self.assertEquals('/accounts/OAuthAuthorizeToken', url.path) self.assertEquals(token_key, url.params['oauth_token']) def testAllParameters(self): token_key = 'ABCDDSFFDSG' token_secret = 'SDFDSGSDADADSAF' scopes = [ 'http://abcd.example.com/feeds', 'http://www.example.com/abcd/feeds' ] request_token = gdata.auth.OAuthToken(key=token_key, secret=token_secret, scopes=scopes) url = gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url='https://www.example.com/accounts/OAuthAuthToken', callback_url='http://www.yourwebapp.com/print', extra_params={'permission': '1'}, include_scopes_in_callback=True, scopes_param_prefix='token_scope') self.assertEquals('https', url.protocol) self.assertEquals('www.example.com', url.host) self.assertEquals('/accounts/OAuthAuthToken', url.path) self.assertEquals(token_key, url.params['oauth_token']) expected_callback_url = ('http://www.yourwebapp.com/print?' 'token_scope=http%3A%2F%2Fabcd.example.com%2Ffeeds' '+http%3A%2F%2Fwww.example.com%2Fabcd%2Ffeeds') self.assertEquals(expected_callback_url, url.params['oauth_callback']) class GenerateOAuthAccessTokenUrlTest(unittest.TestCase): def testDefaultParameters(self): token_key = 'ABCDDSFFDSG' token_secret = 'SDFDSGSDADADSAF' authorized_request_token = gdata.auth.OAuthToken(key=token_key, secret=token_secret) oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) url = gdata.auth.GenerateOAuthAccessTokenUrl(authorized_request_token, oauth_input_params) self.assertEquals('https', url.protocol) self.assertEquals('www.google.com', url.host) self.assertEquals('/accounts/OAuthGetAccessToken', url.path) self.assertEquals(token_key, url.params['oauth_token']) self.assertEquals('1.0', url.params['oauth_version']) self.assertEquals('HMAC-SHA1', url.params['oauth_signature_method']) self.assert_(url.params['oauth_nonce']) self.assert_(url.params['oauth_timestamp']) self.assertEquals(CONSUMER_KEY, url.params['oauth_consumer_key']) self.assert_(url.params['oauth_signature']) def testAllParameters(self): token_key = 'ABCDDSFFDSG' authorized_request_token = gdata.auth.OAuthToken(key=token_key) oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY) url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, oauth_input_params, access_token_url='https://www.example.com/accounts/OAuthGetAccessToken', oauth_version= '2.0') self.assertEquals('https', url.protocol) self.assertEquals('www.example.com', url.host) self.assertEquals('/accounts/OAuthGetAccessToken', url.path) self.assertEquals(token_key, url.params['oauth_token']) self.assertEquals('2.0', url.params['oauth_version']) self.assertEquals('RSA-SHA1', url.params['oauth_signature_method']) self.assert_(url.params['oauth_nonce']) self.assert_(url.params['oauth_timestamp']) self.assertEquals(CONSUMER_KEY, url.params['oauth_consumer_key']) self.assert_(url.params['oauth_signature']) class ExtractAuthSubTokensTest(unittest.TestCase): def testGetTokenFromUrl(self): url = 'http://www.yourwebapp.com/showcalendar.html?token=CKF50YzIH' self.assert_(gdata.auth.AuthSubTokenFromUrl(url) == 'AuthSub token=CKF50YzIH') self.assert_(gdata.auth.TokenFromUrl(url) == 'CKF50YzIH') url = 'http://www.yourwebapp.com/showcalendar.html?token==tokenCKF50YzIH=' self.assert_(gdata.auth.AuthSubTokenFromUrl(url) == 'AuthSub token==tokenCKF50YzIH=') self.assert_(gdata.auth.TokenFromUrl(url) == '=tokenCKF50YzIH=') def testGetTokenFromHttpResponse(self): response_body = ('Token=DQAA...7DCTN\r\n' 'Expiration=20061004T123456Z') self.assert_(gdata.auth.AuthSubTokenFromHttpBody(response_body) == 'AuthSub token=DQAA...7DCTN') class CreateAuthSubTokenFlowTest(unittest.TestCase): def testGenerateRequest(self): request_url = gdata.auth.generate_auth_sub_url(next='http://example.com', scopes=['http://www.blogger.com/feeds/', 'http://www.google.com/base/feeds/']) self.assertEquals(request_url.protocol, 'https') self.assertEquals(request_url.host, 'www.google.com') self.assertEquals(request_url.params['scope'], 'http://www.blogger.com/feeds/ http://www.google.com/base/feeds/') self.assertEquals(request_url.params['hd'], 'default') self.assert_(request_url.params['next'].find('auth_sub_scopes') > -1) self.assert_(request_url.params['next'].startswith('http://example.com')) # Use a more complicated 'next' URL. request_url = gdata.auth.generate_auth_sub_url( next='http://example.com/?token_scope=http://www.blogger.com/feeds/', scopes=['http://www.blogger.com/feeds/', 'http://www.google.com/base/feeds/']) self.assert_(request_url.params['next'].find('auth_sub_scopes') > -1) self.assert_(request_url.params['next'].find('token_scope') > -1) self.assert_(request_url.params['next'].startswith('http://example.com/')) def testParseNextUrl(self): url = ('http://example.com/?auth_sub_scopes=http%3A%2F%2Fwww.blogger.com' '%2Ffeeds%2F+http%3A%2F%2Fwww.google.com%2Fbase%2Ffeeds%2F&' 'token=my_nifty_token') token = gdata.auth.extract_auth_sub_token_from_url(url) self.assertEquals(token.get_token_string(), 'my_nifty_token') self.assert_(isinstance(token, gdata.auth.AuthSubToken)) self.assert_(token.valid_for_scope('http://www.blogger.com/feeds/')) self.assert_(token.valid_for_scope('http://www.google.com/base/feeds/')) self.assert_( not token.valid_for_scope('http://www.google.com/calendar/feeds/')) # Parse a more complicated response. url = ('http://example.com/?auth_sub_scopes=http%3A%2F%2Fwww.blogger.com' '%2Ffeeds%2F+http%3A%2F%2Fwww.google.com%2Fbase%2Ffeeds%2F&' 'token_scope=http%3A%2F%2Fwww.blogger.com%2Ffeeds%2F&' 'token=second_token') token = gdata.auth.extract_auth_sub_token_from_url(url) self.assertEquals(token.get_token_string(), 'second_token') self.assert_(isinstance(token, gdata.auth.AuthSubToken)) self.assert_(token.valid_for_scope('http://www.blogger.com/feeds/')) self.assert_(token.valid_for_scope('http://www.google.com/base/feeds/')) self.assert_( not token.valid_for_scope('http://www.google.com/calendar/feeds/')) def testParseNextWithNoToken(self): token = gdata.auth.extract_auth_sub_token_from_url('http://example.com/') self.assert_(token is None) token = gdata.auth.extract_auth_sub_token_from_url( 'http://example.com/?no_token=foo&other=1') self.assert_(token is None) class ExtractClientLoginTokenTest(unittest.TestCase): def testExtractFromBodyWithScopes(self): http_body_string = ('SID=DQAAAGgA7Zg8CTN\r\n' 'LSID=DQAAAGsAlk8BBbG\r\n' 'Auth=DQAAAGgAdk3fA5N') token = gdata.auth.extract_client_login_token(http_body_string, ['http://docs.google.com/feeds/']) self.assertEquals(token.get_token_string(), 'DQAAAGgAdk3fA5N') self.assert_(isinstance(token, gdata.auth.ClientLoginToken)) self.assert_(token.valid_for_scope('http://docs.google.com/feeds/')) self.assert_(not token.valid_for_scope('http://www.blogger.com/feeds')) class ExtractOAuthTokensTest(unittest.TestCase): def testOAuthTokenFromUrl(self): scope_1 = 'http://docs.google.com/feeds/' scope_2 = 'http://www.blogger.com/feeds/' # Case 1: token and scopes both are present. url = ('http://dummy.com/?oauth_token_scope=http%3A%2F%2Fwww.blogger.com' '%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&' 'oauth_token=CMns6t7MCxDz__8B') token = gdata.auth.OAuthTokenFromUrl(url) self.assertEquals('CMns6t7MCxDz__8B', token.key) self.assertEquals(2, len(token.scopes)) self.assert_(scope_1 in token.scopes) self.assert_(scope_2 in token.scopes) # Case 2: token and scopes both are present but scope_param_prefix # passed does not match the one present in the URL. url = ('http://dummy.com/?oauth_token_scope=http%3A%2F%2Fwww.blogger.com' '%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&' 'oauth_token=CMns6t7MCxDz__8B') token = gdata.auth.OAuthTokenFromUrl(url, scopes_param_prefix='token_scope') self.assertEquals('CMns6t7MCxDz__8B', token.key) self.assert_(not token.scopes) # Case 3: None present. url = ('http://dummy.com/?no_oauth_token_scope=http%3A%2F%2Fwww.blogger.com' '%2Ffeeds%2F+http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&' 'no_oauth_token=CMns6t7MCxDz__8B') token = gdata.auth.OAuthTokenFromUrl(url) self.assert_(token is None) def testOAuthTokenFromHttpBody(self): token_key = 'ABCD' token_secret = 'XYZ' # Case 1: token key and secret both present single time. http_body = 'oauth_token=%s&oauth_token_secret=%s' % (token_key, token_secret) token = gdata.auth.OAuthTokenFromHttpBody(http_body) self.assertEquals(token_key, token.key) self.assertEquals(token_secret, token.secret) class OAuthInputParametersTest(unittest.TestCase): def setUp(self): self.oauth_input_parameters_hmac = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) self.oauth_input_parameters_rsa = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY) def testGetSignatureMethod(self): self.assertEquals( 'HMAC-SHA1', self.oauth_input_parameters_hmac.GetSignatureMethod().get_name()) rsa_signature_method = self.oauth_input_parameters_rsa.GetSignatureMethod() self.assertEquals('RSA-SHA1', rsa_signature_method.get_name()) self.assertEquals(RSA_KEY, rsa_signature_method._fetch_private_cert(None)) def testGetConsumer(self): self.assertEquals(CONSUMER_KEY, self.oauth_input_parameters_hmac.GetConsumer().key) self.assertEquals(CONSUMER_KEY, self.oauth_input_parameters_rsa.GetConsumer().key) self.assertEquals(CONSUMER_SECRET, self.oauth_input_parameters_hmac.GetConsumer().secret) self.assert_(self.oauth_input_parameters_rsa.GetConsumer().secret is None) class TokenClassesTest(unittest.TestCase): def testClientLoginToAndFromString(self): token = gdata.auth.ClientLoginToken() token.set_token_string('foo') self.assertEquals(token.get_token_string(), 'foo') self.assertEquals(token.auth_header, '%s%s' % ( gdata.auth.PROGRAMMATIC_AUTH_LABEL, 'foo')) token.set_token_string(token.get_token_string()) self.assertEquals(token.get_token_string(), 'foo') def testAuthSubToAndFromString(self): token = gdata.auth.AuthSubToken() token.set_token_string('foo') self.assertEquals(token.get_token_string(), 'foo') self.assertEquals(token.auth_header, '%s%s' % ( gdata.auth.AUTHSUB_AUTH_LABEL, 'foo')) token.set_token_string(token.get_token_string()) self.assertEquals(token.get_token_string(), 'foo') def testSecureAuthSubToAndFromString(self): # Case 1: no token. token = gdata.auth.SecureAuthSubToken(RSA_KEY) token.set_token_string('foo') self.assertEquals(token.get_token_string(), 'foo') token.set_token_string(token.get_token_string()) self.assertEquals(token.get_token_string(), 'foo') self.assertEquals(str(token), 'foo') # Case 2: token is a string token = gdata.auth.SecureAuthSubToken(RSA_KEY, token_string='foo') self.assertEquals(token.get_token_string(), 'foo') token.set_token_string(token.get_token_string()) self.assertEquals(token.get_token_string(), 'foo') self.assertEquals(str(token), 'foo') def testOAuthToAndFromString(self): token_key = 'ABCD' token_secret = 'XYZ' # Case 1: token key and secret both present single time. token_string = 'oauth_token=%s&oauth_token_secret=%s' % (token_key, token_secret) token = gdata.auth.OAuthToken() token.set_token_string(token_string) self.assert_(-1 < token.get_token_string().find(token_string.split('&')[0])) self.assert_(-1 < token.get_token_string().find(token_string.split('&')[1])) self.assertEquals(token_key, token.key) self.assertEquals(token_secret, token.secret) # Case 2: token key and secret both present multiple times with unwanted # parameters. token_string = ('oauth_token=%s&oauth_token_secret=%s&' 'oauth_token=%s&ExtraParams=GarbageString' % (token_key, token_secret, 'LMNO')) token = gdata.auth.OAuthToken() token.set_token_string(token_string) self.assert_(-1 < token.get_token_string().find(token_string.split('&')[0])) self.assert_(-1 < token.get_token_string().find(token_string.split('&')[1])) self.assertEquals(token_key, token.key) self.assertEquals(token_secret, token.secret) # Case 3: Only token key present. token_string = 'oauth_token=%s' % (token_key,) token = gdata.auth.OAuthToken() token.set_token_string(token_string) self.assertEquals(token_string, token.get_token_string()) self.assertEquals(token_key, token.key) self.assert_(not token.secret) # Case 4: Only token key present. token_string = 'oauth_token_secret=%s' % (token_secret,) token = gdata.auth.OAuthToken() token.set_token_string(token_string) self.assertEquals(token_string, token.get_token_string()) self.assertEquals(token_secret, token.secret) self.assert_(not token.key) # Case 5: None present. token_string = '' token = gdata.auth.OAuthToken() token.set_token_string(token_string) self.assert_(token.get_token_string() is None) self.assert_(not token.key) self.assert_(not token.secret) def testSecureAuthSubGetAuthHeader(self): # Case 1: Presence of OAuth token (in case of 3-legged OAuth) url = 'http://dummy.com/?q=notebook&s=true' token = gdata.auth.SecureAuthSubToken(RSA_KEY, token_string='foo') auth_header = token.GetAuthHeader('GET', url) self.assert_('Authorization' in auth_header) header_value = auth_header['Authorization'] self.assert_(header_value.startswith(r'AuthSub token="foo"')) self.assert_(-1 < header_value.find(r'sigalg="rsa-sha1"')) self.assert_(-1 < header_value.find(r'data="')) self.assert_(-1 < header_value.find(r'sig="')) m = re.search(r'data="(.*?)"', header_value) self.assert_(m is not None) data = m.group(1) self.assert_(data.startswith('GET')) self.assert_(-1 < data.find(url)) def testOAuthGetAuthHeader(self): # Case 1: Presence of OAuth token (in case of 3-legged OAuth) oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.RSA_SHA1, CONSUMER_KEY, rsa_key=RSA_KEY) token = gdata.auth.OAuthToken(key='ABCDDSFFDSG', oauth_input_params=oauth_input_params) auth_header = token.GetAuthHeader('GET', 'http://dummy.com/?q=notebook&s=true', realm='http://dummy.com') self.assert_('Authorization' in auth_header) header_value = auth_header['Authorization'] self.assert_(-1 < header_value.find(r'OAuth realm="http://dummy.com"')) self.assert_(-1 < header_value.find(r'oauth_version="1.0"')) self.assert_(-1 < header_value.find(r'oauth_token="ABCDDSFFDSG"')) self.assert_(-1 < header_value.find(r'oauth_nonce="')) self.assert_(-1 < header_value.find(r'oauth_timestamp="')) self.assert_(-1 < header_value.find(r'oauth_signature="')) self.assert_(-1 < header_value.find( r'oauth_consumer_key="%s"' % CONSUMER_KEY)) self.assert_(-1 < header_value.find(r'oauth_signature_method="RSA-SHA1"')) # Case 2: Absence of OAuth token (in case of 2-legged OAuth) oauth_input_params = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) token = gdata.auth.OAuthToken(oauth_input_params=oauth_input_params) auth_header = token.GetAuthHeader( 'GET', 'http://dummy.com/?xoauth_requestor_id=user@gmail.com&q=book') self.assert_('Authorization' in auth_header) header_value = auth_header['Authorization'] self.assert_(-1 < header_value.find(r'OAuth realm=""')) self.assert_(-1 < header_value.find(r'oauth_version="1.0"')) self.assertEquals(-1, header_value.find(r'oauth_token=')) self.assert_(-1 < header_value.find(r'oauth_nonce="')) self.assert_(-1 < header_value.find(r'oauth_timestamp="')) self.assert_(-1 < header_value.find(r'oauth_signature="')) self.assert_(-1 < header_value.find( r'oauth_consumer_key="%s"' % CONSUMER_KEY)) self.assert_(-1 < header_value.find(r'oauth_signature_method="HMAC-SHA1"')) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Vic Fryzel <vf@google.com>' import unittest import atom.core from gdata import test_data import gdata.calendar_resource.data import gdata.test_config as conf class CalendarResourceEntryTest(unittest.TestCase): def setUp(self): self.entry = atom.core.parse(test_data.CALENDAR_RESOURCE_ENTRY, gdata.calendar_resource.data.CalendarResourceEntry) self.feed = atom.core.parse(test_data.CALENDAR_RESOURCES_FEED, gdata.calendar_resource.data.CalendarResourceFeed) def testCalendarResourceEntryFromString(self): self.assert_(isinstance(self.entry, gdata.calendar_resource.data.CalendarResourceEntry)) self.assertEquals(self.entry.resource_id, 'CR-NYC-14-12-BR') self.assertEquals(self.entry.resource_common_name, 'Boardroom') self.assertEquals(self.entry.resource_description, ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom')) self.assertEquals(self.entry.resource_type, 'CR') def testCalendarResourceFeedFromString(self): self.assertEquals(len(self.feed.entry), 2) self.assert_(isinstance(self.feed, gdata.calendar_resource.data.CalendarResourceFeed)) self.assert_(isinstance(self.feed.entry[0], gdata.calendar_resource.data.CalendarResourceEntry)) self.assert_(isinstance(self.feed.entry[1], gdata.calendar_resource.data.CalendarResourceEntry)) self.assertEquals( self.feed.entry[0].find_edit_link(), 'https://apps-apis.google.com/feeds/calendar/resource/2.0/yourdomain.com/CR-NYC-14-12-BR') self.assertEquals(self.feed.entry[0].resource_id, 'CR-NYC-14-12-BR') self.assertEquals(self.feed.entry[0].resource_common_name, 'Boardroom') self.assertEquals(self.feed.entry[0].resource_description, ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom')) self.assertEquals(self.feed.entry[0].resource_type, 'CR') self.assertEquals(self.feed.entry[1].resource_id, '(Bike)-London-43-Lobby-Bike-1') self.assertEquals(self.feed.entry[1].resource_common_name, 'London bike-1') self.assertEquals(self.feed.entry[1].resource_description, 'Bike is in London at building 43\'s lobby.') self.assertEquals(self.feed.entry[1].resource_type, '(Bike)') self.assertEquals( self.feed.entry[1].find_edit_link(), 'https://apps-apis.google.com/a/feeds/calendar/resource/2.0/yourdomain.com/(Bike)-London-43-Lobby-Bike-1') def suite(): return conf.build_suite([CalendarResourceEntryTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'Vic Fryzel <vf@google.com>' import unittest import gdata.client import gdata.data import gdata.gauth import gdata.calendar_resource.client import gdata.calendar_resource.data import gdata.test_config as conf conf.options.register_option(conf.APPS_DOMAIN_OPTION) class CalendarResourceClientTest(unittest.TestCase): def setUp(self): self.client = gdata.calendar_resource.client.CalendarResourceClient( domain='example.com') if conf.options.get_value('runlive') == 'true': self.client = gdata.calendar_resource.client.CalendarResourceClient( domain=conf.options.get_value('appsdomain')) if conf.options.get_value('ssl') == 'true': self.client.ssl = True conf.configure_client(self.client, 'CalendarResourceClientTest', self.client.auth_service, True) def tearDown(self): conf.close_client(self.client) def testClientConfiguration(self): self.assertEqual('apps-apis.google.com', self.client.host) self.assertEqual('2.0', self.client.api_version) self.assertEqual('apps', self.client.auth_service) self.assertEqual( ('http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'), self.client.auth_scopes) if conf.options.get_value('runlive') == 'true': self.assertEqual(self.client.domain, conf.options.get_value('appsdomain')) else: self.assertEqual(self.client.domain, 'example.com') def testMakeResourceFeedUri(self): self.assertEqual('/a/feeds/calendar/resource/2.0/%s/' % self.client.domain, self.client.MakeResourceFeedUri()) self.assertEqual('/a/feeds/calendar/resource/2.0/%s/CR-NYC-14-12-BR' % self.client.domain, self.client.MakeResourceFeedUri(resource_id='CR-NYC-14-12-BR')) self.assertEqual('/a/feeds/calendar/resource/2.0/%s/?test=1' % self.client.domain, self.client.MakeResourceFeedUri(params={'test': 1})) self.assertEqual('/a/feeds/calendar/resource/2.0/%s/CR-NYC-14-12-BR?test=1' % self.client.domain, self.client.MakeResourceFeedUri(resource_id='CR-NYC-14-12-BR', params={'test': 1})) def testCreateRetrieveUpdateDelete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateUpdateDelete') try: new_entry = self.client.CreateResource( 'CR-NYC-14-12-BR', 'Boardroom', ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom'), 'CR') except Exception, e: print e self.client.delete_resource('CR-NYC-14-12-BR') # If the test failed to run to completion # the resource may already exist new_entry = self.client.CreateResource( 'CR-NYC-14-12-BR', 'Boardroom', ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom'), 'CR') self.assert_(isinstance(new_entry, gdata.calendar_resource.data.CalendarResourceEntry)) self.assertEqual(new_entry.resource_id, 'CR-NYC-14-12-BR') self.assertEqual(new_entry.resource_common_name, 'Boardroom') self.assertEqual(new_entry.resource_description, ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom')) self.assertEqual(new_entry.resource_type, 'CR') fetched_entry = self.client.get_resource(resource_id='CR-NYC-14-12-BR') self.assert_(isinstance(fetched_entry, gdata.calendar_resource.data.CalendarResourceEntry)) self.assertEqual(fetched_entry.resource_id, 'CR-NYC-14-12-BR') self.assertEqual(fetched_entry.resource_common_name, 'Boardroom') self.assertEqual(fetched_entry.resource_description, ('This conference room is in New York City, building 14, floor 12, ' 'Boardroom')) self.assertEqual(fetched_entry.resource_type, 'CR') new_entry.resource_id = 'CR-MTV-14-12-BR' new_entry.resource_common_name = 'Executive Boardroom' new_entry.resource_description = 'This conference room is in Mountain View' new_entry.resource_type = 'BR' updated_entry = self.client.update(new_entry) self.assert_(isinstance(updated_entry, gdata.calendar_resource.data.CalendarResourceEntry)) self.assertEqual(updated_entry.resource_id, 'CR-MTV-14-12-BR') self.assertEqual(updated_entry.resource_common_name, 'Executive Boardroom') self.assertEqual(updated_entry.resource_description, 'This conference room is in Mountain View') self.assertEqual(updated_entry.resource_type, 'BR') self.client.delete_resource('CR-NYC-14-12-BR') def suite(): return conf.build_suite([CalendarResourceClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import unittest from gdata import test_data import gdata.blogger import atom class BlogEntryTest(unittest.TestCase): def testBlogEntryFromString(self): entry = gdata.blogger.BlogEntryFromString(test_data.BLOG_ENTRY) self.assertEquals(entry.GetBlogName(), 'blogName') self.assertEquals(entry.GetBlogId(), 'blogID') self.assertEquals(entry.title.text, 'Lizzy\'s Diary') def testBlogPostFeedFromString(self): feed = gdata.blogger.BlogPostFeedFromString(test_data.BLOG_POSTS_FEED) self.assertEquals(len(feed.entry), 1) self.assert_(isinstance(feed, gdata.blogger.BlogPostFeed)) self.assert_(isinstance(feed.entry[0], gdata.blogger.BlogPostEntry)) self.assertEquals(feed.entry[0].GetPostId(), 'postID') self.assertEquals(feed.entry[0].GetBlogId(), 'blogID') self.assertEquals(feed.entry[0].title.text, 'Quite disagreeable') def testCommentFeedFromString(self): feed = gdata.blogger.CommentFeedFromString(test_data.BLOG_COMMENTS_FEED) self.assertEquals(len(feed.entry), 1) self.assert_(isinstance(feed, gdata.blogger.CommentFeed)) self.assert_(isinstance(feed.entry[0], gdata.blogger.CommentEntry)) self.assertEquals(feed.entry[0].GetBlogId(), 'blogID') self.assertEquals(feed.entry[0].GetCommentId(), 'commentID') self.assertEquals(feed.entry[0].title.text, 'This is my first comment') self.assertEquals(feed.entry[0].in_reply_to.source, 'http://blogName.blogspot.com/feeds/posts/default/postID') self.assertEquals(feed.entry[0].in_reply_to.ref, 'tag:blogger.com,1999:blog-blogID.post-postID') self.assertEquals(feed.entry[0].in_reply_to.href, 'http://blogName.blogspot.com/2007/04/first-post.html') self.assertEquals(feed.entry[0].in_reply_to.type, 'text/html') def testIdParsing(self): entry = gdata.blogger.BlogEntry() entry.id = atom.Id( text='tag:blogger.com,1999:user-146606542.blog-4023408167658848') self.assertEquals(entry.GetBlogId(), '4023408167658848') entry.id = atom.Id(text='tag:blogger.com,1999:blog-4023408167658848') self.assertEquals(entry.GetBlogId(), '4023408167658848') class InReplyToTest(unittest.TestCase): def testToAndFromString(self): in_reply_to = gdata.blogger.InReplyTo(href='http://example.com/href', ref='http://example.com/ref', source='http://example.com/my_post', type='text/html') xml_string = str(in_reply_to) parsed = gdata.blogger.InReplyToFromString(xml_string) self.assertEquals(parsed.source, in_reply_to.source) self.assertEquals(parsed.href, in_reply_to.href) self.assertEquals(parsed.ref, in_reply_to.ref) self.assertEquals(parsed.type, in_reply_to.type) class CommentEntryTest(unittest.TestCase): def testToAndFromString(self): comment = gdata.blogger.CommentEntry(content=atom.Content(text='Nifty!'), in_reply_to=gdata.blogger.InReplyTo( source='http://example.com/my_post')) parsed = gdata.blogger.CommentEntryFromString(str(comment)) self.assertEquals(parsed.in_reply_to.source, comment.in_reply_to.source) self.assertEquals(parsed.content.text, comment.content.text) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'e.bidelman (Eric Bidelman)' import unittest import atom from gdata import test_data import gdata.acl.data import gdata.data import gdata.docs.data import gdata.test_config as conf class DocsHelperTest(unittest.TestCase): def setUp(self): pass def testMakeKindCategory(self): category = gdata.docs.data.MakeKindCategory('folder') self.assertEqual(category.label, 'folder') self.assertEqual(category.scheme, 'http://schemas.google.com/g/2005#kind') self.assertEqual( category.term, 'http://schemas.google.com/docs/2007#folder') category = gdata.docs.data.MakeKindCategory('spreadsheet') self.assertEqual(category.label, 'spreadsheet') self.assertEqual(category.scheme, 'http://schemas.google.com/g/2005#kind') self.assertEqual( category.term, 'http://schemas.google.com/docs/2007#spreadsheet') def testMakeContentLinkFromResourceId(self): link = gdata.docs.data.make_content_link_from_resource_id( 'document%3A1234567890') self.assertEqual(link, '/feeds/download/documents/Export?docId=1234567890') link2 = gdata.docs.data.make_content_link_from_resource_id( 'presentation%3A1234567890') self.assertEqual( link2, '/feeds/download/presentations/Export?docId=1234567890') link3 = gdata.docs.data.make_content_link_from_resource_id( 'spreadsheet%3A1234567890') self.assertEqual( link3, ('https://spreadsheets.google.com/feeds/download/spreadsheets/' 'Export?key=1234567890')) # Try an invalid resource id. exception_raised = False try: link4 = gdata.docs.data.make_content_link_from_resource_id('1234567890') except ValueError, e: # expected exception_raised = True self.assert_(exception_raised) # Try an resource id that cannot be exported. exception_raised = False try: link4 = gdata.docs.data.make_content_link_from_resource_id( 'pdf%3A1234567890') except ValueError, e: # expected exception_raised = True self.assert_(exception_raised) class DocsEntryTest(unittest.TestCase): def setUp(self): self.entry = atom.core.parse(test_data.DOCUMENT_LIST_ENTRY_V3, gdata.docs.data.DocsEntry) def testToAndFromStringDocsEntry(self): self.assert_(isinstance(self.entry, gdata.docs.data.DocsEntry)) self.assertEqual(self.entry.GetDocumentType(), 'spreadsheet') self.assert_(isinstance(self.entry.last_viewed, gdata.docs.data.LastViewed)) self.assertEqual(self.entry.last_viewed.text, '2009-03-05T07:48:21.493Z') self.assert_( isinstance(self.entry.last_modified_by, gdata.docs.data.LastModifiedBy)) self.assertEqual( self.entry.last_modified_by.email.text, 'test.user@gmail.com') self.assertEqual(self.entry.last_modified_by.name.text, 'test.user') self.assert_(isinstance(self.entry.resource_id, gdata.docs.data.ResourceId)) self.assertEqual(self.entry.resource_id.text, 'spreadsheet:supercalifragilisticexpealidocious') self.assert_(isinstance(self.entry.writers_can_invite, gdata.docs.data.WritersCanInvite)) self.assertEqual(self.entry.writers_can_invite.value, 'true') self.assert_(isinstance(self.entry.quota_bytes_used, gdata.docs.data.QuotaBytesUsed)) self.assertEqual(self.entry.quota_bytes_used.text, '1000') self.assertEqual(len(self.entry.feed_link), 2) self.assert_(isinstance(self.entry.feed_link[0], gdata.data.FeedLink)) self.assertEqual( self.entry.get_acl_feed_link().href, ('https://docs.google.com/feeds/default/private/full/' 'spreadsheet%3Asupercalifragilisticexpealidocious/acl')) self.assertEqual( self.entry.get_revisions_feed_link().href, ('https://docs.google.com/feeds/default/private/full/' 'spreadsheet%3Asupercalifragilisticexpealidocious/revisions')) self.assertEqual(len(self.entry.in_folders()), 1) self.assertEqual(self.entry.in_folders()[0].title, 'AFolderName') class AclTest(unittest.TestCase): def setUp(self): self.acl_entry = atom.core.parse(test_data.DOCUMENT_LIST_ACL_ENTRY, gdata.docs.data.Acl) self.acl_entry_withkey = atom.core.parse( test_data.DOCUMENT_LIST_ACL_WITHKEY_ENTRY, gdata.docs.data.Acl) def testToAndFromString(self): self.assert_(isinstance(self.acl_entry, gdata.docs.data.Acl)) self.assert_(isinstance(self.acl_entry.role, gdata.acl.data.AclRole)) self.assert_(isinstance(self.acl_entry.scope, gdata.acl.data.AclScope)) self.assertEqual(self.acl_entry.scope.value, 'user@gmail.com') self.assertEqual(self.acl_entry.scope.type, 'user') self.assertEqual(self.acl_entry.role.value, 'writer') acl_entry_str = str(self.acl_entry) new_acl_entry = atom.core.parse(acl_entry_str, gdata.docs.data.Acl) self.assert_(isinstance(new_acl_entry, gdata.docs.data.Acl)) self.assert_(isinstance(new_acl_entry.role, gdata.acl.data.AclRole)) self.assert_(isinstance(new_acl_entry.scope, gdata.acl.data.AclScope)) self.assertEqual(new_acl_entry.scope.value, self.acl_entry.scope.value) self.assertEqual(new_acl_entry.scope.type, self.acl_entry.scope.type) self.assertEqual(new_acl_entry.role.value, self.acl_entry.role.value) def testToAndFromStringWithKey(self): self.assert_(isinstance(self.acl_entry_withkey, gdata.docs.data.Acl)) self.assert_(self.acl_entry_withkey.role is None) self.assert_(isinstance(self.acl_entry_withkey.with_key, gdata.acl.data.AclWithKey)) self.assert_(isinstance(self.acl_entry_withkey.with_key.role, gdata.acl.data.AclRole)) self.assert_(isinstance(self.acl_entry_withkey.scope, gdata.acl.data.AclScope)) self.assertEqual(self.acl_entry_withkey.with_key.key, 'somekey') self.assertEqual(self.acl_entry_withkey.with_key.role.value, 'writer') self.assertEqual(self.acl_entry_withkey.scope.value, 'example.com') self.assertEqual(self.acl_entry_withkey.scope.type, 'domain') acl_entry_withkey_str = str(self.acl_entry_withkey) new_acl_entry_withkey = atom.core.parse(acl_entry_withkey_str, gdata.docs.data.Acl) self.assert_(isinstance(new_acl_entry_withkey, gdata.docs.data.Acl)) self.assert_(new_acl_entry_withkey.role is None) self.assert_(isinstance(new_acl_entry_withkey.with_key, gdata.acl.data.AclWithKey)) self.assert_(isinstance(new_acl_entry_withkey.with_key.role, gdata.acl.data.AclRole)) self.assert_(isinstance(new_acl_entry_withkey.scope, gdata.acl.data.AclScope)) self.assertEqual(new_acl_entry_withkey.with_key.key, self.acl_entry_withkey.with_key.key) self.assertEqual(new_acl_entry_withkey.with_key.role.value, self.acl_entry_withkey.with_key.role.value) self.assertEqual(new_acl_entry_withkey.scope.value, self.acl_entry_withkey.scope.value) self.assertEqual(new_acl_entry_withkey.scope.type, self.acl_entry_withkey.scope.type) def testCreateNewAclEntry(self): cat = gdata.atom.Category( term='http://schemas.google.com/acl/2007#accessRule', scheme='http://schemas.google.com/g/2005#kind') acl_entry = gdata.docs.DocumentListAclEntry(category=[cat]) acl_entry.scope = gdata.docs.Scope(value='user@gmail.com', type='user') acl_entry.role = gdata.docs.Role(value='writer') self.assert_(isinstance(acl_entry, gdata.docs.DocumentListAclEntry)) self.assert_(isinstance(acl_entry.role, gdata.docs.Role)) self.assert_(isinstance(acl_entry.scope, gdata.docs.Scope)) self.assertEqual(acl_entry.scope.value, 'user@gmail.com') self.assertEqual(acl_entry.scope.type, 'user') self.assertEqual(acl_entry.role.value, 'writer') class AclFeedTest(unittest.TestCase): def setUp(self): self.feed = atom.core.parse(test_data.DOCUMENT_LIST_ACL_FEED, gdata.docs.data.AclFeed) def testToAndFromString(self): for entry in self.feed.entry: self.assert_(isinstance(entry, gdata.docs.data.Acl)) feed = atom.core.parse(str(self.feed), gdata.docs.data.AclFeed) for entry in feed.entry: self.assert_(isinstance(entry, gdata.docs.data.Acl)) def testConvertActualData(self): entries = self.feed.entry self.assert_(len(entries) == 2) self.assertEqual(entries[0].title.text, 'Document Permission - user@gmail.com') self.assertEqual(entries[0].role.value, 'owner') self.assertEqual(entries[0].scope.type, 'user') self.assertEqual(entries[0].scope.value, 'user@gmail.com') self.assert_(entries[0].GetSelfLink() is not None) self.assert_(entries[0].GetEditLink() is not None) self.assertEqual(entries[1].title.text, 'Document Permission - user2@google.com') self.assertEqual(entries[1].role.value, 'writer') self.assertEqual(entries[1].scope.type, 'domain') self.assertEqual(entries[1].scope.value, 'google.com') self.assert_(entries[1].GetSelfLink() is not None) self.assert_(entries[1].GetEditLink() is not None) class RevisionFeedTest(unittest.TestCase): def setUp(self): self.feed = atom.core.parse(test_data.DOCUMENT_LIST_REVISION_FEED, gdata.docs.data.RevisionFeed) def testToAndFromString(self): for entry in self.feed.entry: self.assert_(isinstance(entry, gdata.docs.data.Revision)) feed = atom.core.parse(str(self.feed), gdata.docs.data.RevisionFeed) for entry in feed.entry: self.assert_(isinstance(entry, gdata.docs.data.Revision)) def testConvertActualData(self): entries = self.feed.entry self.assert_(len(entries) == 1) self.assertEqual(entries[0].title.text, 'Revision 2') self.assertEqual(entries[0].publish.value, 'true') self.assertEqual(entries[0].publish_auto.value, 'true') self.assertEqual(entries[0].publish_outside_domain.value, 'false') self.assertEqual( entries[0].GetPublishLink().href, 'https://docs.google.com/View?docid=dfr4&pageview=1&hgd=1') self.assertEqual( entries[0].FindPublishLink(), 'https://docs.google.com/View?docid=dfr4&pageview=1&hgd=1') class DataClassSanityTest(unittest.TestCase): def test_basic_element_structure(self): conf.check_data_classes(self, [ gdata.docs.data.ResourceId, gdata.docs.data.LastModifiedBy, gdata.docs.data.LastViewed, gdata.docs.data.WritersCanInvite, gdata.docs.data.QuotaBytesUsed, gdata.docs.data.Publish, gdata.docs.data.PublishAuto, gdata.docs.data.PublishOutsideDomain, gdata.docs.data.DocsEntry, gdata.docs.data.Acl, gdata.docs.data.AclFeed, gdata.docs.data.DocList, gdata.docs.data.Revision, gdata.docs.data.RevisionFeed]) def suite(): return conf.build_suite( [DataClassSanityTest, DocsHelperTest, DocsEntryTest, AclTest, AclFeed]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = ('api.jfisher (Jeff Fisher), ' 'api.eric@google.com (Eric Bidelman)') import getpass import os import re import StringIO import time import unittest import gdata.docs.service import gdata.spreadsheet.service username = '' password = '' client = gdata.docs.service.DocsService() editClient = gdata.docs.service.DocsService() spreadsheets = gdata.spreadsheet.service.SpreadsheetsService() class DocumentsListServiceTest(unittest.TestCase): def setUp(self): self.client = client self.editClient = editClient self.editClient.SetClientLoginToken(client.GetClientLoginToken()) self.editClient.additional_headers = {'If-Match': '*'} self.spreadsheets = spreadsheets self.DOCUMENT_CATEGORY = client._MakeKindCategory(gdata.docs.service.DOCUMENT_LABEL) self.SPREADSHEET_CATEGORY = client._MakeKindCategory(gdata.docs.service.SPREADSHEET_LABEL) self.PRESENTATION_CATEGORY = client._MakeKindCategory(gdata.docs.service.PRESENTATION_LABEL) class DocumentListQueryTest(DocumentsListServiceTest): def setUp(self): DocumentsListServiceTest.setUp(self) self.feed = self.client.GetDocumentListFeed() def testGetDocumentsListFeed(self): self.assert_(isinstance(self.feed, gdata.docs.DocumentListFeed)) uri = 'http://docs.google.com/feeds/documents/private/full/?max-results=1' # Query using GetDocumentListFeed() feed = self.client.GetDocumentListFeed(uri) self.assert_(isinstance(feed, gdata.docs.DocumentListFeed)) self.assertEqual(len(feed.entry), 1) self.assertEqual(self.feed.entry[0].id.text, feed.entry[0].id.text) self.assertEqual(self.feed.entry[0].title.text, feed.entry[0].title.text) # Query using QueryDocumentListFeed() feed2 = self.client.QueryDocumentListFeed(uri) self.assertEqual(len(feed2.entry), 1) self.assertEqual(self.feed.entry[0].id.text, feed2.entry[0].id.text) self.assertEqual(self.feed.entry[0].title.text, feed2.entry[0].title.text) def testGetDocumentsListEntry(self): self_link = self.feed.entry[0].GetSelfLink().href entry = self.client.GetDocumentListEntry(self_link) self.assert_(isinstance(entry, gdata.docs.DocumentListEntry)) self.assertEqual(self.feed.entry[0].id.text, entry.id.text) self.assertEqual(self.feed.entry[0].title.text, entry.title.text) self.assert_(self.feed.entry[0].resourceId.text is not None) self.assert_(self.feed.entry[0].lastModifiedBy is not None) self.assert_(self.feed.entry[0].lastViewed is not None) def testGetDocumentsListAclFeed(self): uri = ('http://docs.google.com/feeds/documents/private/full/' '-/mine?max-results=1') feed = self.client.GetDocumentListFeed(uri) feed_link = feed.entry[0].GetAclLink().href acl_feed = self.client.GetDocumentListAclFeed(feed_link) self.assert_(isinstance(acl_feed, gdata.docs.DocumentListAclFeed)) self.assert_(isinstance(acl_feed.entry[0], gdata.docs.DocumentListAclEntry)) self.assert_(acl_feed.entry[0].scope is not None) self.assert_(acl_feed.entry[0].role is not None) class DocumentListAclTest(DocumentsListServiceTest): def setUp(self): DocumentsListServiceTest.setUp(self) uri = ('http://docs.google.com/feeds/documents/private/full' '/-/mine?max-results=1') self.feed = self.client.GetDocumentListFeed(uri) self.EMAIL = 'x@example.com' self.SCOPE_TYPE = 'user' self.ROLE_VALUE = 'reader' def testCreateAndUpdateAndDeleteAcl(self): # Add new ACL scope = gdata.docs.Scope(value=self.EMAIL, type=self.SCOPE_TYPE) role = gdata.docs.Role(value=self.ROLE_VALUE) acl_entry = self.client.Post( gdata.docs.DocumentListAclEntry(scope=scope, role=role), self.feed.entry[0].GetAclLink().href, converter=gdata.docs.DocumentListAclEntryFromString) self.assert_(isinstance(acl_entry, gdata.docs.DocumentListAclEntry)) self.assertEqual(acl_entry.scope.value, self.EMAIL) self.assertEqual(acl_entry.scope.type, self.SCOPE_TYPE) self.assertEqual(acl_entry.role.value, self.ROLE_VALUE) # Update the user's role ROLE_VALUE = 'writer' acl_entry.role.value = ROLE_VALUE updated_acl_entry = self.editClient.Put( acl_entry, acl_entry.GetEditLink().href, converter=gdata.docs.DocumentListAclEntryFromString) self.assertEqual(updated_acl_entry.scope.value, self.EMAIL) self.assertEqual(updated_acl_entry.scope.type, self.SCOPE_TYPE) self.assertEqual(updated_acl_entry.role.value, ROLE_VALUE) # Delete the ACL self.editClient.Delete(updated_acl_entry.GetEditLink().href) # Make sure entry was actually deleted acl_feed = self.client.GetDocumentListAclFeed( self.feed.entry[0].GetAclLink().href) for acl_entry in acl_feed.entry: self.assert_(acl_entry.scope.value != self.EMAIL) class DocumentListCreateAndDeleteTest(DocumentsListServiceTest): def setUp(self): DocumentsListServiceTest.setUp(self) self.BLANK_TITLE = "blank.txt" self.TITLE = 'Test title' self.new_entry = gdata.docs.DocumentListEntry() self.new_entry.category.append(self.DOCUMENT_CATEGORY) def testCreateAndDeleteEmptyDocumentSlugHeaderTitle(self): created_entry = self.client.Post(self.new_entry, '/feeds/documents/private/full', extra_headers={'Slug': self.BLANK_TITLE}) self.editClient.Delete(created_entry.GetEditLink().href) self.assertEqual(created_entry.title.text, self.BLANK_TITLE) self.assertEqual(created_entry.category[0].label, 'document') def testCreateAndDeleteEmptyDocumentAtomTitle(self): self.new_entry.title = gdata.atom.Title(text=self.TITLE) created_entry = self.client.Post(self.new_entry, '/feeds/documents/private/full') self.editClient.Delete(created_entry.GetEditLink().href) self.assertEqual(created_entry.title.text, self.TITLE) self.assertEqual(created_entry.category[0].label, 'document') def testCreateAndDeleteEmptySpreadsheet(self): self.new_entry.title = gdata.atom.Title(text=self.TITLE) self.new_entry.category[0] = self.SPREADSHEET_CATEGORY created_entry = self.client.Post(self.new_entry, '/feeds/documents/private/full') self.editClient.Delete(created_entry.GetEditLink().href) self.assertEqual(created_entry.title.text, self.TITLE) self.assertEqual(created_entry.category[0].label, 'viewed') self.assertEqual(created_entry.category[1].label, 'spreadsheet') def testCreateAndDeleteEmptyPresentation(self): self.new_entry.title = gdata.atom.Title(text=self.TITLE) self.new_entry.category[0] = self.PRESENTATION_CATEGORY created_entry = self.client.Post(self.new_entry, '/feeds/documents/private/full') self.editClient.Delete(created_entry.GetEditLink().href) self.assertEqual(created_entry.title.text, self.TITLE) self.assertEqual(created_entry.category[0].label, 'viewed') self.assertEqual(created_entry.category[1].label, 'presentation') def testCreateAndDeleteFolder(self): folder_name = 'TestFolder' folder = self.client.CreateFolder(folder_name) self.assertEqual(folder.title.text, folder_name) self.editClient.Delete(folder.GetEditLink().href) def testCreateAndDeleteFolderInFolder(self): DEST_FOLDER_NAME = 'TestFolder' dest_folder = self.client.CreateFolder(DEST_FOLDER_NAME) CREATED_FOLDER_NAME = 'TestFolder2' new_folder = self.client.CreateFolder(CREATED_FOLDER_NAME, dest_folder) for category in new_folder.category: if category.scheme.startswith(gdata.docs.service.FOLDERS_SCHEME_PREFIX): self.assertEqual(new_folder.category[0].label, DEST_FOLDER_NAME) break # delete the folders we created, this will also delete the child folder dest_folder = self.client.Get(dest_folder.GetSelfLink().href) self.editClient.Delete(dest_folder.GetEditLink().href) class DocumentListMoveInAndOutOfFolderTest(DocumentsListServiceTest): def setUp(self): DocumentsListServiceTest.setUp(self) self.folder_name = 'TestFolder' self.folder = self.client.CreateFolder(self.folder_name) self.doc_title = 'TestDoc' self.ms = gdata.MediaSource(file_path='test.doc', content_type='application/msword') def tearDown(self): folder = self.client.Get(self.folder.GetSelfLink().href) self.editClient.Delete(folder.GetEditLink().href) def testUploadDocumentToFolder(self): created_entry = self.client.Upload(self.ms, self.doc_title, self.folder) for category in created_entry.category: if category.scheme.startswith(gdata.docs.service.FOLDERS_SCHEME_PREFIX): self.assertEqual(category.label, self.folder_name) break # delete the doc we created created_entry = self.client.Get(created_entry.GetSelfLink().href) match = re.search('\/(document%3A[^\/]*)\/?.*?\/(.*)$', created_entry.GetEditLink().href) edit_uri = 'http://docs.google.com/feeds/documents/private/full/' edit_uri += '%s/%s' % (match.group(1), match.group(2)) self.editClient.Delete(edit_uri) def testMoveDocumentInAndOutOfFolder(self): created_entry = self.client.Upload(self.ms, self.doc_title) moved_entry = self.client.MoveIntoFolder(created_entry, self.folder) for category in moved_entry.category: if category.scheme.startswith(gdata.docs.service.FOLDERS_SCHEME_PREFIX): self.assertEqual(category.label, self.folder_name) break self.editClient.MoveOutOfFolder(moved_entry) moved_entry = self.client.Get(moved_entry.GetSelfLink().href) for category in moved_entry.category: starts_with_folder__prefix = category.scheme.startswith( gdata.docs.service.FOLDERS_SCHEME_PREFIX) self.assert_(not starts_with_folder__prefix) created_entry = self.client.Get(created_entry.GetSelfLink().href) self.editClient.Delete(created_entry.GetEditLink().href) def testMoveFolderIntoFolder(self): dest_folder_name = 'DestFolderName' dest_folder = self.client.CreateFolder(dest_folder_name) self.client.MoveIntoFolder(self.folder, dest_folder) self.folder = self.client.Get(self.folder.GetSelfLink().href) folder_was_moved = False for category in self.folder.category: if category.term == dest_folder_name: folder_was_moved = True break self.assert_(folder_was_moved) #cleanup dest_folder = self.client.Get(dest_folder.GetSelfLink().href) self.editClient.Delete(dest_folder.GetEditLink().href) class DocumentListUploadTest(DocumentsListServiceTest): def testUploadAndDeleteDocument(self): ms = gdata.MediaSource(file_path='test.doc', content_type='application/msword') entry = self.client.Upload(ms, 'test doc') self.assertEqual(entry.title.text, 'test doc') self.assertEqual(entry.category[0].label, 'document') self.assert_(isinstance(entry, gdata.docs.DocumentListEntry)) self.editClient.Delete(entry.GetEditLink().href) def testUploadAndDeletePresentation(self): ms = gdata.MediaSource(file_path='test.ppt', content_type='application/vnd.ms-powerpoint') entry = self.client.Upload(ms, 'test preso') self.assertEqual(entry.title.text, 'test preso') self.assertEqual(entry.category[0].label, 'viewed') self.assertEqual(entry.category[1].label, 'presentation') self.assert_(isinstance(entry, gdata.docs.DocumentListEntry)) self.editClient.Delete(entry.GetEditLink().href) def testUploadAndDeleteSpreadsheet(self): ms = gdata.MediaSource(file_path='test.csv', content_type='text/csv') entry = self.client.Upload(ms, 'test spreadsheet') self.assert_(entry.title.text == 'test spreadsheet') self.assertEqual(entry.category[0].label, 'viewed') self.assertEqual(entry.category[1].label, 'spreadsheet') self.assert_(isinstance(entry, gdata.docs.DocumentListEntry)) self.editClient.Delete(entry.GetEditLink().href) class DocumentListUpdateTest(DocumentsListServiceTest): def setUp(self): DocumentsListServiceTest.setUp(self) self.TITLE = 'CreatedTestDoc' new_entry = gdata.docs.DocumentListEntry() new_entry.title = gdata.atom.Title(text=self.TITLE) new_entry.category.append(self.DOCUMENT_CATEGORY) self.created_entry = self.client.Post(new_entry, '/feeds/documents/private/full') def tearDown(self): # Delete the test doc we created self_link = self.created_entry.GetSelfLink().href entry = self.client.GetDocumentListEntry(self_link) self.editClient.Delete(entry.GetEditLink().href) def testUpdateDocumentMetadataAndContent(self): title = 'UpdatedTestDoc' # Update metadata self.created_entry.title.text = title updated_entry = self.editClient.Put(self.created_entry, self.created_entry.GetEditLink().href) self.assertEqual(updated_entry.title.text, title) # Update document's content ms = gdata.MediaSource(file_path='test.doc', content_type='application/msword') uri = updated_entry.GetEditMediaLink().href updated_entry = self.editClient.Put(ms, uri) self.assertEqual(updated_entry.title.text, title) # Append content to document data = 'data to append' ms = gdata.MediaSource(file_handle=StringIO.StringIO(data), content_type='text/plain', content_length=len(data)) uri = updated_entry.GetEditMediaLink().href + '?append=true' updated_entry = self.editClient.Put(ms, uri) class DocumentListExportTest(DocumentsListServiceTest): def testExportDocument(self): query = ('https://docs.google.com/feeds/documents/private/full' '/-/document?max-results=1') feed = self.client.QueryDocumentListFeed(query) file_paths = ['./downloadedTest.doc', './downloadedTest.html', './downloadedTest.odt', './downloadedTest.pdf', './downloadedTest.png', './downloadedTest.rtf', './downloadedTest.txt', './downloadedTest.zip'] for path in file_paths: self.client.Export(feed.entry[0], path) self.assert_(os.path.exists(path)) self.assert_(os.path.getsize(path)) os.remove(path) def testExportPresentation(self): query = ('https://docs.google.com/feeds/documents/private/full' '/-/presentation?max-results=1') feed = self.client.QueryDocumentListFeed(query) file_paths = ['./downloadedTest.pdf', './downloadedTest.ppt', './downloadedTest.swf', './downloadedTest.txt'] for path in file_paths: self.client.Export(feed.entry[0].resourceId.text, path) self.assert_(os.path.exists(path)) self.assert_(os.path.getsize(path)) os.remove(path) def testExportSpreadsheet(self): query = ('https://docs.google.com/feeds/documents/private/full' '/-/spreadsheet?max-results=1') feed = self.client.QueryDocumentListFeed(query) file_paths = ['./downloadedTest.xls', './downloadedTest.csv', './downloadedTest.pdf', './downloadedTest.ods', './downloadedTest.tsv', './downloadedTest.html'] docs_token = self.client.GetClientLoginToken() self.client.SetClientLoginToken(self.spreadsheets.GetClientLoginToken()) for path in file_paths: self.client.Export(feed.entry[0], path) self.assert_(os.path.exists(path)) self.assert_(os.path.getsize(path) > 0) os.remove(path) self.client.SetClientLoginToken(docs_token) def testExportNonExistentDocument(self): path = './ned.txt' exception_raised = False try: self.client.Export('non_existent_doc', path) except Exception, e: # expected exception_raised = True self.assert_(exception_raised) self.assert_(not os.path.exists(path)) if __name__ == '__main__': print ('DocList API Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() if client.GetClientLoginToken() is None: client.ClientLogin(username, password, source='Document List Client Unit Tests') if spreadsheets.GetClientLoginToken() is None: spreadsheets.ClientLogin(username, password, source='Document List Client Unit Tests') unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'e.bidelman (Eric Bidelman)' import os import time import unittest import gdata.client import gdata.data import gdata.gauth import gdata.docs.client import gdata.docs.data import gdata.test_config as conf class DocsTestCase(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.docs.client.DocsClient() if conf.options.get_value('ssl') == 'true': self.client.ssl = True conf.configure_client(self.client, 'DocsTest', self.client.auth_service) def tearDown(self): conf.close_client(self.client) class DocsFetchingDataTest(DocsTestCase): def testGetDocList(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetDocList') # Query using GetDocList() feed = self.client.GetDocList(limit=1) self.assert_(isinstance(feed, gdata.docs.data.DocList)) self.assertEqual(len(feed.entry), 1) def testGetDoc(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetDoc') uri = ('http://docs.google.com/feeds/default/private/full/' '-/spreadsheet?max-results=1') feed = self.client.GetDocList(uri, limit=1) self.assertEqual(len(feed.entry), 1) self.assertEqual(feed.entry[0].GetDocumentType(), 'spreadsheet') resource_id = feed.entry[0].resource_id.text entry = self.client.GetDoc(resource_id) self.assert_(isinstance(entry, gdata.docs.data.DocsEntry)) self.assert_(entry.id.text is not None) self.assert_(entry.title.text is not None) self.assert_(entry.resource_id.text is not None) self.assert_(entry.title.text is not None) def testGetAclFeed(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetAclFeed') uri = ('http://docs.google.com/feeds/default/private/full/' '-/mine?max-results=1') feed = self.client.GetDocList(uri=uri) self.assertEqual(len(feed.entry), 1) acl_feed = self.client.GetAclPermissions(feed.entry[0].resource_id.text) self.assert_(isinstance(acl_feed, gdata.docs.data.AclFeed)) self.assert_(isinstance(acl_feed.entry[0], gdata.docs.data.Acl)) self.assert_(acl_feed.entry[0].scope is not None) self.assert_(acl_feed.entry[0].role is not None) def testGetRevisionFeed(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetRevisionFeed') uri = 'http://docs.google.com/feeds/default/private/full/-/document' feed = self.client.GetDocList(uri=uri, limit=1) self.assertEqual(len(feed.entry), 1) revision_feed = self.client.GetRevisions(feed.entry[0].resource_id.text) self.assert_(isinstance(revision_feed, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revision_feed.entry[0], gdata.docs.data.Revision)) class DocsRevisionsTest(DocsTestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.docs.client.DocsClient() self.client.ssl = conf.options.get_value('ssl') == 'true' conf.configure_client(self.client, 'DocsTest', self.client.auth_service) conf.configure_cache(self.client, 'testDocsRevisions') try: self.testdoc = self.client.Create( gdata.docs.data.DOCUMENT_LABEL, 'My Doc') # Because of an etag change issue, we must sleep for a few seconds time.sleep(10) except: self.tearDown() raise try: self.testdoc = self.client.GetDoc(self.testdoc.resource_id.text) self.testfile = self.client.Upload( 'test.bin', 'My Binary File', content_type='application/octet-stream') # Because of an etag change issue, we must sleep for a few seconds time.sleep(10) self.testfile = self.client.GetDoc(self.testfile.resource_id.text) except: self.tearDown() raise def tearDown(self): if conf.options.get_value('runlive') == 'true': # Do a best effort tearDown, so pass on any exception try: self.client.Delete(self.testdoc) except: pass try: self.client.Delete(self.testfile) except: pass conf.close_client(self.client) def testArbFileRevisions(self): if not conf.options.get_value('runlive') == 'true': return revisions = self.client.GetRevisions(self.testfile.resource_id.text) self.assert_(isinstance(revisions, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revisions.entry[0], gdata.docs.data.Revision)) self.assertEqual(len(revisions.entry), 1) ms = gdata.data.MediaSource( file_path='test.bin', content_type='application/octet-stream') self.testfile.title.text = 'My Binary File Updated' self.testfile = self.client.Update(self.testfile, media_source=ms) self.assertEqual(self.testfile.title.text, 'My Binary File Updated') revisions = self.client.GetRevisions(self.testfile.resource_id.text) self.assert_(isinstance(revisions, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revisions.entry[0], gdata.docs.data.Revision)) self.assert_(isinstance(revisions.entry[1], gdata.docs.data.Revision)) self.assertEqual(len(revisions.entry), 2) self.client.Delete(revisions.entry[1], force=True) revisions = self.client.GetRevisions(self.testfile.resource_id.text) self.assert_(isinstance(revisions, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revisions.entry[0], gdata.docs.data.Revision)) self.assertEqual(len(revisions.entry), 1) def testDocRevisions(self): if not conf.options.get_value('runlive') == 'true': return revisions = self.client.GetRevisions(self.testdoc.resource_id.text) self.assert_(isinstance(revisions, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revisions.entry[0], gdata.docs.data.Revision)) self.assertEqual(len(revisions.entry), 1) ms = gdata.data.MediaSource( file_path='test.doc', content_type='application/msword') self.testdoc.title.text = 'My Doc Updated' self.testdoc = self.client.Update(self.testdoc, media_source=ms) revisions = self.client.GetRevisions(self.testdoc.resource_id.text) self.assert_(isinstance(revisions, gdata.docs.data.RevisionFeed)) self.assert_(isinstance(revisions.entry[0], gdata.docs.data.Revision)) self.assert_(isinstance(revisions.entry[1], gdata.docs.data.Revision)) self.assertEqual(len(revisions.entry), 2) class CreatingAndDeletionTest(DocsTestCase): def testCreateAndMoveDoc(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testCreateAndMoveDoc') new_folder = self.client.Create(gdata.docs.data.FOLDER_LABEL, 'My Folder') self.assertEqual(new_folder.title.text, 'My Folder') self.assertEqual(new_folder.GetDocumentType(), 'folder') new_doc = self.client.Create(gdata.docs.data.DOCUMENT_LABEL, 'My Doc', writers_can_invite=False) self.assertEqual(new_doc.GetDocumentType(), 'document') self.assertEqual(new_doc.title.text, 'My Doc') self.assertEqual(new_doc.writers_can_invite.value, 'false') # Move doc into folder new_entry = self.client.Move(new_doc, new_folder) self.assertEqual(len(new_entry.InFolders()), 1) self.assertEqual(new_entry.InFolders()[0].title, 'My Folder') # Create new spreadsheet inside the folder. new_spread = self.client.Create( gdata.docs.data.SPREADSHEET_LABEL, 'My Spread', folder_or_id=new_folder) self.assertEqual(new_spread.GetDocumentType(), 'spreadsheet') self.assertEqual(len(new_spread.InFolders()), 1) self.assertEqual(new_spread.InFolders()[0].title, 'My Folder') # Create new folder, and move spreadsheet into that folder too. new_folder2 = self.client.Create(gdata.docs.data.FOLDER_LABEL, 'My Folder2') self.assertEqual(new_folder2.title.text, 'My Folder2') self.assertEqual(new_folder2.GetDocumentType(), 'folder') moved_entry = self.client.Move( new_spread, new_folder2, keep_in_folders=True) self.assertEqual(len(moved_entry.InFolders()), 2) # Move spreadsheet to root level was_moved = self.client.Move(moved_entry) self.assert_(was_moved) spread_entry = self.client.GetDoc(moved_entry.resource_id.text) self.assertEqual(len(spread_entry.InFolders()), 0) # Clean up our mess. self.client.Delete(new_folder.GetEditLink().href, force=True) self.client.Delete(new_folder2.GetEditLink().href, force=True) self.client.Delete(new_doc.GetEditLink().href, force=True) self.client.Delete(spread_entry.GetEditLink().href, force=True) class DocumentListUploadTest(DocsTestCase): def testUploadAndDeleteDocument(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUploadAndDeleteDocument') ms = gdata.data.MediaSource(file_path='test.doc', content_type='application/msword') entry = self.client.Upload(ms, 'test doc') self.assertEqual(entry.title.text, 'test doc') self.assertEqual(entry.GetDocumentType(), 'document') self.assert_(isinstance(entry, gdata.docs.data.DocsEntry)) self.client.Delete(entry, force=True) def testUploadAndDeletePdf(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUploadAndDeletePdf') # Try passing in filename isntead of MediaSource object on this upload. entry = self.client.Upload( 'test.pdf', 'test pdf', content_type='application/pdf') self.assertEqual(entry.title.text, 'test pdf') self.assertEqual(entry.GetDocumentType(), 'pdf') self.assert_(isinstance(entry, gdata.docs.data.DocsEntry)) self.client.Delete(entry, force=True) class DocumentListExportTest(DocsTestCase): def testExportDocument(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testExportDocument') uri = 'http://docs.google.com/feeds/default/private/full/-/document' feed = self.client.GetDocList(uri=uri, limit=1) file_paths = ['./downloadedTest.doc', './downloadedTest.html', './downloadedTest.odt', './downloadedTest.pdf', './downloadedTest.png', './downloadedTest.rtf', './downloadedTest.txt', './downloadedTest.zip'] for path in file_paths: self.client.Export(feed.entry[0], path) self.assert_(os.path.exists(path)) self.assert_(os.path.getsize(path)) os.remove(path) def testExportNonExistentDocument(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testExportNonExistentDocument') path = './ned.txt' self.assert_(not os.path.exists(path)) exception_raised = False try: self.client.Export('non_existent_doc', path) except Exception, e: # expected exception_raised = True self.assert_(exception_raised) self.assert_(not os.path.exists(path)) def testDownloadPdf(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testDownloadPdf') uri = 'http://docs.google.com/feeds/default/private/full/-/pdf' feed = self.client.GetDocList(uri=uri, limit=1) path = './downloadedTest.pdf' self.client.Download(feed.entry[0], path) self.assert_(os.path.exists(path)) self.assert_(os.path.getsize(path)) os.remove(path) def suite(): return conf.build_suite([DocsFetchingDataTest, CreatingAndDeletionTest, DocumentListUploadTest, DocumentListExportTest, DocsRevisionsTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains Unit Tests for Google Profiles API. ProfilesServiceTest: Provides methods to test feeds and manipulate items. ProfilesQueryTest: Constructs a query object for the profiles feed. Extends Query. """ __author__ = 'jtoledo (Julian Toledo)' import getopt import getpass import sys import unittest import gdata.contacts import gdata.contacts.service email = '' password = '' domain = '' server = 'www.google.com' GDATA_VER_HEADER = 'GData-Version' class ProfilesServiceTest(unittest.TestCase): def setUp(self): additional_headers = {GDATA_VER_HEADER: 3} self.gd_client = gdata.contacts.service.ContactsService( contact_list=domain, additional_headers=additional_headers ) self.gd_client.email = email self.gd_client.password = password self.gd_client.source = 'GoogleInc-ProfilesPythonTest-1' self.gd_client.ProgrammaticLogin() def testGetFeedUriCustom(self): uri = self.gd_client.GetFeedUri(kind='profiles', scheme='https') self.assertEquals( 'https://%s/m8/feeds/profiles/domain/%s/full' % (server, domain), uri) def testGetProfileFeedUriDefault(self): self.gd_client.contact_list = 'domain.com' self.assertEquals('/m8/feeds/profiles/domain/domain.com/full', self.gd_client.GetFeedUri('profiles')) def testCleanUriNeedsCleaning(self): self.assertEquals('/relative/uri', self.gd_client._CleanUri( 'http://www.google.com/relative/uri')) def testCleanUriDoesNotNeedCleaning(self): self.assertEquals('/relative/uri', self.gd_client._CleanUri( '/relative/uri')) def testGetProfilesFeed(self): feed = self.gd_client.GetProfilesFeed() self.assert_(isinstance(feed, gdata.contacts.ProfilesFeed)) def testGetProfile(self): # Gets an existing entry feed = self.gd_client.GetProfilesFeed() entry = feed.entry[0] self.assert_(isinstance(entry, gdata.contacts.ProfileEntry)) self.assertEquals(entry.title.text, self.gd_client.GetProfile(entry.id.text).title.text) self.assertEquals(entry._children, self.gd_client.GetProfile(entry.id.text)._children) def testUpdateProfile(self): feed = self.gd_client.GetProfilesFeed() entry = feed.entry[1] original_occupation = entry.occupation entry.occupation = gdata.contacts.Occupation(text='TEST') updated = self.gd_client.UpdateProfile(entry.GetEditLink().href, entry) self.assertEquals('TEST', updated.occupation.text) updated.occupation = original_occupation self.gd_client.UpdateProfile(updated.GetEditLink().href, updated) if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=', 'domain=']) except getopt.error, msg: print ('Profiles Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.\n' '\nUsage: service_test.py --email=EMAIL ' '--password=PASSWORD --domain=DOMAIN\n') sys.exit(2) # Process options for option, arg in opts: if option == '--email': email = arg elif option == '--pw': password = arg elif option == '--domain': domain = arg while not email: print 'NOTE: Please run these tests only with a test account.' email = raw_input('Please enter your email: ') while not password: password = getpass.getpass('Please enter password: ') if not password: print 'Password cannot be blank.' while not domain: print 'NOTE: Please run these tests only with a test account.' domain = raw_input('Please enter your Apps domain: ') suite = unittest.makeSuite(ProfilesServiceTest) unittest.TextTestRunner().run(suite)
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'jcgregorio@google.com (Joe Gregorio)' import atom.core import atom.data import gdata.contacts.client import gdata.data import gdata.test_config as conf import unittest conf.options.register_option(conf.APPS_DOMAIN_OPTION) conf.options.register_option(conf.TARGET_USERNAME_OPTION) class ProfileTest(unittest.TestCase): def setUp(self): self.client = gdata.contacts.client.ContactsClient(domain='example.com') if conf.options.get_value('runlive') == 'true': self.client = gdata.contacts.client.ContactsClient( domain=conf.options.get_value('appsdomain')) if conf.options.get_value('ssl') == 'true': self.client.ssl = True conf.configure_client(self.client, 'ProfileTest', self.client.auth_service, True) self.client.username = conf.options.get_value('appsusername').split('@')[0] def tearDown(self): conf.close_client(self.client) def test_profiles_feed(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_profiles_feed') feed = self.client.get_profiles_feed() self.assert_(isinstance(feed, gdata.contacts.data.ProfilesFeed)) def suite(): return conf.build_suite([ProfileTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import getpass import re import unittest import urllib import atom import gdata.contacts.service import gdata.test_config as conf conf.options.register_option(conf.TEST_IMAGE_LOCATION_OPTION) class ContactsServiceTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.contacts.service.ContactsService() conf.configure_service(self.gd_client, 'ContactsServiceTest', 'cp') self.gd_client.email = conf.options.get_value('username') def tearDown(self): conf.close_service(self.gd_client) def testGetContactsFeed(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testGetContactsFeed') feed = self.gd_client.GetContactsFeed() self.assert_(isinstance(feed, gdata.contacts.ContactsFeed)) def testDefaultContactList(self): self.assertEquals('default', self.gd_client.contact_list) def testCustomContactList(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testCustomContactList') self.gd_client.contact_list = conf.options.get_value('username') feed = self.gd_client.GetContactsFeed() self.assert_(isinstance(feed, gdata.contacts.ContactsFeed)) def testGetFeedUriDefault(self): self.gd_client.contact_list = 'domain.com' self.assertEquals('/m8/feeds/contacts/domain.com/full', self.gd_client.GetFeedUri()) def testGetFeedUriCustom(self): uri = self.gd_client.GetFeedUri(kind='groups', contact_list='example.com', projection='base/batch', scheme='https') self.assertEquals( 'https://www.google.com/m8/feeds/groups/example.com/base/batch', uri) def testCreateUpdateDeleteContactAndUpdatePhoto(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testCreateUpdateDeleteContactAndUpdatePhoto') DeleteTestContact(self.gd_client) # Create a new entry new_entry = gdata.contacts.ContactEntry() new_entry.title = atom.Title(text='Elizabeth Bennet') new_entry.content = atom.Content(text='Test Notes') new_entry.email.append(gdata.contacts.Email( rel='http://schemas.google.com/g/2005#work', primary='true', address='liz@gmail.com')) new_entry.phone_number.append(gdata.contacts.PhoneNumber( rel='http://schemas.google.com/g/2005#work', text='(206)555-1212')) new_entry.organization = gdata.contacts.Organization( org_name=gdata.contacts.OrgName(text='TestCo.'), rel='http://schemas.google.com/g/2005#work') entry = self.gd_client.CreateContact(new_entry) # Generate and parse the XML for the new entry. self.assertEquals(entry.title.text, new_entry.title.text) self.assertEquals(entry.content.text, 'Test Notes') self.assertEquals(len(entry.email), 1) self.assertEquals(entry.email[0].rel, new_entry.email[0].rel) self.assertEquals(entry.email[0].address, 'liz@gmail.com') self.assertEquals(len(entry.phone_number), 1) self.assertEquals(entry.phone_number[0].rel, new_entry.phone_number[0].rel) self.assertEquals(entry.phone_number[0].text, '(206)555-1212') self.assertEquals(entry.organization.org_name.text, 'TestCo.') # Edit the entry. entry.phone_number[0].text = '(555)555-1212' updated = self.gd_client.UpdateContact(entry.GetEditLink().href, entry) self.assertEquals(updated.content.text, 'Test Notes') self.assertEquals(len(updated.phone_number), 1) self.assertEquals(updated.phone_number[0].rel, entry.phone_number[0].rel) self.assertEquals(updated.phone_number[0].text, '(555)555-1212') # Change the contact's photo. updated_photo = self.gd_client.ChangePhoto( conf.options.get_value('imgpath'), updated, content_type='image/jpeg') # Refetch the contact so that it has the new photo link updated = self.gd_client.GetContact(updated.GetSelfLink().href) self.assert_(updated.GetPhotoLink() is not None) # Fetch the photo data. hosted_image = self.gd_client.GetPhoto(updated) self.assert_(hosted_image is not None) # Delete the entry. self.gd_client.DeleteContact(updated.GetEditLink().href) def testCreateAndDeleteContactUsingBatch(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testCreateAndDeleteContactUsingBatch') # Get random data for creating contact random_contact_number = 'notRandom12' random_contact_title = 'Random Contact %s' % ( random_contact_number) # Set contact data contact = gdata.contacts.ContactEntry() contact.title = atom.Title(text=random_contact_title) contact.email = gdata.contacts.Email( address='user%s@example.com' % random_contact_number, primary='true', rel=gdata.contacts.REL_WORK) contact.content = atom.Content(text='Contact created by ' 'gdata-python-client automated test ' 'suite.') # Form a batch request batch_request = gdata.contacts.ContactsFeed() batch_request.AddInsert(entry=contact) # Execute the batch request to insert the contact. default_batch_url = gdata.contacts.service.DEFAULT_BATCH_URL batch_result = self.gd_client.ExecuteBatch(batch_request, default_batch_url) self.assertEquals(len(batch_result.entry), 1) self.assertEquals(batch_result.entry[0].title.text, random_contact_title) self.assertEquals(batch_result.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(batch_result.entry[0].batch_status.code, '201') expected_batch_url = re.compile('default').sub( urllib.quote(self.gd_client.email), gdata.contacts.service.DEFAULT_BATCH_URL) self.failUnless(batch_result.GetBatchLink().href, expected_batch_url) # Create a batch request to delete the newly created entry. batch_delete_request = gdata.contacts.ContactsFeed() batch_delete_request.AddDelete(entry=batch_result.entry[0]) batch_delete_result = self.gd_client.ExecuteBatch( batch_delete_request, batch_result.GetBatchLink().href) self.assertEquals(len(batch_delete_result.entry), 1) self.assertEquals(batch_delete_result.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEquals(batch_result.entry[0].batch_status.code, '201') def testCleanUriNeedsCleaning(self): self.assertEquals('/relative/uri', self.gd_client._CleanUri( 'http://www.google.com/relative/uri')) def testCleanUriDoesNotNeedCleaning(self): self.assertEquals('/relative/uri', self.gd_client._CleanUri( '/relative/uri')) class ContactsQueryTest(unittest.TestCase): def testConvertToStringDefaultFeed(self): query = gdata.contacts.service.ContactsQuery() self.assertEquals(str(query), '/m8/feeds/contacts/default/full') query.max_results = 10 self.assertEquals(query.ToUri(), '/m8/feeds/contacts/default/full?max-results=10') def testConvertToStringCustomFeed(self): query = gdata.contacts.service.ContactsQuery('/custom/feed/uri') self.assertEquals(str(query), '/custom/feed/uri') query.max_results = '10' self.assertEquals(query.ToUri(), '/custom/feed/uri?max-results=10') def testGroupQueryParameter(self): query = gdata.contacts.service.ContactsQuery() query.group = 'http://google.com/m8/feeds/groups/liz%40gmail.com/full/270f' self.assertEquals(query.ToUri(), '/m8/feeds/contacts/default/full' '?group=http%3A%2F%2Fgoogle.com%2Fm8%2Ffeeds%2Fgroups' '%2Fliz%2540gmail.com%2Ffull%2F270f') class ContactsGroupsTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.contacts.service.ContactsService() conf.configure_service(self.gd_client, 'ContactsServiceTest', 'cp') def tearDown(self): conf.close_service(self.gd_client) def testCreateUpdateDeleteGroup(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testCreateUpdateDeleteGroup') test_group = gdata.contacts.GroupEntry(title=atom.Title( text='test group py')) new_group = self.gd_client.CreateGroup(test_group) self.assert_(isinstance(new_group, gdata.contacts.GroupEntry)) self.assertEquals(new_group.title.text, 'test group py') # Change the group's title new_group.title.text = 'new group name py' updated_group = self.gd_client.UpdateGroup(new_group.GetEditLink().href, new_group) self.assertEquals(updated_group.title.text, new_group.title.text) # Remove the group self.gd_client.DeleteGroup(updated_group.GetEditLink().href) # Utility methods. def DeleteTestContact(client): # Get test contact feed = client.GetContactsFeed() for entry in feed.entry: if (entry.title.text == 'Elizabeth Bennet' and entry.content.text == 'Test Notes' and entry.email[0].address == 'liz@gmail.com'): client.DeleteContact(entry.GetEditLink().href) def suite(): return unittest.TestSuite((unittest.makeSuite(ContactsServiceTest, 'test'), unittest.makeSuite(ContactsQueryTest, 'test'), unittest.makeSuite(ContactsGroupsTest, 'test'),)) if __name__ == '__main__': print ('Contacts Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.test_config as conf import gdata.contacts.client import atom.core import atom.data import gdata.data class ContactsTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.contacts.client.ContactsClient() conf.configure_client(self.client, 'ContactsTest', 'cp') def tearDown(self): conf.close_client(self.client) def test_create_update_delete_contact(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete_contact') new_contact = gdata.contacts.data.ContactEntry( nickname=gdata.contacts.data.NickName(text='Joe'), name=gdata.data.Name( given_name=gdata.data.GivenName(text='Joseph'), family_name=gdata.data.FamilyName(text='Testerson'))) new_contact.birthday = gdata.contacts.data.Birthday(when='2009-11-11') new_contact.language.append(gdata.contacts.data.Language( label='German')) created = self.client.create_contact(new_contact) # Add another language. created.language.append(gdata.contacts.data.Language( label='French')) # Create a new membership group for our test contact. new_group = gdata.contacts.data.GroupEntry( title=atom.data.Title(text='a test group')) created_group = self.client.create_group(new_group) self.assert_(created_group.id.text) # Add the contact to the new group. created.group_membership_info.append( gdata.contacts.data.GroupMembershipInfo(href=created_group.id.text)) # Upload the changes to the language and group membership. edited = self.client.update(created) # Delete the group and the test contact. self.client.delete(created_group) self.client.delete(edited) def test_low_level_create_update_delete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_low_level_create_update_delete') entry = atom.data.Entry() entry.title = atom.data.Title(text='Jeff') entry._other_elements.append( gdata.data.Email(rel=gdata.data.WORK_REL, address='j.s@google.com')) http_request = atom.http_core.HttpRequest() http_request.add_body_part(entry.to_string(), 'application/atom+xml') posted = self.client.request('POST', 'http://www.google.com/m8/feeds/contacts/default/full', desired_class=atom.data.Entry, http_request=http_request) self_link = None edit_link = None for link in posted.get_elements('link', 'http://www.w3.org/2005/Atom'): if link.get_attributes('rel')[0].value == 'self': self_link = link.get_attributes('href')[0].value elif link.get_attributes('rel')[0].value == 'edit': edit_link = link.get_attributes('href')[0].value self.assert_(self_link is not None) self.assert_(edit_link is not None) etag = posted.get_attributes('etag')[0].value self.assert_(etag is not None) self.assert_(len(etag) > 0) # Delete the test contact. http_request = atom.http_core.HttpRequest() http_request.headers['If-Match'] = etag self.client.request('DELETE', edit_link, http_request=http_request) def suite(): return conf.build_suite([ContactsTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.lliabraa@google.com (Lane LiaBraaten)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.calendar import gdata.calendar.service import gdata.service import random import getpass from gdata import test_data username = '' password = '' class CalendarServiceAclUnitTest(unittest.TestCase): _aclFeedUri = "/calendar/feeds/default/acl/full" _aclEntryUri = "%s/user:%s" % (_aclFeedUri, "user@gmail.com",) def setUp(self): self.cal_client = gdata.calendar.service.CalendarService() self.cal_client.email = username self.cal_client.password = password self.cal_client.source = 'GCalendarClient ACL "Unit" Tests' def tearDown(self): # No teardown needed pass def _getRandomNumber(self): """Return a random number as a string for testing""" r = random.Random() r.seed() return str(r.randint(100000,1000000)) def _generateAclEntry(self, role="owner", scope_type="user", scope_value=None): """Generates a ACL rule from parameters or makes a random user an owner by default""" if (scope_type=="user" and scope_value is None): scope_value = "user%s@gmail.com" % (self._getRandomNumber()) rule = gdata.calendar.CalendarAclEntry() rule.title = atom.Title(text=role) rule.scope = gdata.calendar.Scope(value=scope_value, type="user") rule.role = gdata.calendar.Role(value="http://schemas.google.com/gCal/2005#%s" % (role)) return rule def assertEqualAclEntry(self, expected, actual): """Compares the values of two ACL entries""" self.assertEqual(expected.role.value, actual.role.value) self.assertEqual(expected.scope.value, actual.scope.value) self.assertEqual(expected.scope.type, actual.scope.type) def testGetAclFeedUnauthenticated(self): """Fiendishly try to get an ACL feed without authenticating""" try: self.cal_client.GetCalendarAclFeed(self._aclFeedUri) self.fail("Unauthenticated request should fail") except gdata.service.RequestError, error: self.assertEqual(error[0]['status'], 401) self.assertEqual(error[0]['reason'], "Authorization required") def testGetAclFeed(self): """Get an ACL feed""" self.cal_client.ProgrammaticLogin() feed = self.cal_client.GetCalendarAclFeed(self._aclFeedUri) self.assertNotEqual(0,len(feed.entry)) def testGetAclEntryUnauthenticated(self): """Fiendishly try to get an ACL entry without authenticating""" try: self.cal_client.GetCalendarAclEntry(self._aclEntryUri) self.fail("Unauthenticated request should fail"); except gdata.service.RequestError, error: self.assertEqual(error[0]['status'], 401) self.assertEqual(error[0]['reason'], "Authorization required") def testGetAclEntry(self): """Get an ACL entry""" self.cal_client.ProgrammaticLogin() self.cal_client.GetCalendarAclEntry(self._aclEntryUri) def testCalendarAclFeedFromString(self): """Create an ACL feed from a hard-coded string""" aclFeed = gdata.calendar.CalendarAclFeedFromString(test_data.ACL_FEED) self.assertEqual("Elizabeth Bennet's access control list", aclFeed.title.text) self.assertEqual(2,len(aclFeed.entry)) def testCalendarAclEntryFromString(self): """Create an ACL entry from a hard-coded string""" aclEntry = gdata.calendar.CalendarAclEntryFromString(test_data.ACL_ENTRY) self.assertEqual("owner", aclEntry.title.text) self.assertEqual("user", aclEntry.scope.type) self.assertEqual("liz@gmail.com", aclEntry.scope.value) self.assertEqual("http://schemas.google.com/gCal/2005#owner", aclEntry.role.value) def testCreateAndDeleteAclEntry(self): """Add an ACL rule and verify that is it returned in the ACL feed. Then delete the rule and verify that the rule is no longer included in the ACL feed.""" # Get the current number of ACL rules self.cal_client.ProgrammaticLogin() aclFeed = self.cal_client.GetCalendarAclFeed(self._aclFeedUri) original_rule_count = len(aclFeed.entry) # Insert entry rule = self._generateAclEntry() returned_rule = self.cal_client.InsertAclEntry(rule, self._aclFeedUri) # Verify rule was added with correct ACL values aclFeed = self.cal_client.GetCalendarAclFeed(self._aclFeedUri) self.assertEqual(original_rule_count+1, len(aclFeed.entry)) self.assertEqualAclEntry(rule, returned_rule) # Delete the event self.cal_client.DeleteAclEntry(returned_rule.GetEditLink().href) aclFeed = self.cal_client.GetCalendarAclFeed(self._aclFeedUri) self.assertEquals(original_rule_count, len(aclFeed.entry)) def testUpdateAclChangeScopeValue(self): """Fiendishly try to insert a test ACL rule and attempt to change the scope value (i.e. username). Verify that an exception is thrown, then delete the test rule.""" # Insert a user-scoped owner role ot random user aclEntry = self._generateAclEntry("owner","user"); self.cal_client.ProgrammaticLogin() rule = self._generateAclEntry() returned_rule = self.cal_client.InsertAclEntry(rule, self._aclFeedUri) # Change the scope value (i.e. what user is the owner) and update the entry updated_rule = returned_rule updated_rule.scope.value = "user_%s@gmail.com" % (self._getRandomNumber()) try: returned_rule = self.cal_client.UpdateAclEntry(returned_rule.GetEditLink().href, updated_rule) except gdata.service.RequestError, error: self.assertEqual(error[0]['status'], 403) self.assertEqual(error[0]['reason'], "Forbidden") self.cal_client.DeleteAclEntry(updated_rule.GetEditLink().href) def testUpdateAclChangeScopeType(self): """Fiendishly try to insert a test ACL rule and attempt to change the scope type (i.e. from 'user' to 'domain'). Verify that an exception is thrown, then delete the test rule.""" # Insert a user-scoped owner role ot random user aclEntry = self._generateAclEntry("owner","user"); self.cal_client.ProgrammaticLogin() rule = self._generateAclEntry() returned_rule = self.cal_client.InsertAclEntry(rule, self._aclFeedUri) # Change the scope value (i.e. what user is the owner) and update the entry updated_rule = returned_rule updated_rule.scope.type = "domain" try: returned_rule = self.cal_client.UpdateAclEntry(returned_rule.GetEditLink().href, updated_rule) except gdata.service.RequestError, error: self.assertEqual(error[0]['status'], 403) self.assertEqual(error[0]['reason'], "Forbidden") self.cal_client.DeleteAclEntry(updated_rule.GetEditLink().href) def testUpdateAclChangeRoleValue(self): """Insert a test ACL rule and attempt to change the scope type (i.e. from 'owner' to 'editor'). Verify that an exception is thrown, then delete the test rule.""" # Insert a user-scoped owner role ot random user aclEntry = self._generateAclEntry("owner","user"); self.cal_client.ProgrammaticLogin() rule = self._generateAclEntry() returned_rule = self.cal_client.InsertAclEntry(rule, self._aclFeedUri) # Change the scope value (i.e. what user is the owner) and update the entry updated_rule = returned_rule updated_rule.role.value = "http://schemas.google.com/gCal/2005#editor" returned_rule = self.cal_client.UpdateAclEntry(returned_rule.GetEditLink().href, updated_rule) self.assertEqualAclEntry(updated_rule, returned_rule) self.cal_client.DeleteAclEntry(updated_rule.GetEditLink().href) if __name__ == '__main__': print ('NOTE: Please run these tests only with a test account. ' + 'The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.rboyd@google.com (Ryan Boyd)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import atom.mock_http import gdata.calendar import gdata.calendar.service import random import getpass username = '' password = '' class CalendarServiceUnitTest(unittest.TestCase): def setUp(self): self.cal_client = gdata.calendar.service.CalendarService() self.cal_client.email = username self.cal_client.password = password self.cal_client.source = 'GCalendarClient "Unit" Tests' def tearDown(self): # No teardown needed pass def testUrlScrubbing(self): self.assertEquals(self.cal_client._RemoveStandardUrlPrefix( '/test'), '/test') self.assertEquals(self.cal_client._RemoveStandardUrlPrefix( 'http://www.google.com/calendar/test'), '/calendar/test') self.assertEquals(self.cal_client._RemoveStandardUrlPrefix( 'https://www.google.com/calendar/test'), 'https://www.google.com/calendar/test') def testPostUpdateAndDeleteSubscription(self): """Test posting a new subscription, updating it, deleting it""" self.cal_client.ProgrammaticLogin() subscription_id = 'c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com' subscription_url = '%s%s' % ( 'http://www.google.com/calendar/feeds/default/allcalendars/full/', subscription_id) # Subscribe to Google Doodles calendar calendar = gdata.calendar.CalendarListEntry() calendar.id = atom.Id(text=subscription_id) returned_calendar = self.cal_client.InsertCalendarSubscription(calendar) self.assertEquals(subscription_url, returned_calendar.id.text) self.assertEquals('Google Doodles', returned_calendar.title.text) # Update subscription calendar_to_update = self.cal_client.GetCalendarListEntry(subscription_url) self.assertEquals('Google Doodles', calendar_to_update.title.text) self.assertEquals('true', calendar_to_update.selected.value) calendar_to_update.selected.value = 'false' self.assertEquals('false', calendar_to_update.selected.value) updated_calendar = self.cal_client.UpdateCalendar(calendar_to_update) self.assertEquals('false', updated_calendar.selected.value) # Delete subscription response = self.cal_client.DeleteCalendarEntry( returned_calendar.GetEditLink().href) self.assertEquals(True, response) def testPostUpdateAndDeleteCalendar(self): """Test posting a new calendar, updating it, deleting it""" self.cal_client.ProgrammaticLogin() # New calendar to create title='Little League Schedule' description='This calendar contains practice and game times' time_zone='America/Los_Angeles' hidden=False location='Oakland' color='#2952A3' # Calendar object calendar = gdata.calendar.CalendarListEntry() calendar.title = atom.Title(text=title) calendar.summary = atom.Summary(text=description) calendar.where = gdata.calendar.Where(value_string=location) calendar.color = gdata.calendar.Color(value=color) calendar.timezone = gdata.calendar.Timezone(value=time_zone) if hidden: calendar.hidden = gdata.calendar.Hidden(value='true') else: calendar.hidden = gdata.calendar.Hidden(value='false') # Create calendar new_calendar = self.cal_client.InsertCalendar(new_calendar=calendar) self.assertEquals(title, new_calendar.title.text) self.assertEquals(description, new_calendar.summary.text) self.assertEquals(location, new_calendar.where.value_string) self.assertEquals(color, new_calendar.color.value) self.assertEquals(time_zone, new_calendar.timezone.value) if hidden: self.assertEquals('true', new_calendar.hidden.value) else: self.assertEquals('false', new_calendar.hidden.value) # Update calendar calendar_to_update = self.cal_client.GetCalendarListEntry( new_calendar.id.text) updated_title = 'This is the updated title' calendar_to_update.title.text = updated_title updated_calendar = self.cal_client.UpdateCalendar(calendar_to_update) self.assertEquals(updated_title, updated_calendar.title.text) # Delete calendar calendar_to_delete = self.cal_client.GetCalendarListEntry( new_calendar.id.text) self.cal_client.Delete(calendar_to_delete.GetEditLink().href) return new_calendar def testPostAndDeleteExtendedPropertyEvent(self): """Test posting a new entry with an extended property, deleting it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000,1000000)) random_event_title = 'My Random Extended Property Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append(atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.extended_property.append(gdata.calendar.ExtendedProperty( name='prop test name', value='prop test value')) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent(event, '/calendar/feeds/default/private/full') self.assertEquals(event.extended_property[0].value, new_event.extended_property[0].value) # Delete the event self.cal_client.DeleteEvent(new_event.GetEditLink().href) # WARNING: Due to server-side issues, this test takes a while (~60seconds) def testPostEntryWithCommentAndDelete(self): """Test posting a new entry with an extended property, deleting it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000,1000000)) random_event_title = 'My Random Comments Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append(atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent(event, '/calendar/feeds/default/private/full') # Get comments feed comments_url = new_event.comments.feed_link.href comments_query = gdata.calendar.service.CalendarEventCommentQuery(comments_url) comments_feed = self.cal_client.CalendarQuery(comments_query) # Add comment comments_entry = gdata.calendar.CalendarEventCommentEntry() comments_entry.content = atom.Content(text='Comments content') comments_entry.author.append( atom.Author(name=atom.Name(text='GData Test user'), email=atom.Email(text=username))) new_comments_entry = self.cal_client.InsertEventComment(comments_entry, comments_feed.GetPostLink().href) # Delete the event event_to_delete = self.cal_client.GetCalendarEventEntry(new_event.id.text) self.cal_client.DeleteEvent(event_to_delete.GetEditLink().href) def testPostQueryUpdateAndDeleteEvents(self): """Test posting a new entry, updating it, deleting it, querying for it""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000,1000000)) random_event_title = 'My Random Test Event %s' % random_event_number random_start_hour = (r.randint(1,1000000) % 23) random_end_hour = random_start_hour + 1 non_random_start_minute = 0 non_random_end_minute = 0 random_month = (r.randint(1,1000000) % 12 + 1) random_day_of_month = (r.randint(1,1000000) % 28 + 1) non_random_year = 2008 start_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_start_hour, non_random_start_minute,) end_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_end_hour, non_random_end_minute,) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append(atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.where.append(gdata.calendar.Where(value_string='Down by the river')) event.when.append(gdata.calendar.When(start_time=start_time,end_time=end_time)) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent(event, '/calendar/feeds/default/private/full') # Ensure that atom data returned from calendar server equals atom data sent self.assertEquals(event.title.text, new_event.title.text) self.assertEquals(event.content.text, new_event.content.text) # Ensure that gd:where data returned from calendar equals value sent self.assertEquals(event.where[0].value_string, new_event.where[0].value_string) # Commented out as dateutil is not in this repository # Ensure that dates returned from calendar server equals dates sent #start_time_py = parse(event.when[0].start_time) #start_time_py_new = parse(new_event.when[0].start_time) #self.assertEquals(start_time_py, start_time_py_new) #end_time_py = parse(event.when[0].end_time) #end_time_py_new = parse(new_event.when[0].end_time) #self.assertEquals(end_time_py, end_time_py_new) # Update event event_to_update = new_event updated_title_text = event_to_update.title.text + ' - UPDATED' event_to_update.title = atom.Title(text=updated_title_text) updated_event = self.cal_client.UpdateEvent( event_to_update.GetEditLink().href, event_to_update) # Ensure that updated title was set in the updated event self.assertEquals(event_to_update.title.text, updated_event.title.text) # Delete the event self.cal_client.DeleteEvent(updated_event.GetEditLink().href) # Ensure deleted event is marked as canceled in the feed after_delete_query = gdata.calendar.service.CalendarEventQuery() after_delete_query.updated_min = '2007-01-01' after_delete_query.text_query = str(random_event_number) after_delete_query.max_results = '1' after_delete_query_result = self.cal_client.CalendarQuery( after_delete_query) # Ensure feed returned at max after_delete_query.max_results events self.assert_( len(after_delete_query_result.entry) <= after_delete_query.max_results) # Ensure status of returned event is canceled self.assertEquals(after_delete_query_result.entry[0].event_status.value, 'CANCELED') def testEventWithSyncEventAndUID(self): """Test posting a new entry (with syncEvent and a UID) and deleting it.""" # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000,1000000)) random_event_title = 'My Random Test Event %s' % random_event_number random_start_hour = (r.randint(1,1000000) % 23) random_end_hour = random_start_hour + 1 non_random_start_minute = 0 non_random_end_minute = 0 random_month = (r.randint(1,1000000) % 12 + 1) random_day_of_month = (r.randint(1,1000000) % 28 + 1) non_random_year = 2008 start_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_start_hour, non_random_start_minute,) end_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % ( non_random_year, random_month, random_day_of_month, random_end_hour, non_random_end_minute,) # create a random event ID. I'm mimicing an example from outlook here, # the format doesn't seem to be important per the RFC except for being # globally unique. uid_string = '' for i in xrange(121): uid_string += "%X" % r.randint(0, 0xf) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append(atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') event.where.append(gdata.calendar.Where(value_string='Down by the river')) event.when.append(gdata.calendar.When( start_time=start_time,end_time=end_time)) event.sync_event = gdata.calendar.SyncEvent('true') event.uid = gdata.calendar.UID(value=uid_string) # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent(event, '/calendar/feeds/default/private/full') # Inserting it a second time should fail, as it'll have the same UID try: bad_event = self.cal_client.InsertEvent(event, '/calendar/feeds/default/private/full') self.fail('Was able to insert an event with a duplicate UID') except gdata.service.RequestError, error: # for the current problem with redirects, just re-raise so the # failure doesn't seem to be because of the duplicate UIDs. status = error[0]['status'] if status == 302: raise # otherwise, make sure it was the right error self.assertEquals(error[0]['status'], 409) self.assertEquals(error[0]['reason'], 'Conflict') # Ensure that atom data returned from calendar server equals atom data # sent self.assertEquals(event.title.text, new_event.title.text) self.assertEquals(event.content.text, new_event.content.text) # Ensure that gd:where data returned from calendar equals value sent self.assertEquals(event.where[0].value_string, new_event.where[0].value_string) # Delete the event self.cal_client.DeleteEvent(new_event.GetEditLink().href) def testCreateAndDeleteEventUsingBatch(self): # Get random data for creating event r = random.Random() r.seed() random_event_number = str(r.randint(100000,1000000)) random_event_title = 'My Random Comments Test Event %s' % ( random_event_number) # Set event data event = gdata.calendar.CalendarEventEntry() event.author.append(atom.Author(name=atom.Name(text='GData Test user'))) event.title = atom.Title(text=random_event_title) event.content = atom.Content(text='Picnic with some lunch') # Form a batch request batch_request = gdata.calendar.CalendarEventFeed() batch_request.AddInsert(entry=event) # Execute the batch request to insert the event. self.cal_client.ProgrammaticLogin() batch_result = self.cal_client.ExecuteBatch(batch_request, gdata.calendar.service.DEFAULT_BATCH_URL) self.assertEquals(len(batch_result.entry), 1) self.assertEquals(batch_result.entry[0].title.text, random_event_title) self.assertEquals(batch_result.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(batch_result.GetBatchLink().href, gdata.calendar.service.DEFAULT_BATCH_URL) # Create a batch request to delete the newly created entry. batch_delete_request = gdata.calendar.CalendarEventFeed() batch_delete_request.AddDelete(entry=batch_result.entry[0]) batch_delete_result = self.cal_client.ExecuteBatch(batch_delete_request, batch_result.GetBatchLink().href) self.assertEquals(len(batch_delete_result.entry), 1) self.assertEquals(batch_delete_result.entry[0].batch_operation.type, gdata.BATCH_DELETE) def testCorrectReturnTypesForGetMethods(self): self.cal_client.ProgrammaticLogin() result = self.cal_client.GetCalendarEventFeed() self.assertEquals(isinstance(result, gdata.calendar.CalendarEventFeed), True) def testValidHostName(self): mock_http = atom.mock_http.MockHttpClient() response = atom.mock_http.MockResponse(body='<entry/>', status=200, reason='OK') mock_http.add_response(response, 'GET', 'https://www.google.com/calendar/feeds/default/allcalendars/full') self.cal_client.ssl = True self.cal_client.http_client = mock_http self.cal_client.SetAuthSubToken('foo') self.assertEquals(str(self.cal_client.token_store.find_token( 'https://www.google.com/calendar/feeds/default/allcalendars/full')), 'AuthSub token=foo') resp = self.cal_client.Get('/calendar/feeds/default/allcalendars/full') self.assert_(resp is not None) class CalendarEventQueryUnitTest(unittest.TestCase): def setUp(self): self.query = gdata.calendar.service.CalendarEventQuery() def testOrderByValidatesValues(self): self.query.orderby = 'lastmodified' self.assertEquals(self.query.orderby, 'lastmodified') try: self.query.orderby = 'illegal input' self.fail() except gdata.calendar.service.Error: self.assertEquals(self.query.orderby, 'lastmodified') def testSortOrderValidatesValues(self): self.query.sortorder = 'a' self.assertEquals(self.query.sortorder, 'a') try: self.query.sortorder = 'illegal input' self.fail() except gdata.calendar.service.Error: self.assertEquals(self.query.sortorder, 'a') def testTimezoneParameter(self): self.query.ctz = 'America/Los_Angeles' self.assertEquals(self.query['ctz'], 'America/Los_Angeles') self.assert_(self.query.ToUri().find('America%2FLos_Angeles') > -1) if __name__ == '__main__': print ('Google Calendar Test\nNOTE: Please run these tests only with a ' 'test account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'Alexandre Vivien <alex@simplecode.fr>' import unittest import gdata.client import gdata.data import gdata.gauth import gdata.marketplace.client import gdata.marketplace.data import gdata.test_config as conf conf.options.register_option(conf.APPS_DOMAIN_OPTION) class LicensingClientTest(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) gdata.test_config.options.register( 'appsid', 'Enter the Application ID of your Marketplace application', description='The Application ID of your Marketplace application') gdata.test_config.options.register( 'appsconsumerkey', 'Enter the Consumer Key of your Marketplace application', description='The Consumer Key of your Marketplace application') gdata.test_config.options.register( 'appsconsumersecret', 'Enter the Consumer Secret of your Marketplace application', description='The Consumer Secret of your Marketplace application') def setUp(self): self.client = gdata.marketplace.client.LicensingClient(domain='example.com') if conf.options.get_value('runlive') == 'true': self.client = gdata.marketplace.client.LicensingClient(domain=conf.options.get_value('appsdomain')) conf.configure_client(self.client, 'LicensingClientTest', self.client.auth_service, True) self.client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(conf.options.get_value('appsconsumerkey'), conf.options.get_value('appsconsumersecret'), '') self.client.source = 'GData-Python-Client-Test' self.client.account_type='HOSTED' self.client.http_client.debug = True self.app_id = conf.options.get_value('appsid') def tearDown(self): conf.close_client(self.client) def testGetLicense(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetLicense') fetched_feed = self.client.GetLicense(app_id=self.app_id) self.assertTrue(isinstance(fetched_feed, gdata.marketplace.data.LicenseFeed)) self.assertTrue(isinstance(fetched_feed.entry[0], gdata.marketplace.data.LicenseEntry)) entity = fetched_feed.entry[0].content.entity self.assertTrue(entity is not None) self.assertNotEqual(entity.id, '') self.assertNotEqual(entity.enabled, '') self.assertNotEqual(entity.customer_id, '') self.assertNotEqual(entity.state, '') def testGetLicenseNotifications(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testGetLicenseNotifications') fetched_feed = self.client.GetLicenseNotifications(app_id=self.app_id, max_results=2) self.assertTrue(isinstance(fetched_feed, gdata.marketplace.data.LicenseFeed)) self.assertEqual(len(fetched_feed.entry), 2) for entry in fetched_feed.entry: entity = entry.content.entity self.assertTrue(entity is not None) self.assertNotEqual(entity.id, '') self.assertNotEqual(entity.domain_name, '') self.assertNotEqual(entity.installer_email, '') self.assertNotEqual(entity.tos_acceptance_time, '') self.assertNotEqual(entity.last_change_time, '') self.assertNotEqual(entity.product_config_id, '') self.assertNotEqual(entity.state, '') next_uri = fetched_feed.find_next_link() fetched_feed_next = self.client.GetLicenseNotifications(uri=next_uri) self.assertTrue(isinstance(fetched_feed_next, gdata.marketplace.data.LicenseFeed)) self.assertTrue(len(fetched_feed_next.entry) <= 2) for entry in fetched_feed_next.entry: entity = entry.content.entity self.assertTrue(entity is not None) self.assertNotEqual(entity.id, '') self.assertNotEqual(entity.domain_name, '') self.assertNotEqual(entity.installer_email, '') self.assertNotEqual(entity.tos_acceptance_time, '') self.assertNotEqual(entity.last_change_time, '') self.assertNotEqual(entity.product_config_id, '') self.assertNotEqual(entity.state, '') def suite(): return conf.build_suite([LicensingClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeffrey Scudder)' import getpass import time import unittest import StringIO import gdata.photos.service import gdata.photos import atom username = '' password = '' test_image_location = '../../testimage.jpg' test_image_name = 'testimage.jpg' class PhotosServiceTest(unittest.TestCase): def setUp(self): # Initialize the client and create a new album for testing. self.client = gdata.photos.service.PhotosService() self.client.email = username self.client.password = password self.client.source = 'Photos Client Unit Tests' self.client.ProgrammaticLogin() # Give the album a unique title by appending the current time. self.test_album = self.client.InsertAlbum( 'Python library test' + str(time.time()), 'A temporary test album.') def testUploadGetAndDeletePhoto(self): image_entry = self.client.InsertPhotoSimple(self.test_album, 'test', 'a pretty testing picture', test_image_location) self.assert_(image_entry.title.text == 'test') results_feed = self.client.SearchUserPhotos('test') self.assert_(len(results_feed.entry) > 0) self.client.Delete(image_entry) def testInsertPhotoUpdateBlobAndDelete(self): new_entry = gdata.photos.PhotoEntry() new_entry.title = atom.Title(text='a_test_image') new_entry.summary = atom.Summary(text='Just a test.') new_entry.category.append(atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/photos/2007#photo')) entry = self.client.InsertPhoto(self.test_album, new_entry, test_image_location, content_type='image/jpeg') self.assert_(entry.id.text) updated_entry = self.client.UpdatePhotoBlob(entry, test_image_location) self.assert_(entry.GetEditLink().href != updated_entry.GetEditLink().href) self.client.Delete(updated_entry) def tearDown(self): # Delete the test album. test_album = self.client.GetEntry(self.test_album.GetSelfLink().href) self.client.Delete(test_album) if __name__ == '__main__': print ('Google Photos test\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Content API for Shopping tests""" __author__ = 'afshar (Ali Afshar)' import unittest from gdata.contentforshopping import client, data class CFSClientTest(unittest.TestCase): def test_uri_missing_account_id(self): c = client.ContentForShoppingClient() self.assertRaises(ValueError, c._create_uri, account_id=None, projection=None, resource='a/b') def test_uri_bad_projection(self): c = client.ContentForShoppingClient() self.assertRaises(ValueError, c._create_uri, account_id='123', projection='banana', resource='a/b') def test_good_default_account_id(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection=None, resource='a/b') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/a/b/generic') def test_override_request_account_id(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id='321', projection=None, resource='a/b') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/321/a/b/generic') def test_default_projection(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection=None, resource='a/b') self.assertEqual(c.cfs_projection, 'generic') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/a/b/generic') def test_default_projection_change(self): c = client.ContentForShoppingClient(account_id='123', projection='schema') uri = c._create_uri(account_id=None, projection=None, resource='a/b') self.assertEqual(c.cfs_projection, 'schema') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/a/b/schema') def test_request_projection(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection='schema', resource='a/b') self.assertEqual(c.cfs_projection, 'generic') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/a/b/schema') def test_request_resource(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection=None, resource='x/y/z') self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/x/y/z/generic') def test_path_single(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection=None, resource='r', path=['1']) self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/r/generic/1') def test_path_multiple(self): c = client.ContentForShoppingClient(account_id='123') uri = c._create_uri(account_id=None, projection=None, resource='r', path=['1', '2']) self.assertEqual(uri, 'https://content.googleapis.com/content/v1/123/r/generic/1/2') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2008, 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.client import gdata.gauth import gdata.data import atom.mock_http_core import StringIO class ClientLoginTest(unittest.TestCase): def test_token_request(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK', 'SID=DQAAAGgA...7Zg8CTN\n' 'LSID=DQAAAGsA...lk8BBbG\n' 'Auth=DQAAAGgA...dk3fA5N', {'Content-Type': 'text/plain'}) token = client.request_client_login_token('email', 'pw', 'cp', 'test') self.assert_(isinstance(token, gdata.gauth.ClientLoginToken)) self.assertEqual(token.token_string, 'DQAAAGgA...dk3fA5N') # Test a server response without a ClientLogin token.` client.http_client.set_response(200, 'OK', 'SID=12345\nLSID=34567', {}) self.assertRaises(gdata.client.ClientLoginTokenMissing, client.request_client_login_token, 'email', 'pw', '', '') # Test a 302 redirect from the server on a login request. client.http_client.set_response(302, 'ignored', '', {}) # TODO: change the exception class to one in gdata.client. self.assertRaises(gdata.client.BadAuthenticationServiceURL, client.request_client_login_token, 'email', 'pw', '', '') # Test a CAPTCHA challenge from the server client.http_client.set_response(403, 'Access Forbidden', 'Url=http://www.google.com/login/captcha\n' 'Error=CaptchaRequired\n' 'CaptchaToken=DQAAAGgA...dkI1LK9\n' # TODO: verify this sample CAPTCHA URL matches an # actual challenge from the server. 'CaptchaUrl=Captcha?ctoken=HiteT4bVoP6-yFkHPibe7O9EqxeiI7lUSN', {}) try: token = client.request_client_login_token('email', 'pw', '', '') self.fail('should raise a CaptchaChallenge on a 403 with a ' 'CaptchRequired error.') except gdata.client.CaptchaChallenge, challenge: self.assertEquals(challenge.captcha_url, 'http://www.google.com/accounts/' 'Captcha?ctoken=HiteT4bVoP6-yFkHPibe7O9EqxeiI7lUSN') self.assertEquals(challenge.captcha_token, 'DQAAAGgA...dkI1LK9') # Test an unexpected response, a 404 for example. client.http_client.set_response(404, 'ignored', '', {}) self.assertRaises(gdata.client.ClientLoginFailed, client.request_client_login_token, 'email', 'pw', '', '') def test_client_login(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK', 'SID=DQAAAGgA...7Zg8CTN\n' 'LSID=DQAAAGsA...lk8BBbG\n' 'Auth=DQAAAGgA...dk3fA5N', {'Content-Type': 'text/plain'}) client.client_login('me@example.com', 'password', 'wise', 'unit test') self.assert_(isinstance(client.auth_token, gdata.gauth.ClientLoginToken)) self.assertEqual(client.auth_token.token_string, 'DQAAAGgA...dk3fA5N') class AuthSubTest(unittest.TestCase): def test_get_and_upgrade_token(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK', 'Token=UpgradedTokenVal\n' 'Extra data', {'Content-Type': 'text/plain'}) page_url = 'http://example.com/showcalendar.html?token=CKF50YzIHxCTKMAg' client.auth_token = gdata.gauth.AuthSubToken.from_url(page_url) self.assert_(isinstance(client.auth_token, gdata.gauth.AuthSubToken)) self.assertEqual(client.auth_token.token_string, 'CKF50YzIHxCTKMAg') upgraded = client.upgrade_token() self.assert_(isinstance(client.auth_token, gdata.gauth.AuthSubToken)) self.assertEqual(client.auth_token.token_string, 'UpgradedTokenVal') self.assertEqual(client.auth_token, upgraded) # Ensure passing in a token returns without modifying client's auth_token. client.http_client.set_response(200, 'OK', 'Token=4567', {}) upgraded = client.upgrade_token( gdata.gauth.AuthSubToken.from_url('?token=1234')) self.assertEqual(upgraded.token_string, '4567') self.assertEqual(client.auth_token.token_string, 'UpgradedTokenVal') self.assertNotEqual(client.auth_token, upgraded) # Test exception cases client.auth_token = None self.assertRaises(gdata.client.UnableToUpgradeToken, client.upgrade_token, None) self.assertRaises(gdata.client.UnableToUpgradeToken, client.upgrade_token) def test_revoke_token(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient( 200, 'OK', '', {}) page_url = 'http://example.com/showcalendar.html?token=CKF50YzIHxCTKMAg' client.auth_token = gdata.gauth.AuthSubToken.from_url(page_url) deleted = client.revoke_token() self.assert_(deleted) self.assertEqual( client.http_client.last_request.headers['Authorization'], 'AuthSub token=CKF50YzIHxCTKMAg') class OAuthTest(unittest.TestCase): def test_hmac_flow(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient( 200, 'OK', 'oauth_token=ab3cd9j4ks7&oauth_token_secret=ZXhhbXBsZS', {}) request_token = client.get_oauth_token( ['http://example.com/service'], 'http://example.net/myapp', 'consumer', consumer_secret='secret') # Check that the response was correctly parsed. self.assertEqual(request_token.token, 'ab3cd9j4ks7') self.assertEqual(request_token.token_secret, 'ZXhhbXBsZS') self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN) # Also check the Authorization header which was sent in the request. auth_header = client.http_client.last_request.headers['Authorization'] self.assert_('OAuth' in auth_header) self.assert_( 'oauth_callback="http%3A%2F%2Fexample.net%2Fmyapp"' in auth_header) self.assert_('oauth_version="1.0"' in auth_header) self.assert_('oauth_signature_method="HMAC-SHA1"' in auth_header) self.assert_('oauth_consumer_key="consumer"' in auth_header) # Check generation of the authorization URL. authorize_url = request_token.generate_authorization_url() self.assert_(str(authorize_url).startswith( 'https://www.google.com/accounts/OAuthAuthorizeToken')) self.assert_('oauth_token=ab3cd9j4ks7' in str(authorize_url)) # Check that the token information from the browser's URL is parsed. redirected_url = ( 'http://example.net/myapp?oauth_token=CKF5zz&oauth_verifier=Xhhbas') gdata.gauth.authorize_request_token(request_token, redirected_url) self.assertEqual(request_token.token, 'CKF5zz') self.assertEqual(request_token.verifier, 'Xhhbas') self.assertEqual(request_token.auth_state, gdata.gauth.AUTHORIZED_REQUEST_TOKEN) # Check that the token upgrade response was correctly parsed. client.http_client.set_response( 200, 'OK', 'oauth_token=3cd9Fj417&oauth_token_secret=Xhrh6bXBs', {}) access_token = client.get_access_token(request_token) self.assertEqual(request_token.token, '3cd9Fj417') self.assertEqual(request_token.token_secret, 'Xhrh6bXBs') self.assert_(request_token.verifier is None) self.assertEqual(request_token.auth_state, gdata.gauth.ACCESS_TOKEN) self.assertEqual(request_token.token, access_token.token) self.assertEqual(request_token.token_secret, access_token.token_secret) self.assert_(access_token.verifier is None) self.assertEqual(request_token.auth_state, access_token.auth_state) # Also check the Authorization header which was sent in the request. auth_header = client.http_client.last_request.headers['Authorization'] self.assert_('OAuth' in auth_header) self.assert_('oauth_callback="' not in auth_header) self.assert_('oauth_version="1.0"' in auth_header) self.assert_('oauth_verifier="Xhhbas"' in auth_header) self.assert_('oauth_signature_method="HMAC-SHA1"' in auth_header) self.assert_('oauth_consumer_key="consumer"' in auth_header) class RequestTest(unittest.TestCase): def test_simple_request(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.EchoHttpClient() response = client.request('GET', 'https://example.com/test') self.assertEqual(response.getheader('Echo-Host'), 'example.com:None') self.assertEqual(response.getheader('Echo-Uri'), '/test') self.assertEqual(response.getheader('Echo-Scheme'), 'https') self.assertEqual(response.getheader('Echo-Method'), 'GET') http_request = atom.http_core.HttpRequest( uri=atom.http_core.Uri(scheme='http', host='example.net', port=8080), method='POST', headers={'X': 1}) http_request.add_body_part('test', 'text/plain') response = client.request(http_request=http_request) self.assertEqual(response.getheader('Echo-Host'), 'example.net:8080') # A Uri with path set to None should default to /. self.assertEqual(response.getheader('Echo-Uri'), '/') self.assertEqual(response.getheader('Echo-Scheme'), 'http') self.assertEqual(response.getheader('Echo-Method'), 'POST') self.assertEqual(response.getheader('Content-Type'), 'text/plain') self.assertEqual(response.getheader('X'), '1') self.assertEqual(response.read(), 'test') # Use the same request object from above, but overwrite the request path # by passing in a URI. response = client.request(uri='/new/path?p=1', http_request=http_request) self.assertEqual(response.getheader('Echo-Host'), 'example.net:8080') self.assertEqual(response.getheader('Echo-Uri'), '/new/path?p=1') self.assertEqual(response.getheader('Echo-Scheme'), 'http') self.assertEqual(response.read(), 'test') def test_gdata_version_header(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.EchoHttpClient() response = client.request('GET', 'http://example.com') self.assertEqual(response.getheader('GData-Version'), None) client.api_version = '2' response = client.request('GET', 'http://example.com') self.assertEqual(response.getheader('GData-Version'), '2') def test_redirects(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.MockHttpClient() # Add the redirect response for the initial request. first_request = atom.http_core.HttpRequest('http://example.com/1', 'POST') client.http_client.add_response(first_request, 302, None, {'Location': 'http://example.com/1?gsessionid=12'}) second_request = atom.http_core.HttpRequest( 'http://example.com/1?gsessionid=12', 'POST') client.http_client.AddResponse(second_request, 200, 'OK', body='Done') response = client.Request('POST', 'http://example.com/1') self.assertEqual(response.status, 200) self.assertEqual(response.reason, 'OK') self.assertEqual(response.read(), 'Done') redirect_loop_request = atom.http_core.HttpRequest( 'http://example.com/2?gsessionid=loop', 'PUT') client.http_client.add_response(redirect_loop_request, 302, None, {'Location': 'http://example.com/2?gsessionid=loop'}) try: response = client.request(method='PUT', uri='http://example.com/2?gsessionid=loop') self.fail('Loop URL should have redirected forever.') except gdata.client.RedirectError, err: self.assert_(str(err).startswith('Too many redirects from server')) def test_lowercase_location(self): client = gdata.client.GDClient() client.http_client = atom.mock_http_core.MockHttpClient() # Add the redirect response for the initial request. first_request = atom.http_core.HttpRequest('http://example.com/1', 'POST') # In some environments, notably App Engine, the HTTP headers which come # back from a server will be normalized to all lowercase. client.http_client.add_response(first_request, 302, None, {'location': 'http://example.com/1?gsessionid=12'}) second_request = atom.http_core.HttpRequest( 'http://example.com/1?gsessionid=12', 'POST') client.http_client.AddResponse(second_request, 200, 'OK', body='Done') response = client.Request('POST', 'http://example.com/1') self.assertEqual(response.status, 200) self.assertEqual(response.reason, 'OK') self.assertEqual(response.read(), 'Done') def test_exercise_exceptions(self): # TODO pass def test_converter_vs_desired_class(self): def bad_converter(string): return 1 class TestClass(atom.core.XmlElement): _qname = '{http://www.w3.org/2005/Atom}entry' client = gdata.client.GDClient() client.http_client = atom.mock_http_core.EchoHttpClient() test_entry = gdata.data.GDEntry() result = client.post(test_entry, 'http://example.com') self.assert_(isinstance(result, gdata.data.GDEntry)) result = client.post(test_entry, 'http://example.com', converter=bad_converter) self.assertEquals(result, 1) result = client.post(test_entry, 'http://example.com', desired_class=TestClass) self.assert_(isinstance(result, TestClass)) class QueryTest(unittest.TestCase): def test_query_modifies_request(self): request = atom.http_core.HttpRequest() gdata.client.Query( text_query='foo', categories=['a', 'b']).modify_request(request) # categories param from above is named category in URL self.assertEqual(request.uri.query, {'q': 'foo', 'category': 'a,b'}) def test_client_uses_query_modification(self): """If the Query is passed as an unexpected param it should apply""" client = gdata.client.GDClient() client.http_client = atom.mock_http_core.EchoHttpClient() query = gdata.client.Query(max_results=7) client.http_client = atom.mock_http_core.SettableHttpClient( 201, 'CREATED', gdata.data.GDEntry().ToString(), {}) response = client.get('https://example.com/foo', a_random_param=query) self.assertEqual( client.http_client.last_request.uri.query['max-results'], '7') class VersionConversionTest(unittest.TestCase): def test_use_default_version(self): self.assertEquals(gdata.client.get_xml_version(None), 1) def test_str_to_int_version(self): self.assertEquals(gdata.client.get_xml_version('1'), 1) self.assertEquals(gdata.client.get_xml_version('2'), 2) self.assertEquals(gdata.client.get_xml_version('2.1.2'), 2) self.assertEquals(gdata.client.get_xml_version('10.4'), 10) class UpdateTest(unittest.TestCase): """Test Update/PUT""" def test_update_uri_editlink(self): """Test that the PUT uri is grabbed from the entry's edit link""" client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient( 200, 'OK', gdata.data.GDEntry().ToString(), {}) entry = gdata.data.GDEntry() entry.link.append(atom.data.Link(rel='edit', href='https://example.com/edit')) response = client.update(entry) request = client.http_client.last_request self.assertEqual(str(client.http_client.last_request.uri), 'https://example.com/edit') def test_update_uri(self): """Test that when passed, a uri overrides the entry's edit link""" client = gdata.client.GDClient() client.http_client = atom.mock_http_core.SettableHttpClient( 200, 'OK', gdata.data.GDEntry().ToString(), {}) entry = gdata.data.GDEntry() entry.link.append(atom.data.Link(rel='edit', href='https://example.com/edit')) response = client.update(entry, uri='https://example.com/test') self.assertEqual(str(client.http_client.last_request.uri), 'https://example.com/test') def suite(): return unittest.TestSuite((unittest.makeSuite(ClientLoginTest, 'test'), unittest.makeSuite(AuthSubTest, 'test'), unittest.makeSuite(OAuthTest, 'test'), unittest.makeSuite(RequestTest, 'test'), unittest.makeSuite(VersionConversionTest, 'test'), unittest.makeSuite(QueryTest, 'test'), unittest.makeSuite(UpdateTest, 'test'))) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeffrey Scudder)' import unittest from gdata import test_data import gdata.photos class AlbumFeedTest(unittest.TestCase): def setUp(self): self.album_feed = gdata.photos.AlbumFeedFromString(test_data.ALBUM_FEED) def testCorrectXmlParsing(self): self.assert_(self.album_feed.id.text == 'http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/1') self.assert_(self.album_feed.gphoto_id.text == '1') self.assert_(len(self.album_feed.entry) == 4) for entry in self.album_feed.entry: if entry.id.text == 'http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2': self.assert_(entry.summary.text == 'Blue') class PhotoFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.photos.PhotoFeedFromString(test_data.ALBUM_FEED) def testCorrectXmlParsing(self): for entry in self.feed.entry: if entry.id.text == 'http://picasaweb.google.com/data/entry/api/user/sample.user/albumid/1/photoid/2': self.assert_(entry.gphoto_id.text == '2') self.assert_(entry.albumid.text == '1') self.assert_(entry.exif.flash.text == 'true') self.assert_(entry.media.title.type == 'plain') self.assert_(entry.media.title.text == 'Aqua Blue.jpg') self.assert_(len(entry.media.thumbnail) == 3) class AnyFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.photos.AnyFeedFromString(test_data.ALBUM_FEED) def testEntryTypeConversion(self): for entry in self.feed.entry: if entry.id.text == 'http://picasaweb.google.com/data/feed/api/user/sample.user/albumid/': self.assert_(isinstance(entry, gdata.photos.PhotoEntry)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeffrey Scudder)' import unittest from gdata import test_data import atom import gdata.contacts class ContactEntryTest(unittest.TestCase): def setUp(self): self.entry = gdata.contacts.ContactEntryFromString(test_data.NEW_CONTACT) def testParsingTestEntry(self): self.assertEquals(self.entry.title.text, 'Fitzgerald') self.assertEquals(len(self.entry.email), 2) for email in self.entry.email: if email.rel == 'http://schemas.google.com/g/2005#work': self.assertEquals(email.address, 'liz@gmail.com') elif email.rel == 'http://schemas.google.com/g/2005#home': self.assertEquals(email.address, 'liz@example.org') self.assertEquals(len(self.entry.phone_number), 3) self.assertEquals(len(self.entry.postal_address), 1) self.assertEquals(self.entry.postal_address[0].primary, 'true') self.assertEquals(self.entry.postal_address[0].text, '1600 Amphitheatre Pkwy Mountain View') self.assertEquals(len(self.entry.im), 1) self.assertEquals(len(self.entry.group_membership_info), 1) self.assertEquals(self.entry.group_membership_info[0].href, 'http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f') self.assertEquals(self.entry.group_membership_info[0].deleted, 'false') self.assertEquals(len(self.entry.extended_property), 2) self.assertEquals(self.entry.extended_property[0].name, 'pet') self.assertEquals(self.entry.extended_property[0].value, 'hamster') self.assertEquals(self.entry.extended_property[1].name, 'cousine') self.assertEquals( self.entry.extended_property[1].GetXmlBlobExtensionElement().tag, 'italian') def testToAndFromString(self): copied_entry = gdata.contacts.ContactEntryFromString(str(self.entry)) self.assertEquals(copied_entry.title.text, 'Fitzgerald') self.assertEquals(len(copied_entry.email), 2) for email in copied_entry.email: if email.rel == 'http://schemas.google.com/g/2005#work': self.assertEquals(email.address, 'liz@gmail.com') elif email.rel == 'http://schemas.google.com/g/2005#home': self.assertEquals(email.address, 'liz@example.org') self.assertEquals(len(copied_entry.phone_number), 3) self.assertEquals(len(copied_entry.postal_address), 1) self.assertEquals(copied_entry.postal_address[0].primary, 'true') self.assertEquals(copied_entry.postal_address[0].text, '1600 Amphitheatre Pkwy Mountain View') self.assertEquals(len(copied_entry.im), 1) self.assertEquals(len(copied_entry.group_membership_info), 1) self.assertEquals(copied_entry.group_membership_info[0].href, 'http://google.com/m8/feeds/groups/liz%40gmail.com/base/270f') self.assertEquals(copied_entry.group_membership_info[0].deleted, 'false') self.assertEquals(len(copied_entry.extended_property), 2) self.assertEquals(copied_entry.extended_property[0].name, 'pet') self.assertEquals(copied_entry.extended_property[0].value, 'hamster') self.assertEquals(copied_entry.extended_property[1].name, 'cousine') self.assertEquals( copied_entry.extended_property[1].GetXmlBlobExtensionElement().tag, 'italian') def testCreateContactFromScratch(self): # Create a new entry new_entry = gdata.contacts.ContactEntry() new_entry.title = atom.Title(text='Elizabeth Bennet') new_entry.content = atom.Content(text='Test Notes') new_entry.email.append(gdata.contacts.Email( rel='http://schemas.google.com/g/2005#work', address='liz@gmail.com')) new_entry.phone_number.append(gdata.contacts.PhoneNumber( rel='http://schemas.google.com/g/2005#work', text='(206)555-1212')) new_entry.organization = gdata.contacts.Organization( org_name=gdata.contacts.OrgName(text='TestCo.')) new_entry.extended_property.append(gdata.ExtendedProperty(name='test', value='1234')) new_entry.birthday = gdata.contacts.Birthday(when='2009-7-23') sports_property = gdata.ExtendedProperty(name='sports') sports_property.SetXmlBlob('<dance><salsa/><ballroom_dancing/></dance>') new_entry.extended_property.append(sports_property) # Generate and parse the XML for the new entry. entry_copy = gdata.contacts.ContactEntryFromString(str(new_entry)) self.assertEquals(entry_copy.title.text, new_entry.title.text) self.assertEquals(entry_copy.content.text, 'Test Notes') self.assertEquals(len(entry_copy.email), 1) self.assertEquals(entry_copy.email[0].rel, new_entry.email[0].rel) self.assertEquals(entry_copy.email[0].address, 'liz@gmail.com') self.assertEquals(len(entry_copy.phone_number), 1) self.assertEquals(entry_copy.phone_number[0].rel, new_entry.phone_number[0].rel) self.assertEquals(entry_copy.birthday.when, '2009-7-23') self.assertEquals(entry_copy.phone_number[0].text, '(206)555-1212') self.assertEquals(entry_copy.organization.org_name.text, 'TestCo.') self.assertEquals(len(entry_copy.extended_property), 2) self.assertEquals(entry_copy.extended_property[0].name, 'test') self.assertEquals(entry_copy.extended_property[0].value, '1234') class ContactsFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.contacts.ContactsFeedFromString(test_data.CONTACTS_FEED) def testParsingTestFeed(self): self.assertEquals(self.feed.id.text, 'http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base') self.assertEquals(self.feed.title.text, 'Contacts') self.assertEquals(self.feed.total_results.text, '1') self.assertEquals(len(self.feed.entry), 1) self.assert_(isinstance(self.feed.entry[0], gdata.contacts.ContactEntry)) self.assertEquals(self.feed.entry[0].GetPhotoLink().href, 'http://google.com/m8/feeds/photos/media/liz%40gmail.com/c9012de') self.assertEquals(self.feed.entry[0].GetPhotoEditLink().href, 'http://www.google.com/m8/feeds/photos/media/liz%40gmail.com/' 'c9012de/photo4524') def testToAndFromString(self): copied_feed = gdata.contacts.ContactsFeedFromString(str(self.feed)) self.assertEquals(copied_feed.id.text, 'http://www.google.com/m8/feeds/contacts/liz%40gmail.com/base') self.assertEquals(copied_feed.title.text, 'Contacts') self.assertEquals(copied_feed.total_results.text, '1') self.assertEquals(len(copied_feed.entry), 1) self.assert_(isinstance(copied_feed.entry[0], gdata.contacts.ContactEntry)) class GroupsFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.contacts.GroupsFeedFromString( test_data.CONTACT_GROUPS_FEED) def testParsingGroupsFeed(self): self.assertEquals(self.feed.id.text, 'jo@gmail.com') self.assertEquals(self.feed.title.text, 'Jo\'s Contact Groups') self.assertEquals(self.feed.total_results.text, '3') self.assertEquals(len(self.feed.entry), 1) self.assert_(isinstance(self.feed.entry[0], gdata.contacts.GroupEntry)) class GroupEntryTest(unittest.TestCase): def setUp(self): self.entry = gdata.contacts.GroupEntryFromString( test_data.CONTACT_GROUP_ENTRY) def testParsingTestEntry(self): self.assertEquals(self.entry.title.text, 'Salsa group') self.assertEquals(len(self.entry.extended_property), 1) self.assertEquals(self.entry.extended_property[0].name, 'more info about the group') self.assertEquals( self.entry.extended_property[0].GetXmlBlobExtensionElement().namespace, atom.ATOM_NAMESPACE) self.assertEquals( self.entry.extended_property[0].GetXmlBlobExtensionElement().tag, 'info') self.assertEquals( self.entry.extended_property[0].GetXmlBlobExtensionElement().text, 'Very nice people.') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2008, 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'e.bidelman@google.com (Eric Bidelman)' import os import unittest import atom.data import gdata.client import gdata.data import gdata.gauth import gdata.docs.client import gdata.docs.data import gdata.test_config as conf TEST_FILE_LOCATION_OPTION = conf.Option( 'file', 'Please enter the full path to a test file to upload', description=('This test file will be uploaded to DocList which. An example ' 'file can be found in tests/gdata_tests/docs/test.doc')) CONTENT_TYPE_OPTION = conf.Option( 'contenttype', 'Please enter the mimetype of the file', description='The content type should match that of the upload file.') conf.options.register_option(TEST_FILE_LOCATION_OPTION) conf.options.register_option(CONTENT_TYPE_OPTION) class ResumableUploadTestCase(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.docs.client.DocsClient(source='ResumableUploadTest') if conf.options.get_value('ssl') == 'true': self.client.ssl = True self.f = open(conf.options.get_value('file')) self.content_type = conf.options.get_value('contenttype') conf.configure_client( self.client, 'ResumableUploadTest', self.client.auth_service) def tearDown(self): conf.close_client(self.client) self.f.close() def testUploadEntireDocumentAndUpdate(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUploadDocument') uploader = gdata.client.ResumableUploader( self.client, self.f, self.content_type, os.path.getsize(self.f.name), chunk_size=20000, # 20000 bytes. desired_class=gdata.docs.data.DocsEntry) e = gdata.docs.data.DocsEntry( title=atom.data.Title(text='MyResumableTitleEntireFile')) e.category.append(gdata.docs.data.make_kind_category('document')) e.writers_can_invite = gdata.docs.data.WritersCanInvite(value='false') entry = uploader.UploadFile( '/feeds/upload/create-session/default/private/full', entry=e) # Verify upload has really completed. self.assertEqual(uploader.QueryUploadStatus(), True) self.assert_(isinstance(entry, gdata.docs.data.DocsEntry)) self.assertEqual(entry.title.text, 'MyResumableTitleEntireFile') self.assertEqual(entry.GetDocumentType(), 'document') self.assertEqual(entry.writers_can_invite.value, 'false') self.assertEqual(int(entry.quota_bytes_used.text), 0) self.client.Delete(entry, force=True) def testUploadDocumentInChunks(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'testUploadDocumentInChunks') uploader = gdata.client.ResumableUploader( self.client, self.f, self.content_type, os.path.getsize(self.f.name), desired_class=gdata.docs.data.DocsEntry) uploader._InitSession( '/feeds/upload/create-session/default/private/full', headers={'Slug': 'MyManualChunksNoAtomTitle'}) start_byte = 0 entry = None while not entry: entry = uploader.UploadChunk( start_byte, uploader.file_handle.read(uploader.chunk_size)) start_byte += uploader.chunk_size # Verify upload has really completed. self.assertEqual(uploader.QueryUploadStatus(), True) self.assert_(isinstance(entry, gdata.docs.data.DocsEntry)) self.assertEqual(entry.title.text, 'MyManualChunksNoAtomTitle') self.assertEqual(entry.GetDocumentType(), 'document') self.client.Delete(entry, force=True) def suite(): return conf.build_suite([ResumableUploadTestCase]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.test_config as conf import gdata.analytics.client import gdata.apps.emailsettings.client import gdata.blogger.client import gdata.spreadsheets.client import gdata.calendar_resource.client import gdata.contacts.client import gdata.docs.client import gdata.maps.client import gdata.projecthosting.client import gdata.sites.client class ClientSmokeTest(unittest.TestCase): def test_check_auth_client_classes(self): conf.check_clients_with_auth(self, ( gdata.analytics.client.AnalyticsClient, gdata.apps.emailsettings.client.EmailSettingsClient, gdata.blogger.client.BloggerClient, gdata.spreadsheets.client.SpreadsheetsClient, gdata.calendar_resource.client.CalendarResourceClient, gdata.contacts.client.ContactsClient, gdata.docs.client.DocsClient, gdata.maps.client.MapsClient, gdata.projecthosting.client.ProjectHostingClient, gdata.sites.client.SitesClient )) def suite(): return conf.build_suite([ClientSmokeTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'samuel.cyprian@gmail.com (Samuel Cyprian)' import unittest from gdata import oauth, test_config HTTP_METHOD_POST = 'POST' VERSION = '1.0' class OauthUtilsTest(unittest.TestCase): def test_build_authenticate_header(self): self.assertEqual(oauth.build_authenticate_header(), {'WWW-Authenticate' :'OAuth realm=""'}) self.assertEqual(oauth.build_authenticate_header('foo'), {'WWW-Authenticate': 'OAuth realm="foo"'}) def test_escape(self): #Special cases self.assertEqual(oauth.escape('~'), '~') self.assertEqual(oauth.escape('/'), '%2F') self.assertEqual(oauth.escape('+'), '%2B') self.assertEqual(oauth.escape(' '), '%20') self.assertEqual(oauth.escape('Peter Strömberg'), 'Peter%20Str%C3%B6mberg') def test_generate_timestamp(self): self.assertTrue(oauth.generate_timestamp()>0) self.assertTrue(type(oauth.generate_timestamp()) is type(0)) def test_generate_nonce(self): DEFAULT_NONCE_LENGTH = 8 self.assertTrue(len(oauth.generate_nonce()) is DEFAULT_NONCE_LENGTH) self.assertTrue(type(oauth.generate_nonce()) is type('')) class OAuthConsumerTest(unittest.TestCase): def setUp(self): self.key = 'key' self.secret = 'secret' self.consumer = oauth.OAuthConsumer(self.key, self.secret) def test_OAuthConsumer_attr_key(self): self.assertEqual(self.consumer.key, self.key) def test_OAuthConsumer_attr_secret(self): self.assertEqual(self.consumer.secret, self.secret) class OAuthTokenTest(unittest.TestCase): def setUp(self): self.key = 'key' self.secret = 'secret' self.token = oauth.OAuthToken(self.key, self.secret) def test_OAuthToken_attr_key(self): self.assertEqual(self.token.key, self.key) def test_OAuthToken_attr_secret(self): self.assertEqual(self.token.secret, self.secret) def test_to_string(self): self.assertEqual(self.token.to_string(), 'oauth_token_secret=secret&oauth_token=key') t = oauth.OAuthToken('+', '%') self.assertEqual(t.to_string(), 'oauth_token_secret=%25&oauth_token=%2B') def test_from_string(self): s = 'oauth_token_secret=secret&oauth_token=key' t = oauth.OAuthToken.from_string(s) self.assertEqual(t.key, 'key') self.assertEqual(t.secret, 'secret') t = oauth.OAuthToken.from_string('oauth_token_secret=%25&oauth_token=%2B') self.assertEqual(t.key, '+') self.assertEqual(t.secret, '%') def test___str__(self): self.assertEqual(str(self.token), 'oauth_token_secret=secret&oauth_token=key') t = oauth.OAuthToken('+', '%') self.assertEqual(str(t), 'oauth_token_secret=%25&oauth_token=%2B') class OAuthParameters(object): CONSUMER_KEY = 'oauth_consumer_key' TOKEN = 'oauth_token' SIGNATURE_METHOD = 'oauth_signature_method' SIGNATURE = 'oauth_signature' TIMESTAMP = 'oauth_timestamp' NONCE = 'oauth_nonce' VERSION = 'oauth_version' CALLBACK = 'oauth_callback' ALL_PARAMETERS = (CONSUMER_KEY, TOKEN, SIGNATURE_METHOD, SIGNATURE, TIMESTAMP, NONCE, VERSION) class OAuthTest(unittest.TestCase): def setUp(self): self.consumer = oauth.OAuthConsumer('a56b5ff0a637ab283d1d8e32ced37a9c', '9a3248210c84b264b56b98c0b872bc8a') self.token = oauth.OAuthToken('5b2cafbf20b11bace53b29e37d8a673d', '3f71254637df2002d8819458ae4f6c51') self.http_url = 'http://dev.alicehub.com/server/api/newsfeed/update/' self.http_method = HTTP_METHOD_POST class OAuthRequestTest(OAuthTest): def setUp(self): super(OAuthRequestTest, self).setUp() self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.non_oauth_param_message = 'message' self.non_oauth_param_context_id = 'context_id' self.parameters = {OAuthParameters.CONSUMER_KEY:self.consumer.key, OAuthParameters.TOKEN: self.token.key, OAuthParameters.SIGNATURE_METHOD: 'HMAC-SHA1', OAuthParameters.SIGNATURE: '947ysBZiMn6FGZ11AW06Ioco4mo=', OAuthParameters.TIMESTAMP: '1278573584', OAuthParameters.NONCE: '1770704051', OAuthParameters.VERSION: VERSION, self.non_oauth_param_message:'hey', self.non_oauth_param_context_id:'',} oauth_params_string = """ oauth_nonce="1770704051", oauth_timestamp="1278573584", oauth_consumer_key="a56b5ff0a637ab283d1d8e32ced37a9c", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="5b2cafbf20b11bace53b29e37d8a673d", oauth_signature="947ysBZiMn6FGZ11AW06Ioco4mo%3D" """ self.oauth_header_with_realm = {'Authorization': """OAuth realm="http://example.com", %s """ % oauth_params_string} self.oauth_header_without_realm = {'Authorization': 'OAuth %s' % oauth_params_string} self.additional_param = 'foo' self.additional_value = 'bar' self.oauth_request = oauth.OAuthRequest(self.http_method, self.http_url, self.parameters) def test_set_parameter(self): self.oauth_request.set_parameter(self.additional_param, self.additional_value) self.assertEqual(self.oauth_request.get_parameter(self.additional_param), self.additional_value) def test_get_parameter(self): self.assertRaises(oauth.OAuthError, self.oauth_request.get_parameter, self.additional_param) self.oauth_request.set_parameter(self.additional_param, self.additional_value) self.assertEqual(self.oauth_request.get_parameter(self.additional_param), self.additional_value) def test__get_timestamp_nonce(self): self.assertEqual(self.oauth_request._get_timestamp_nonce(), (self.parameters[OAuthParameters.TIMESTAMP], self.parameters[OAuthParameters.NONCE])) def test_get_nonoauth_parameters(self): non_oauth_params = self.oauth_request.get_nonoauth_parameters() self.assertTrue(non_oauth_params.has_key(self.non_oauth_param_message)) self.assertFalse(non_oauth_params.has_key(OAuthParameters.CONSUMER_KEY)) def test_to_header(self): realm = 'google' header_without_realm = self.oauth_request.to_header()\ .get('Authorization') header_with_realm = self.oauth_request.to_header(realm)\ .get('Authorization') self.assertTrue(header_with_realm.find(realm)) for k in OAuthParameters.ALL_PARAMETERS: self.assertTrue(header_without_realm.find(k) > -1) self.assertTrue(header_with_realm.find(k) > -1) def check_for_params_in_string(self, params, s): for k, v in params.iteritems(): self.assertTrue(s.find(oauth.escape(k)) > -1) self.assertTrue(s.find(oauth.escape(v)) > -1) def test_to_postdata(self): post_data = self.oauth_request.to_postdata() self.check_for_params_in_string(self.parameters, post_data) def test_to_url(self): GET_url = self.oauth_request.to_url() self.assertTrue(GET_url\ .find(self.oauth_request.get_normalized_http_url()) > -1) self.assertTrue(GET_url.find('?') > -1) self.check_for_params_in_string(self.parameters, GET_url) def test_get_normalized_parameters(self): _params = self.parameters.copy() normalized_params = self.oauth_request.get_normalized_parameters() self.assertFalse(normalized_params\ .find(OAuthParameters.SIGNATURE + '=') > -1) self.assertTrue(self.parameters.get(OAuthParameters.SIGNATURE) is None) key_values = [tuple(kv.split('=')) for kv in normalized_params.split('&')] del _params[OAuthParameters.SIGNATURE] expected_key_values = _params.items() expected_key_values.sort() for k, v in expected_key_values: self.assertTrue(expected_key_values.index((k,v))\ is key_values.index((oauth.escape(k), oauth.escape(v)))) def test_get_normalized_http_method(self): lower_case_http_method = HTTP_METHOD_POST.lower() self.oauth_request.http_method = lower_case_http_method self.assertEqual(self.oauth_request.get_normalized_http_method(), lower_case_http_method.upper()) def test_get_normalized_http_url(self): url1 = 'HTTP://Example.com:80/resource?id=123' expected_url1 = "http://example.com/resource" self.oauth_request.http_url = url1 self.assertEqual(self.oauth_request.get_normalized_http_url(), expected_url1) url2 = 'HTTPS://Example.com:443/resource?id=123' expected_url2 = "https://example.com/resource" self.oauth_request.http_url = url2 self.assertEqual(self.oauth_request.get_normalized_http_url(), expected_url2) url3 = 'HTTP://Example.com:8080/resource?id=123' expected_url3 = "http://example.com:8080/resource" self.oauth_request.http_url = url3 self.assertEqual(self.oauth_request.get_normalized_http_url(), expected_url3) def test_sign_request(self): expected_signature = self.oauth_request.parameters\ .get(OAuthParameters.SIGNATURE) del self.oauth_request.parameters[OAuthParameters.SIGNATURE] self.oauth_request.sign_request(self.signature_method, self.consumer, self.token) self.assertEqual(self.oauth_request.parameters\ .get(OAuthParameters.SIGNATURE), expected_signature) def test_build_signature(self): expected_signature = self.oauth_request.parameters\ .get(OAuthParameters.SIGNATURE) self.assertEqual(self.oauth_request.build_signature(self.signature_method, self.consumer, self.token), expected_signature) def test_from_request(self): request = oauth.OAuthRequest.from_request(self.http_method, self.http_url, self.oauth_header_with_realm, {}, "message=hey&context_id=") self.assertEqual(request.__dict__, self.oauth_request.__dict__) self.assertTrue(isinstance(request, oauth.OAuthRequest)) def test_from_consumer_and_token(self): request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token, self.http_method, self.http_url) self.assertTrue(isinstance(request, oauth.OAuthRequest)) def test_from_token_and_callback(self): callback = 'http://example.com' request = oauth.OAuthRequest.from_token_and_callback(self.token, callback, self.http_method, self.http_url) self.assertTrue(isinstance(request, oauth.OAuthRequest)) self.assertEqual(request.get_parameter(OAuthParameters.CALLBACK), callback) def test__split_header(self): del self.parameters[self.non_oauth_param_message] del self.parameters[self.non_oauth_param_context_id] self.assertEqual(oauth.OAuthRequest._split_header(self\ .oauth_header_with_realm['Authorization']), self.parameters) self.assertEqual(oauth.OAuthRequest._split_header(self\ .oauth_header_without_realm['Authorization']), self.parameters) def test_split_url_string(self): qs = "a=1&c=hi%20there&empty=" expected_result = {'a': '1', 'c': 'hi there', 'empty': ''} self.assertEqual(oauth.OAuthRequest._split_url_string(qs), expected_result) class OAuthServerTest(OAuthTest): def setUp(self): super(OAuthServerTest, self).setUp() self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.data_store = MockOAuthDataStore() self.user = MockUser('Foo Bar') self.request_token_url = "http://example.com/oauth/request_token" self.access_token_url = "http://example.com/oauth/access_token" self.oauth_server = oauth.OAuthServer(self.data_store, {self.signature_method.get_name():self.signature_method}) def _prepare_request(self, request, token = None): request.set_parameter(OAuthParameters.SIGNATURE_METHOD, self.signature_method.get_name()) request.set_parameter(OAuthParameters.NONCE, oauth.generate_nonce()) request.set_parameter(OAuthParameters.TIMESTAMP, oauth.generate_timestamp()) request.sign_request(self.signature_method, self.consumer, token) def _get_token(self, request): self._prepare_request(request) return self.oauth_server.fetch_request_token(request) def _get_authorized_token(self, request): req_token = self._get_token(request) return self.oauth_server.authorize_token(req_token, self.user) def test_set_data_store(self): self.oauth_server.data_store = None self.assertTrue(self.oauth_server.data_store is None) self.oauth_server.set_data_store(self.data_store) self.assertTrue(self.oauth_server.data_store is not None) self.assertTrue(isinstance(self.oauth_server.data_store, oauth.OAuthDataStore)) def test_get_data_store(self): self.assertEqual(self.oauth_server.data_store, self.data_store) def test_add_signature_method(self): signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() self.oauth_server.add_signature_method(signature_method) self.assertTrue(isinstance(self.oauth_server.signature_methods\ .get(signature_method.get_name()), oauth.OAuthSignatureMethod_PLAINTEXT)) def test_fetch_request_token(self): initial_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, http_method=self.http_method, http_url=self.request_token_url ) req_token_1 = self._get_token(initial_request) authorization_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, req_token_1, http_method=self.http_method, http_url=self.http_url ) req_token_2 = self._get_token(authorization_request) self.assertEqual(req_token_1.key, req_token_2.key) self.assertEqual(req_token_1.secret, req_token_2.secret) def _get_token_for_authorization(self): request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, http_method=self.http_method, http_url=self.request_token_url ) request_token = self._get_token(request) authorization_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, request_token, http_method=self.http_method, http_url=self.http_url ) return self._get_authorized_token(authorization_request) def test_authorize_token(self): authorized_token = self._get_token_for_authorization() self.assertTrue(authorized_token is not None) def _get_access_token_request(self, authorized_token): access_token_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, authorized_token, http_method=self.http_method, http_url=self.access_token_url ) self._prepare_request(access_token_request, authorized_token) return access_token_request def test_fetch_access_token(self): authorized_token = self._get_token_for_authorization() access_token_request = self._get_access_token_request(authorized_token) access_token = self.oauth_server.fetch_access_token(access_token_request) self.assertTrue(access_token is not None) self.assertNotEqual(str(authorized_token), str(access_token)) # Try to fetch access_token with used request token self.assertRaises(oauth.OAuthError, self.oauth_server.fetch_access_token, access_token_request) def test_verify_request(self): authorized_token = self._get_token_for_authorization() access_token_request = self._get_access_token_request(authorized_token) access_token = self.oauth_server.fetch_access_token(access_token_request) param1 = 'p1' value1 = 'v1' api_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, access_token, http_method=self.http_method, http_url=self.http_url, parameters={param1:value1} ) self._prepare_request(api_request, access_token) result = self.oauth_server.verify_request(api_request) self.assertTrue(result is not None) consumer, token, parameters = result self.assertEqual(parameters.get(param1), value1) def test_get_callback(self): request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, None, http_method=self.http_method, http_url=self.http_url ) self._prepare_request(request) cb_url = 'http://example.com/cb' request.set_parameter(OAuthParameters.CALLBACK, cb_url) self.assertEqual(self.oauth_server.get_callback(request), cb_url) def test_build_authenticate_header(self): self.assertEqual(oauth.build_authenticate_header(), {'WWW-Authenticate': 'OAuth realm=""'}) self.assertEqual(oauth.build_authenticate_header('foo'), {'WWW-Authenticate': 'OAuth realm="foo"'}) class OAuthClientTest(OAuthTest): def setUp(self): super(OAuthClientTest, self).setUp() self.oauth_client = oauth.OAuthClient(self.consumer, self.token) def test_get_consumer(self): consumer = self.oauth_client.get_consumer() self.assertTrue(isinstance(consumer, oauth.OAuthConsumer)) self.assertEqual(consumer.__dict__, self.consumer.__dict__) def test_get_token(self): token = self.oauth_client.get_token() self.assertTrue(isinstance(token, oauth.OAuthToken)) self.assertEqual(token.__dict__, self.token.__dict__) #Mockup OAuthDataStore TOKEN_TYPE_REQUEST = 'request' TOKEN_TYPE_ACCESS = 'access' class MockOAuthDataStore(oauth.OAuthDataStore): def __init__(self): self.consumer = oauth.OAuthConsumer('a56b5ff0a637ab283d1d8e32ced37a9c', '9a3248210c84b264b56b98c0b872bc8a') self.consumer_db = {self.consumer.key: self.consumer} self.request_token_db = {} self.access_token_db = {} self.nonce = None def lookup_consumer(self, key): return self.consumer_db.get(key) def lookup_token(self, oauth_consumer, token_type, token_field): data = None if token_type == TOKEN_TYPE_REQUEST: data = self.request_token_db.get(token_field) elif token_type == TOKEN_TYPE_ACCESS: data = self.access_token_db.get(token_field) if data: token, consumer, authenticated_user = data if consumer.key == oauth_consumer.key: return token return None def lookup_nonce(self, oauth_consumer, oauth_token, nonce): is_used = self.nonce == nonce self.nonce = nonce return is_used def fetch_request_token(self, oauth_consumer): token = oauth.OAuthToken("5b2cafbf20b11bace53b29e37d8a673dRT", "3f71254637df2002d8819458ae4f6c51RT") self.request_token_db[token.key] = (token, oauth_consumer, None) return token def fetch_access_token(self, oauth_consumer, oauth_token): data = self.request_token_db.get(oauth_token.key) if data: del self.request_token_db[oauth_token.key] request_token, consumer, authenticated_user = data access_token = oauth.OAuthToken("5b2cafbf20b11bace53b29e37d8a673dAT", "3f71254637df2002d8819458ae4f6c51AT") self.access_token_db[access_token.key] = (access_token, consumer, authenticated_user) return access_token else: return None def authorize_request_token(self, oauth_token, user): data = self.request_token_db.get(oauth_token.key) if data and data[2] == None: request_token, consumer, authenticated_user = data authenticated_user = user self.request_token_db[request_token.key] = (request_token, consumer, authenticated_user) return request_token else: return None #Mock user class MockUser(object): def __init__(self, name): self.name = name def suite(): return test_config.build_suite([OauthUtilsTest, OAuthConsumerTest, OAuthTokenTest, OAuthRequestTest, OAuthServerTest, OAuthClientTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import sys import gdata.sample_util class SettingsUtilTest(unittest.TestCase): def setUp(self): self.settings = gdata.sample_util.SettingsUtil() def test_get_param(self): self.assert_(self.settings.get_param('missing', ask=False) is None) self.settings.prefs['x'] = 'something' self.assertEqual(self.settings.get_param('x'), 'something') def test_get_param_from_command_line_arg(self): self.assert_('x' not in self.settings.prefs) self.assert_(self.settings.get_param('x', ask=False) is None) sys.argv.append('--x=something') self.assertEqual(self.settings.get_param('x'), 'something') self.assert_('x' not in self.settings.prefs) self.assert_('y' not in self.settings.prefs) self.assert_(self.settings.get_param('y', ask=False) is None) sys.argv.append('--y') sys.argv.append('other') self.assertEqual(self.settings.get_param('y', reuse=True), 'other') self.assertEqual(self.settings.prefs['y'], 'other') def suite(): return conf.build_suite([SettingsUtilTest]) if __name__ == '__main__': unittest.main()
Python
''' Created on 21.05.2010 ''' __author__ = 'seriyPS (Sergey Prokhorov)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.base.service import gdata.service import atom.service import gdata.base import atom TST_XML="""<?xml version="1.0" encoding="UTF-8"?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gm='http://base.google.com/ns-metadata/1.0' xmlns:g='http://base.google.com/ns/1.0' xmlns:batch='http://schemas.google.com/gdata/batch'> <id>http://www.google.com/base/feeds/snippets/3804629571624093811</id> <published>2010-03-28T06:55:40.000Z</published> <updated>2010-05-23T06:46:27.000Z</updated> <category scheme='http://base.google.com/categories/itemtypes' term='Products'/> <title type='text'>Cables to Go Ultimate iPod Companion Kit</title> <content type='html'>Ramp up your portable music experience and enjoyment with the Cables to Go Ultimate iPod Companion Kit. This bundle includes all the connections and accessories necessary to enjoy your iPod-compatible device on your TV or home stereo. Cables to Go ...</content> <link rel='alternate' type='text/html' href='http://www.hsn.com/redirect.aspx?pfid=1072528&amp;sz=6&amp;sf=EC0210&amp;ac=GPT&amp;cm_mmc=Shopping%20Engine-_-Froogle-_-Electronics-_-5948880&amp;CAWELAID=491871036'/> <link rel='self' type='application/atom+xml' href='http://www.google.com/base/feeds/snippets/3804629571624093811'/> <author> <name>HSN</name> </author> <g:condition type='text'>new</g:condition> <g:product_type type='text'>Electronics&gt;MP3 Players&gt;iPod Accessories</g:product_type> <g:image_link type='url'>http://dyn-images.hsn.com/is/image/HomeShoppingNetwork/5948880w?$pd500$</g:image_link> <g:upc type='text'>757120355120</g:upc> <g:item_language type='text'>EN</g:item_language> <g:id type='text'>5948880</g:id> <g:shipping type='shipping'><g:price type='floatUnit'>7.95 usd</g:price> <g:country type="text">US</g:country> </g:shipping> <g:price type='floatUnit'>64.95 usd</g:price> <g:target_country type='text'>US</g:target_country> <g:expiration_date type='dateTime'>2010-06-21T00:00:00Z</g:expiration_date> <g:brand type='text'>Cables to Go</g:brand> <g:customer_id type='int'>8717</g:customer_id> <g:item_type type='text'>Products</g:item_type> </entry> """ class Test(unittest.TestCase): def testConstruct(self): thumb_url='http://base.googlehosted.com/base_media?q=http%3A%2F%2Fexample.com%2FEOS%2F1AEOS01008.jpg' item = gdata.base.GBaseItem() item.title = atom.Title(text='Olds Cutlass Supreme Oxygen O2 Sensor') item.link.append(atom.Link(rel='alternate', link_type='text/html', href='http://www.example.com/123456jsh9')) item.item_type = gdata.base.ItemType(text='Products') item.AddItemAttribute(name='price', value_type='floatUnit', value='41.94 usd') item.AddItemAttribute(name='id', value_type='text', value='1AEOS01008-415676-XXX') item.AddItemAttribute(name='quantity', value_type='int', value='5') attr=item.AddItemAttribute(name='image_link', value_type='url', value=None) attr.AddItemAttribute(name='thumb', value=thumb_url, value_type='url') image_attr=item.GetItemAttributes("image_link")[0] self.assert_(isinstance(image_attr, gdata.base.ItemAttributeContainer)) self.assert_(isinstance(image_attr.item_attributes[0], gdata.base.ItemAttributeContainer)) self.assert_(isinstance(image_attr.item_attributes[0], gdata.base.ItemAttribute)) self.assert_(image_attr.item_attributes[0].type=='url') self.assert_(image_attr.item_attributes[0].text==thumb_url) self.assert_(len(image_attr.item_attributes)==1) new_item = gdata.base.GBaseItemFromString(item.ToString()) image_attr=item.GetItemAttributes("image_link")[0] self.assert_(isinstance(image_attr.item_attributes[0], gdata.base.ItemAttributeContainer)) self.assert_(image_attr.item_attributes[0].type=='url') self.assert_(image_attr.item_attributes[0].text==thumb_url) self.assert_(len(image_attr.item_attributes)==1) def testFromXML(self): item = gdata.base.GBaseItemFromString(TST_XML) attr=item.GetItemAttributes("shipping")[0] self.assert_(isinstance(attr, gdata.base.ItemAttributeContainer)) self.assert_(isinstance(attr.item_attributes[0], gdata.base.ItemAttributeContainer)) self.assert_(isinstance(attr.item_attributes[0], gdata.base.ItemAttribute)) self.assert_(attr.item_attributes[0].type=='floatUnit') self.assert_(len(attr.item_attributes)==2) if __name__ == "__main__": unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import unittest import getpass try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.base.service import gdata.service import atom.service import gdata.base import atom from gdata import test_data username = '' password = '' class GBaseServiceUnitTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.base.service.GBaseService() self.gd_client.email = username self.gd_client.password = password self.gd_client.source = 'BaseClient "Unit" Tests' self.gd_client.api_key = 'ABQIAAAAoLioN3buSs9KqIIq9VmkFxT2yXp_ZAY8_ufC' +\ '3CFXhHIE1NvwkxRK8C1Q8OWhsWA2AIKv-cVKlVrNhQ' def tearDown(self): # No teardown needed pass def testProperties(self): email_string = 'Test Email' password_string = 'Passwd' api_key_string = 'my API key' self.gd_client.email = email_string self.assertEquals(self.gd_client.email, email_string) self.gd_client.password = password_string self.assertEquals(self.gd_client.password, password_string) self.gd_client.api_key = api_key_string self.assertEquals(self.gd_client.api_key, api_key_string) self.gd_client.api_key = None self.assert_(self.gd_client.api_key is None) def testQuery(self): my_query = gdata.base.service.BaseQuery(feed='/base/feeds/snippets') my_query['max-results'] = '25' my_query.bq = 'digital camera [item type: products]' result = self.gd_client.Query(my_query.ToUri()) self.assert_(isinstance(result, atom.Feed)) service = gdata.base.service.GBaseService(username, password) query = gdata.base.service.BaseQuery() query.feed = '/base/feeds/snippets' query.bq = 'digital camera' feed = service.Query(query.ToUri()) def testQueryWithConverter(self): my_query = gdata.base.service.BaseQuery(feed='/base/feeds/snippets') my_query['max-results'] = '1' my_query.bq = 'digital camera [item type: products]' result = self.gd_client.Query(my_query.ToUri(), converter=gdata.base.GBaseSnippetFeedFromString) self.assert_(isinstance(result, gdata.base.GBaseSnippetFeed)) def testCorrectReturnTypes(self): q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/snippets' q.bq = 'digital camera' result = self.gd_client.QuerySnippetsFeed(q.ToUri()) self.assert_(isinstance(result, gdata.base.GBaseSnippetFeed)) q.feed = '/base/feeds/attributes' result = self.gd_client.QueryAttributesFeed(q.ToUri()) self.assert_(isinstance(result, gdata.base.GBaseAttributesFeed)) q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/itemtypes/en_US' result = self.gd_client.QueryItemTypesFeed(q.ToUri()) self.assert_(isinstance(result, gdata.base.GBaseItemTypesFeed)) q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/locales' result = self.gd_client.QueryLocalesFeed(q.ToUri()) self.assert_(isinstance(result, gdata.base.GBaseLocalesFeed)) def testInsertItemUpdateItemAndDeleteItem(self): try: self.gd_client.ProgrammaticLogin() self.assert_(self.gd_client.GetClientLoginToken() is not None) self.assert_(self.gd_client.captcha_token is None) self.assert_(self.gd_client.captcha_url is None) except gdata.service.CaptchaRequired: self.fail('Required Captcha') proposed_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) result = self.gd_client.InsertItem(proposed_item) item_id = result.id.text self.assertEquals(result.id.text != None, True) updated_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) updated_item.label[0].text = 'Test Item' result = self.gd_client.UpdateItem(item_id, updated_item) # Try to update an incorrect item_id. try: result = self.gd_client.UpdateItem(item_id + '2', updated_item) self.fail() except gdata.service.RequestError: pass result = self.gd_client.DeleteItem(item_id) self.assert_(result) # Delete and already deleted item. try: result = self.gd_client.DeleteItem(item_id) self.fail() except gdata.service.RequestError: pass def testInsertItemUpdateItemAndDeleteItemWithConverter(self): try: self.gd_client.ProgrammaticLogin() self.assert_(self.gd_client.GetClientLoginToken() is not None) self.assert_(self.gd_client.captcha_token is None) self.assert_(self.gd_client.captcha_url is None) except gdata.service.CaptchaRequired: self.fail('Required Captcha') proposed_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) result = self.gd_client.InsertItem(proposed_item, converter=atom.EntryFromString) self.assertEquals(isinstance(result, atom.Entry), True) self.assertEquals(isinstance(result, gdata.base.GBaseItem), False) item_id = result.id.text self.assertEquals(result.id.text != None, True) updated_item = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) updated_item.label[0].text = 'Test Item' result = self.gd_client.UpdateItem(item_id, updated_item, converter=atom.EntryFromString) self.assertEquals(isinstance(result, atom.Entry), True) self.assertEquals(isinstance(result, gdata.base.GBaseItem), False) result = self.gd_client.DeleteItem(item_id) self.assertEquals(result, True) def testMakeBatchRequests(self): try: self.gd_client.ProgrammaticLogin() self.assert_(self.gd_client.GetClientLoginToken() is not None) self.assert_(self.gd_client.captcha_token is None) self.assert_(self.gd_client.captcha_url is None) except gdata.service.CaptchaRequired: self.fail('Required Captcha') request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id( text='test batch')) entry1 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) entry1.title.text = 'first batch request item' entry2 = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) entry2.title.text = 'second batch request item' request_feed.AddInsert(entry1) request_feed.AddInsert(entry2) result_feed = self.gd_client.ExecuteBatch(request_feed) self.assertEquals(result_feed.entry[0].batch_status.code, '201') self.assertEquals(result_feed.entry[0].batch_status.reason, 'Created') self.assertEquals(result_feed.entry[0].title.text, 'first batch request item') self.assertEquals(result_feed.entry[0].item_type.text, 'products') self.assertEquals(result_feed.entry[1].batch_status.code, '201') self.assertEquals(result_feed.entry[1].batch_status.reason, 'Created') self.assertEquals(result_feed.entry[1].title.text, 'second batch request item') # Now delete the newly created items. request_feed = gdata.base.GBaseItemFeed(atom_id=atom.Id( text='test deletions')) request_feed.AddDelete(entry=result_feed.entry[0]) request_feed.AddDelete(entry=result_feed.entry[1]) self.assertEquals(request_feed.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEquals(request_feed.entry[1].batch_operation.type, gdata.BATCH_DELETE) result_feed = self.gd_client.ExecuteBatch(request_feed) self.assertEquals(result_feed.entry[0].batch_status.code, '200') self.assertEquals(result_feed.entry[0].batch_status.reason, 'Success') self.assertEquals(result_feed.entry[0].title.text, 'first batch request item') self.assertEquals(result_feed.entry[1].batch_status.code, '200') self.assertEquals(result_feed.entry[1].batch_status.reason, 'Success') self.assertEquals(result_feed.entry[1].title.text, 'second batch request item') if __name__ == '__main__': print ('Google Base Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.eric@google.com (Eric Bidelman)' import unittest from gdata import test_data import gdata.health import gdata.health.service class ProfileEntryTest(unittest.TestCase): def setUp(self): self.profile_entry = gdata.health.ProfileEntryFromString( test_data.HEALTH_PROFILE_ENTRY_DIGEST) def testToAndFromStringWithData(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) self.assert_(isinstance(entry, gdata.health.ProfileEntry)) self.assert_(isinstance(entry.ccr, gdata.health.Ccr)) self.assertEqual(len(entry.ccr.GetMedications()), 3) self.assertEqual(len(entry.ccr.GetImmunizations()), 1) self.assertEqual(len(entry.ccr.GetAlerts()), 2) self.assertEqual(len(entry.ccr.GetResults()), 1) self.assertEqual(len(entry.ccr.GetProblems()), 2) self.assertEqual(len(entry.ccr.GetProcedures()), 2) def testGetResultsTextFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) result = entry.ccr.GetResults()[0].FindChildren('Test')[0] test_desc = result.FindChildren('Description')[0].FindChildren('Text')[0] self.assertEqual(test_desc.text, 'Acetaldehyde - Blood') def testGetMedicationNameFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) product = entry.ccr.GetMedications()[1].FindChildren('Product')[0] prod_name = product.FindChildren('ProductName')[0].FindChildren('Text')[0] self.assertEqual(prod_name.text, 'A-Fil') def testGetProblemCodeValueFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) problem_desc = entry.ccr.GetProblems()[1].FindChildren('Description')[0] code = problem_desc.FindChildren('Code')[0].FindChildren('Value')[0] self.assertEqual(code.text, '136.9') def testGetGetImmunizationActorIdFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) immun_source = entry.ccr.GetImmunizations()[0].FindChildren('Source')[0] actor_id = immun_source.FindChildren('Actor')[0].FindChildren('ActorID')[0] self.assertEqual(actor_id.text, 'user@gmail.com') def testGetGetProceduresNameFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) proc_desc = entry.ccr.GetProcedures()[1].FindChildren('Description')[0] proc_name = proc_desc.FindChildren('Text')[0] self.assertEqual(proc_name.text, 'Abdominoplasty') def testGetAlertsFromCcr(self): entry = gdata.health.ProfileEntryFromString(str(self.profile_entry)) alert_type = entry.ccr.GetAlerts()[0].FindChildren('Type')[0] self.assertEqual(alert_type.FindChildren('Text')[0].text, 'Allergy') class ProfileListEntryTest(unittest.TestCase): def setUp(self): self.entry = gdata.health.ProfileListEntryFromString( test_data.HEALTH_PROFILE_LIST_ENTRY) def testToAndFromString(self): self.assert_(isinstance(self.entry, gdata.health.ProfileListEntry)) self.assertEqual(self.entry.GetProfileId(), 'vndCn5sdfwdEIY') self.assertEqual(self.entry.GetProfileName(), 'profile name') class ProfileFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.health.ProfileFeedFromString( test_data.HEALTH_PROFILE_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 15) for an_entry in self.feed.entry: self.assert_(isinstance(an_entry, gdata.health.ProfileEntry)) new_profile_feed = gdata.health.ProfileFeedFromString(str(self.feed)) for an_entry in new_profile_feed.entry: self.assert_(isinstance(an_entry, gdata.health.ProfileEntry)) def testConvertActualData(self): for an_entry in self.feed.entry: self.assert_(an_entry.ccr is not None) class HealthProfileQueryTest(unittest.TestCase): def testHealthQueryToString(self): query = gdata.health.service.HealthProfileQuery() self.assertEqual(query.ToUri(), '/health/feeds/profile/default') query = gdata.health.service.HealthProfileQuery(feed='feeds/profile') self.assertEqual(query.ToUri(), '/health/feeds/profile/default') query = gdata.health.service.HealthProfileQuery(categories=['medication']) self.assertEqual(query.ToUri(), '/health/feeds/profile/default/-/medication') query = gdata.health.service.HealthProfileQuery(projection='ui', profile_id='12345') self.assertEqual(query.ToUri(), '/health/feeds/profile/ui/12345') query = gdata.health.service.HealthProfileQuery() query.categories.append('medication|condition') self.assertEqual(query.ToUri(), '/health/feeds/profile/default/-/medication%7Ccondition') def testH9QueryToString(self): query = gdata.health.service.HealthProfileQuery(service='h9') self.assertEqual(query.ToUri(), '/h9/feeds/profile/default') query = gdata.health.service.HealthProfileQuery( service='h9', feed='feeds/profile', projection='ui', profile_id='12345') self.assertEqual(query.ToUri(), '/h9/feeds/profile/ui/12345') def testDigestParam(self): query = gdata.health.service.HealthProfileQuery(params={'digest': 'true'}) self.assertEqual(query.ToUri(), '/health/feeds/profile/default?digest=true') query.profile_id = '12345' query.projection = 'ui' self.assertEqual( query.ToUri(), '/health/feeds/profile/ui/12345?digest=true') class HealthProfileListQueryTest(unittest.TestCase): def testHealthProfileListQueryToString(self): query = gdata.health.service.HealthProfileListQuery() self.assertEqual(query.ToUri(), '/health/feeds/profile/list') query = gdata.health.service.HealthProfileListQuery(service='health') self.assertEqual(query.ToUri(), '/health/feeds/profile/list') query = gdata.health.service.HealthProfileListQuery( feed='feeds/profile/list') self.assertEqual(query.ToUri(), '/health/feeds/profile/list') query = gdata.health.service.HealthProfileListQuery( service='health', feed='feeds/profile/list') self.assertEqual(query.ToUri(), '/health/feeds/profile/list') def testH9ProfileListQueryToString(self): query = gdata.health.service.HealthProfileListQuery(service='h9') self.assertEqual(query.ToUri(), '/h9/feeds/profile/list') query = gdata.health.service.HealthProfileListQuery( service='h9', feed='feeds/profile/list') self.assertEqual(query.ToUri(), '/h9/feeds/profile/list') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.test_config as conf import gdata.data import gdata.acl.data import gdata.analytics.data import gdata.dublincore.data import gdata.books.data import gdata.calendar.data import gdata.geo.data import gdata.finance.data import gdata.notebook.data import gdata.media.data import gdata.youtube.data import gdata.webmastertools.data import gdata.contacts.data import gdata.opensearch.data class DataSmokeTest(unittest.TestCase): def test_check_all_data_classes(self): conf.check_data_classes(self, ( gdata.data.TotalResults, gdata.data.StartIndex, gdata.data.ItemsPerPage, gdata.data.ExtendedProperty, gdata.data.GDEntry, gdata.data.GDFeed, gdata.data.BatchId, gdata.data.BatchOperation, gdata.data.BatchStatus, gdata.data.BatchEntry, gdata.data.BatchInterrupted, gdata.data.BatchFeed, gdata.data.EntryLink, gdata.data.FeedLink, gdata.data.AdditionalName, gdata.data.Comments, gdata.data.Country, gdata.data.Email, gdata.data.FamilyName, gdata.data.Im, gdata.data.GivenName, gdata.data.NamePrefix, gdata.data.NameSuffix, gdata.data.FullName, gdata.data.Name, gdata.data.OrgDepartment, gdata.data.OrgName, gdata.data.OrgSymbol, gdata.data.OrgTitle, gdata.data.Organization, gdata.data.When, gdata.data.Who, gdata.data.OriginalEvent, gdata.data.PhoneNumber, gdata.data.PostalAddress, gdata.data.Rating, gdata.data.Recurrence, gdata.data.RecurrenceException, gdata.data.Reminder, gdata.data.Agent, gdata.data.HouseName, gdata.data.Street, gdata.data.PoBox, gdata.data.Neighborhood, gdata.data.City, gdata.data.Subregion, gdata.data.Region, gdata.data.Postcode, gdata.data.Country, gdata.data.FormattedAddress, gdata.data.StructuredPostalAddress, gdata.data.Where, gdata.data.AttendeeType, gdata.data.AttendeeStatus, gdata.data.Deleted, gdata.data.Money, gdata.acl.data.AclRole, gdata.acl.data.AclScope, gdata.acl.data.AclWithKey, gdata.acl.data.AclEntry, gdata.acl.data.AclFeed, gdata.analytics.data.Dimension, gdata.analytics.data.EndDate, gdata.analytics.data.Metric, gdata.analytics.data.Aggregates, gdata.analytics.data.DataEntry, gdata.analytics.data.Property, gdata.analytics.data.StartDate, gdata.analytics.data.TableId, gdata.analytics.data.AccountEntry, gdata.analytics.data.TableName, gdata.analytics.data.DataSource, gdata.analytics.data.AccountFeed, gdata.analytics.data.DataFeed, gdata.dublincore.data.Creator, gdata.dublincore.data.Date, gdata.dublincore.data.Description, gdata.dublincore.data.Format, gdata.dublincore.data.Identifier, gdata.dublincore.data.Language, gdata.dublincore.data.Publisher, gdata.dublincore.data.Rights, gdata.dublincore.data.Subject, gdata.dublincore.data.Title, gdata.books.data.CollectionEntry, gdata.books.data.CollectionFeed, gdata.books.data.Embeddability, gdata.books.data.OpenAccess, gdata.books.data.Review, gdata.books.data.Viewability, gdata.books.data.VolumeEntry, gdata.books.data.VolumeFeed, gdata.calendar.data.AccessLevelProperty, gdata.calendar.data.AllowGSync2Property, gdata.calendar.data.AllowGSyncProperty, gdata.calendar.data.AnyoneCanAddSelfProperty, gdata.calendar.data.CalendarAclRole, gdata.calendar.data.CalendarCommentEntry, gdata.calendar.data.CalendarCommentFeed, gdata.calendar.data.CalendarComments, gdata.calendar.data.CalendarExtendedProperty, gdata.calendar.data.CalendarWhere, gdata.calendar.data.ColorProperty, gdata.calendar.data.GuestsCanInviteOthersProperty, gdata.calendar.data.GuestsCanModifyProperty, gdata.calendar.data.GuestsCanSeeGuestsProperty, gdata.calendar.data.HiddenProperty, gdata.calendar.data.IcalUIDProperty, gdata.calendar.data.OverrideNameProperty, gdata.calendar.data.PrivateCopyProperty, gdata.calendar.data.QuickAddProperty, gdata.calendar.data.ResourceProperty, gdata.calendar.data.EventWho, gdata.calendar.data.SelectedProperty, gdata.calendar.data.SendAclNotificationsProperty, gdata.calendar.data.CalendarAclEntry, gdata.calendar.data.CalendarAclFeed, gdata.calendar.data.SendEventNotificationsProperty, gdata.calendar.data.SequenceNumberProperty, gdata.calendar.data.CalendarRecurrenceExceptionEntry, gdata.calendar.data.CalendarRecurrenceException, gdata.calendar.data.SettingsProperty, gdata.calendar.data.SettingsEntry, gdata.calendar.data.CalendarSettingsFeed, gdata.calendar.data.SuppressReplyNotificationsProperty, gdata.calendar.data.SyncEventProperty, gdata.calendar.data.CalendarEventEntry, gdata.calendar.data.TimeZoneProperty, gdata.calendar.data.TimesCleanedProperty, gdata.calendar.data.CalendarEntry, gdata.calendar.data.CalendarEventFeed, gdata.calendar.data.CalendarFeed, gdata.calendar.data.WebContentGadgetPref, gdata.calendar.data.WebContent, gdata.finance.data.Commission, gdata.finance.data.CostBasis, gdata.finance.data.DaysGain, gdata.finance.data.Gain, gdata.finance.data.MarketValue, gdata.finance.data.PortfolioData, gdata.finance.data.PortfolioEntry, gdata.finance.data.PortfolioFeed, gdata.finance.data.PositionData, gdata.finance.data.Price, gdata.finance.data.Symbol, gdata.finance.data.PositionEntry, gdata.finance.data.PositionFeed, gdata.finance.data.TransactionData, gdata.finance.data.TransactionEntry, gdata.finance.data.TransactionFeed, gdata.notebook.data.ComesAfter, gdata.notebook.data.NoteEntry, gdata.notebook.data.NotebookFeed, gdata.notebook.data.NotebookListEntry, gdata.notebook.data.NotebookListFeed, gdata.youtube.data.ComplaintEntry, gdata.youtube.data.ComplaintFeed, gdata.youtube.data.RatingEntry, gdata.youtube.data.RatingFeed, gdata.youtube.data.YouTubeMediaContent, gdata.youtube.data.YtAge, gdata.youtube.data.YtBooks, gdata.youtube.data.YtCompany, gdata.youtube.data.YtDescription, gdata.youtube.data.YtDuration, gdata.youtube.data.YtFirstName, gdata.youtube.data.YtGender, gdata.youtube.data.YtHobbies, gdata.youtube.data.YtHometown, gdata.youtube.data.YtLastName, gdata.youtube.data.YtLocation, gdata.youtube.data.YtMovies, gdata.youtube.data.YtMusic, gdata.youtube.data.YtNoEmbed, gdata.youtube.data.YtOccupation, gdata.youtube.data.YtPlaylistId, gdata.youtube.data.YtPosition, gdata.youtube.data.YtPrivate, gdata.youtube.data.YtQueryString, gdata.youtube.data.YtRacy, gdata.youtube.data.YtRecorded, gdata.youtube.data.YtRelationship, gdata.youtube.data.YtSchool, gdata.youtube.data.YtStatistics, gdata.youtube.data.YtStatus, gdata.youtube.data.YtUserProfileStatistics, gdata.youtube.data.YtUsername, gdata.youtube.data.FriendEntry, gdata.youtube.data.FriendFeed, gdata.youtube.data.YtVideoStatistics, gdata.youtube.data.ChannelEntry, gdata.youtube.data.ChannelFeed, gdata.youtube.data.FavoriteEntry, gdata.youtube.data.FavoriteFeed, gdata.youtube.data.YouTubeMediaCredit, gdata.youtube.data.YouTubeMediaRating, gdata.youtube.data.YtAboutMe, gdata.youtube.data.UserProfileEntry, gdata.youtube.data.UserProfileFeed, gdata.youtube.data.YtAspectRatio, gdata.youtube.data.YtBasePublicationState, gdata.youtube.data.YtPublicationState, gdata.youtube.data.YouTubeAppControl, gdata.youtube.data.YtCaptionPublicationState, gdata.youtube.data.YouTubeCaptionAppControl, gdata.youtube.data.CaptionTrackEntry, gdata.youtube.data.CaptionTrackFeed, gdata.youtube.data.YtCountHint, gdata.youtube.data.PlaylistLinkEntry, gdata.youtube.data.PlaylistLinkFeed, gdata.youtube.data.YtModerationStatus, gdata.youtube.data.YtPlaylistTitle, gdata.youtube.data.SubscriptionEntry, gdata.youtube.data.SubscriptionFeed, gdata.youtube.data.YtSpam, gdata.youtube.data.CommentEntry, gdata.youtube.data.CommentFeed, gdata.youtube.data.YtUploaded, gdata.youtube.data.YtVideoId, gdata.youtube.data.YouTubeMediaGroup, gdata.youtube.data.VideoEntryBase, gdata.youtube.data.PlaylistEntry, gdata.youtube.data.PlaylistFeed, gdata.youtube.data.VideoEntry, gdata.youtube.data.VideoFeed, gdata.youtube.data.VideoMessageEntry, gdata.youtube.data.VideoMessageFeed, gdata.youtube.data.UserEventEntry, gdata.youtube.data.UserEventFeed, gdata.youtube.data.VideoModerationEntry, gdata.youtube.data.VideoModerationFeed, gdata.media.data.MediaCategory, gdata.media.data.MediaCopyright, gdata.media.data.MediaCredit, gdata.media.data.MediaDescription, gdata.media.data.MediaHash, gdata.media.data.MediaKeywords, gdata.media.data.MediaPlayer, gdata.media.data.MediaRating, gdata.media.data.MediaRestriction, gdata.media.data.MediaText, gdata.media.data.MediaThumbnail, gdata.media.data.MediaTitle, gdata.media.data.MediaContent, gdata.media.data.MediaGroup, gdata.webmastertools.data.CrawlIssueCrawlType, gdata.webmastertools.data.CrawlIssueDateDetected, gdata.webmastertools.data.CrawlIssueDetail, gdata.webmastertools.data.CrawlIssueIssueType, gdata.webmastertools.data.CrawlIssueLinkedFromUrl, gdata.webmastertools.data.CrawlIssueUrl, gdata.webmastertools.data.CrawlIssueEntry, gdata.webmastertools.data.CrawlIssuesFeed, gdata.webmastertools.data.Indexed, gdata.webmastertools.data.Keyword, gdata.webmastertools.data.KeywordEntry, gdata.webmastertools.data.KeywordsFeed, gdata.webmastertools.data.LastCrawled, gdata.webmastertools.data.MessageBody, gdata.webmastertools.data.MessageDate, gdata.webmastertools.data.MessageLanguage, gdata.webmastertools.data.MessageRead, gdata.webmastertools.data.MessageSubject, gdata.webmastertools.data.SiteId, gdata.webmastertools.data.MessageEntry, gdata.webmastertools.data.MessagesFeed, gdata.webmastertools.data.SitemapEntry, gdata.webmastertools.data.SitemapMobileMarkupLanguage, gdata.webmastertools.data.SitemapMobile, gdata.webmastertools.data.SitemapNewsPublicationLabel, gdata.webmastertools.data.SitemapNews, gdata.webmastertools.data.SitemapType, gdata.webmastertools.data.SitemapUrlCount, gdata.webmastertools.data.SitemapsFeed, gdata.webmastertools.data.VerificationMethod, gdata.webmastertools.data.Verified, gdata.webmastertools.data.SiteEntry, gdata.webmastertools.data.SitesFeed, gdata.contacts.data.BillingInformation, gdata.contacts.data.Birthday, gdata.contacts.data.CalendarLink, gdata.contacts.data.DirectoryServer, gdata.contacts.data.Event, gdata.contacts.data.ExternalId, gdata.contacts.data.Gender, gdata.contacts.data.Hobby, gdata.contacts.data.Initials, gdata.contacts.data.Jot, gdata.contacts.data.Language, gdata.contacts.data.MaidenName, gdata.contacts.data.Mileage, gdata.contacts.data.NickName, gdata.contacts.data.Occupation, gdata.contacts.data.Priority, gdata.contacts.data.Relation, gdata.contacts.data.Sensitivity, gdata.contacts.data.UserDefinedField, gdata.contacts.data.Website, gdata.contacts.data.HouseName, gdata.contacts.data.Street, gdata.contacts.data.POBox, gdata.contacts.data.Neighborhood, gdata.contacts.data.City, gdata.contacts.data.SubRegion, gdata.contacts.data.Region, gdata.contacts.data.PostalCode, gdata.contacts.data.Country, gdata.contacts.data.PersonEntry, gdata.contacts.data.Deleted, gdata.contacts.data.GroupMembershipInfo, gdata.contacts.data.ContactEntry, gdata.contacts.data.ContactsFeed, gdata.contacts.data.SystemGroup, gdata.contacts.data.GroupEntry, gdata.contacts.data.GroupsFeed, gdata.contacts.data.ProfileEntry, gdata.contacts.data.ProfilesFeed, gdata.opensearch.data.ItemsPerPage, gdata.opensearch.data.StartIndex, gdata.opensearch.data.TotalResults, )) def suite(): return conf.build_suite([DataSmokeTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeffrey Scudder)' import unittest import gdata.codesearch import gdata.test_data class CodeSearchDataTest(unittest.TestCase): def setUp(self): self.feed = gdata.codesearch.CodesearchFeedFromString( gdata.test_data.CODE_SEARCH_FEED) def testCorrectXmlConversion(self): self.assert_(self.feed.id.text == 'http://www.google.com/codesearch/feeds/search?q=malloc') self.assert_(len(self.feed.entry) == 10) for entry in self.feed.entry: if entry.id.text == ('http://www.google.com/codesearch?hl=en&q=+ma' 'lloc+show:LDjwp-Iqc7U:84hEYaYsZk8:xDGReDhvNi0&sa=N&ct=rx&cd=1' '&cs_p=http://www.gnu.org&cs_f=software/autoconf/manual/autoco' 'nf-2.60/autoconf.html-002&cs_p=http://www.gnu.org&cs_f=softwa' 're/autoconf/manual/autoconf-2.60/autoconf.html-002#first'): self.assert_(len(entry.match) == 4) for match in entry.match: if match.line_number == '4': self.assert_(match.type == 'text/html') self.assert_(entry.file.name == 'software/autoconf/manual/autoconf-2.60/autoconf.html-002') self.assert_(entry.package.name == 'http://www.gnu.org') self.assert_(entry.package.uri == 'http://www.gnu.org') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # # Copyright Google 2007-2008, all rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import unittest import getpass import gdata.spreadsheet.text_db import gdata.spreadsheet.service __author__ = 'api.jscudder (Jeffrey Scudder)' username = '' password = '' class FactoryTest(unittest.TestCase): def setUp(self): self.client = gdata.spreadsheet.text_db.DatabaseClient() def testBadCredentials(self): try: self.client.SetCredentials('foo', 'bar') self.fail() except gdata.spreadsheet.text_db.Error, e: pass def testCreateGetAndDeleteDatabase(self): db_title = 'google_spreadsheets_db unit test 1' self.client.SetCredentials(username, password) db = self.client.CreateDatabase(db_title) # Test finding the database using the name time.sleep(5) db_list = self.client.GetDatabases(name=db_title) self.assert_(len(db_list) >= 1) if len(db_list) >= 1: self.assert_(db_list[0].entry.title.text == db_title) # Test finding the database using the spreadsheet key db_list = self.client.GetDatabases(spreadsheet_key=db.spreadsheet_key) self.assert_(len(db_list) == 1) self.assert_(db_list[0].entry.title.text == db_title) # Delete the test spreadsheet time.sleep(10) db.Delete() class DatabaseTest(unittest.TestCase): def setUp(self): client = gdata.spreadsheet.text_db.DatabaseClient(username, password) self.db = client.CreateDatabase('google_spreadsheets_db unit test 2') def tearDown(self): time.sleep(10) self.db.Delete() def testCreateGetAndDeleteTable(self): table = self.db.CreateTable('test1', ['1','2','3']) # Try to get the new table using the worksheet id. table_list = self.db.GetTables(worksheet_id=table.worksheet_id) self.assert_(len(table_list) == 1) self.assert_(table_list[0].entry.title.text, 'test1') # Try to get the table using the name table_list = self.db.GetTables(name='test1') self.assert_(len(table_list) == 1) self.assert_(table_list[0].entry.title.text, 'test1') # Delete the table table.Delete() class TableTest(unittest.TestCase): def setUp(self): client = gdata.spreadsheet.text_db.DatabaseClient(username, password) self.db = client.CreateDatabase('google_spreadsheets_db unit test 3') self.table = self.db.CreateTable('test1', ['a','b','c_d','a', 'd:e']) def tearDown(self): time.sleep(10) self.db.Delete() def testCreateGetAndDeleteRecord(self): new_record = self.table.AddRecord({'a':'test1', 'b':'test2', 'cd':'test3', 'a_2':'test4', 'de':'test5'}) # Test getting record by line number. record = self.table.GetRecord(row_number=1) self.assert_(record is not None) self.assert_(record.content['a'] == 'test1') self.assert_(record.content['b'] == 'test2') self.assert_(record.content['cd'] == 'test3') self.assert_(record.content['a_2'] == 'test4') # Test getting record using the id. record_list = self.table.GetRecord(row_id=new_record.row_id) self.assert_(record is not None) # Delete the record. time.sleep(10) new_record.Delete() def testPushPullSyncing(self): # Get two copies of the same row. first_copy = self.table.AddRecord({'a':'1', 'b':'2', 'cd':'3', 'a_2':'4', 'de':'5'}) second_copy = self.table.GetRecord(first_copy.row_id) # Make changes in the first copy first_copy.content['a'] = '7' first_copy.content['b'] = '9' # Try to get the changes before they've been committed second_copy.Pull() self.assert_(second_copy.content['a'] == '1') self.assert_(second_copy.content['b'] == '2') # Commit the changes, the content should now be different first_copy.Push() second_copy.Pull() self.assert_(second_copy.content['a'] == '7') self.assert_(second_copy.content['b'] == '9') # Make changes to the second copy, push, then try to push changes from # the first copy. first_copy.content['a'] = '10' second_copy.content['a'] = '15' first_copy.Push() try: second_copy.Push() # The second update should raise and exception due to a 409 conflict. self.fail() except gdata.spreadsheet.service.RequestError: pass except Exception, error: #TODO: Why won't the except RequestError catch this? pass def testFindRecords(self): # Add lots of test records: self.table.AddRecord({'a':'1', 'b':'2', 'cd':'3', 'a_2':'4', 'de':'5'}) self.table.AddRecord({'a':'hi', 'b':'2', 'cd':'20', 'a_2':'4', 'de':'5'}) self.table.AddRecord({'a':'2', 'b':'2', 'cd':'3'}) self.table.AddRecord({'a':'2', 'b':'2', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'hi hi hi', 'b':'2', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'"5"', 'b':'5', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'5', 'b':'5', 'cd':'15', 'de':'7'}) time.sleep(10) matches = self.table.FindRecords('a == 1') self.assert_(len(matches) == 1) self.assert_(matches[0].content['a'] == '1') self.assert_(matches[0].content['b'] == '2') matches = self.table.FindRecords('a > 1 && cd < 20') self.assert_(len(matches) == 4) matches = self.table.FindRecords('cd < de') self.assert_(len(matches) == 7) matches = self.table.FindRecords('a == b') self.assert_(len(matches) == 0) matches = self.table.FindRecords('a == 5') self.assert_(len(matches) == 1) def testIterateResultSet(self): # Populate the table with test data. self.table.AddRecord({'a':'1', 'b':'2', 'cd':'3', 'a_2':'4', 'de':'5'}) self.table.AddRecord({'a':'hi', 'b':'2', 'cd':'20', 'a_2':'4', 'de':'5'}) self.table.AddRecord({'a':'2', 'b':'2', 'cd':'3'}) self.table.AddRecord({'a':'2', 'b':'2', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'hi hi hi', 'b':'2', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'"5"', 'b':'5', 'cd':'15', 'de':'7'}) self.table.AddRecord({'a':'5', 'b':'5', 'cd':'15', 'de':'7'}) # Get the first two rows. records = self.table.GetRecords(1, 2) self.assert_(len(records) == 2) self.assert_(records[0].content['a'] == '1') self.assert_(records[1].content['a'] == 'hi') # Then get the next two rows. next_records = records.GetNext() self.assert_(len(next_records) == 2) self.assert_(next_records[0].content['a'] == '2') self.assert_(next_records[0].content['cd'] == '3') self.assert_(next_records[1].content['cd'] == '15') self.assert_(next_records[1].content['de'] == '7') def testLookupFieldsOnPreexistingTable(self): existing_table = self.db.GetTables(name='test1')[0] existing_table.LookupFields() self.assertEquals(existing_table.fields, ['a', 'b', 'cd', 'a_2', 'de']) if __name__ == '__main__': if not username: username = raw_input('Spreadsheets API | Text DB Tests\n' 'Please enter your username: ') if not password: password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.spreadsheet.service import gdata.service import atom.service import gdata.spreadsheet import atom import getpass username = '' password = '' ss_key = '' ws_key = '' class DocumentQueryTest(unittest.TestCase): def setUp(self): self.query = gdata.spreadsheet.service.DocumentQuery() def testTitle(self): self.query['title'] = 'my title' self.assert_(self.query['title'] == 'my title') self.assert_(self.query.ToUri() == '?title=my+title') def testTitleExact(self): self.query['title-exact'] = 'true' self.assert_(self.query['title-exact'] == 'true') self.assert_(self.query.ToUri() == '?title-exact=true') class CellQueryTest(unittest.TestCase): def setUp(self): self.query = gdata.spreadsheet.service.CellQuery() def testMinRow(self): self.query['min-row'] = '1' self.assert_(self.query['min-row'] == '1') self.assert_(self.query.ToUri() == '?min-row=1') def testMaxRow(self): self.query['max-row'] = '100' self.assert_(self.query['max-row'] == '100') self.assert_(self.query.ToUri() == '?max-row=100') def testMinCol(self): self.query['min-col'] = '2' self.assert_(self.query['min-col'] == '2') self.assert_(self.query.ToUri() == '?min-col=2') def testMaxCol(self): self.query['max-col'] = '20' self.assert_(self.query['max-col'] == '20') self.assert_(self.query.ToUri() == '?max-col=20') def testRange(self): self.query['range'] = 'A1:B4' self.assert_(self.query['range'] == 'A1:B4') self.assert_(self.query.ToUri() == '?range=A1%3AB4') def testReturnEmpty(self): self.query['return-empty'] = 'false' self.assert_(self.query['return-empty'] == 'false') self.assert_(self.query.ToUri() == '?return-empty=false') class ListQueryTest(unittest.TestCase): def setUp(self): self.query = gdata.spreadsheet.service.ListQuery() def testSpreadsheetQuery(self): self.query['sq'] = 'first=john&last=smith' self.assert_(self.query['sq'] == 'first=john&last=smith') self.assert_(self.query.ToUri() == '?sq=first%3Djohn%26last%3Dsmith') def testOrderByQuery(self): self.query['orderby'] = 'column:first' self.assert_(self.query['orderby'] == 'column:first') self.assert_(self.query.ToUri() == '?orderby=column%3Afirst') def testReverseQuery(self): self.query['reverse'] = 'true' self.assert_(self.query['reverse'] == 'true') self.assert_(self.query.ToUri() == '?reverse=true') class SpreadsheetsServiceTest(unittest.TestCase): def setUp(self): self.key = ss_key self.worksheet = ws_key self.gd_client = gdata.spreadsheet.service.SpreadsheetsService() self.gd_client.email = username self.gd_client.password = password self.gd_client.source = 'SpreadsheetsClient "Unit" Tests' self.gd_client.ProgrammaticLogin() def testGetSpreadsheetsFeed(self): entry = self.gd_client.GetSpreadsheetsFeed(self.key) self.assert_(isinstance(entry, gdata.spreadsheet.SpreadsheetsSpreadsheet)) def testGetWorksheetsFeed(self): feed = self.gd_client.GetWorksheetsFeed(self.key) self.assert_(isinstance(feed, gdata.spreadsheet.SpreadsheetsWorksheetsFeed)) entry = self.gd_client.GetWorksheetsFeed(self.key, self.worksheet) self.assert_(isinstance(entry, gdata.spreadsheet.SpreadsheetsWorksheet)) def testGetCellsFeed(self): feed = self.gd_client.GetCellsFeed(self.key) self.assert_(isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed)) entry = self.gd_client.GetCellsFeed(self.key, cell='R5C1') self.assert_(isinstance(entry, gdata.spreadsheet.SpreadsheetsCell)) def testGetListFeed(self): feed = self.gd_client.GetListFeed(self.key) self.assert_(isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed)) entry = self.gd_client.GetListFeed(self.key, row_id='cpzh4') self.assert_(isinstance(entry, gdata.spreadsheet.SpreadsheetsList)) def testUpdateCell(self): self.gd_client.UpdateCell(row='5', col='1', inputValue='', key=self.key) self.gd_client.UpdateCell(row='5', col='1', inputValue='newer data', key=self.key) def testBatchUpdateCell(self): cell_feed = self.gd_client.GetCellsFeed(key=self.key) edit_cell = cell_feed.entry[0] old_cell_value = 'a1' # Create a batch request to change the contents of a cell. batch_feed = gdata.spreadsheet.SpreadsheetsCellsFeed() edit_cell.cell.inputValue = 'New Value' batch_feed.AddUpdate(edit_cell) result = self.gd_client.ExecuteBatch(batch_feed, url=cell_feed.GetBatchLink().href) self.assertEquals(len(result.entry), 1) self.assertEquals(result.entry[0].cell.inputValue, 'New Value') # Make a second batch request to change the cell's value back. edit_cell = result.entry[0] edit_cell.cell.inputValue = old_cell_value batch_feed = gdata.spreadsheet.SpreadsheetsCellsFeed() batch_feed.AddUpdate(edit_cell) restored = self.gd_client.ExecuteBatch(batch_feed, url=cell_feed.GetBatchLink().href) self.assertEquals(len(restored.entry), 1) self.assertEquals(restored.entry[0].cell.inputValue, old_cell_value) def testInsertUpdateRow(self): entry = self.gd_client.InsertRow({'a1':'new', 'b1':'row', 'c1':'was', 'd1':'here'}, self.key) entry = self.gd_client.UpdateRow(entry, {'a1':'newer', 'b1':entry.custom['b1'].text, 'c1':entry.custom['c1'].text, 'd1':entry.custom['d1'].text}) self.gd_client.DeleteRow(entry) def testWorksheetCRUD(self): # Add a new worksheet. new_worksheet = self.gd_client.AddWorksheet('worksheet_title_test_12', '2', 3, self.key) self.assertEquals(new_worksheet.col_count.text, '3') self.assertEquals(new_worksheet.row_count.text, '2') self.assertEquals(new_worksheet.title.text, 'worksheet_title_test_12') # Change the dimensions and title of the new worksheet. new_worksheet.col_count.text = '1' new_worksheet.title.text = 'edited worksheet test12' edited_worksheet = self.gd_client.UpdateWorksheet(new_worksheet) self.assertEquals(edited_worksheet.col_count.text, '1') self.assertEquals(edited_worksheet.row_count.text, '2') self.assertEquals(edited_worksheet.title.text, 'edited worksheet test12') # Delete the new worksheet. result = self.gd_client.DeleteWorksheet(edited_worksheet) self.assertEquals(result, True) if __name__ == '__main__': print ('Spreadsheet Tests\nNOTE: Please run these tests only with a test ' 'account. The tests may delete or update your data.') print ('These tests must be run on a sheet with this data:\n' 'a1,b1,c1,d1\n' '1,2,3,4') username = raw_input('Please enter your username: ') password = getpass.getpass() ss_key = raw_input('Please enter your spreadsheet key: ') ws_key = raw_input('Please enter your worksheet key (usually od6): ') unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import unittest import getpass try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.service import gdata import gdata.auth import atom import atom.service import atom.token_store import gdata.base import os.path from gdata import test_data import atom.mock_http import atom.mock_http_core username = '' password = '' test_image_location = '../testimage.jpg' test_image_name = 'testimage.jpg' class GDataServiceMediaUnitTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.service.GDataService() self.gd_client.email = username self.gd_client.password = password self.gd_client.service = 'lh2' self.gd_client.source = 'GDataService Media "Unit" Tests' try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') # create a test album gd_entry = gdata.GDataEntry() gd_entry.title = atom.Title(text='GData Test Album') gd_entry.category.append(atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/photos/2007#album')) self.album_entry = self.gd_client.Post(gd_entry, 'http://picasaweb.google.com/data/feed/api/user/' + username) def tearDown(self): album_entry = self.gd_client.Get(self.album_entry.id.text) self.gd_client.Delete(album_entry.GetEditLink().href) def testSourceGeneratesUserAgentHeader(self): self.gd_client.source = 'GoogleInc-ServiceUnitTest-1' self.assert_(self.gd_client.additional_headers['User-Agent'].startswith( 'GoogleInc-ServiceUnitTest-1 GData-Python')) def testMedia1(self): # Create media-only ms = gdata.MediaSource() ms.setFile(test_image_location, 'image/jpeg') media_entry = self.gd_client.Post(None, self.album_entry.GetFeedLink().href, media_source = ms) self.assert_(media_entry is not None) self.assert_(isinstance(media_entry, gdata.GDataEntry)) self.assert_(media_entry.IsMedia()) # Update media & metadata ms = gdata.MediaSource() ms.setFile(test_image_location, 'image/jpeg') media_entry.summary = atom.Summary(text='Test Image') media_entry2 = self.gd_client.Put(media_entry, media_entry.GetEditLink().href, media_source = ms) self.assert_(media_entry2 is not None) self.assert_(isinstance(media_entry2, gdata.GDataEntry)) self.assert_(media_entry2.IsMedia()) self.assert_(media_entry2.summary.text == 'Test Image') # Read media binary imageSource = self.gd_client.GetMedia(media_entry2.GetMediaURL()) self.assert_(isinstance(imageSource, gdata.MediaSource)) self.assert_(imageSource.content_type == 'image/jpeg') self.assert_(imageSource.content_length) imageData = imageSource.file_handle.read() self.assert_(imageData) # Delete entry response = self.gd_client.Delete(media_entry2.GetEditLink().href) self.assert_(response) def testMedia2(self): # Create media & metadata ms = gdata.MediaSource() ms.setFile(test_image_location, 'image/jpeg') new_media_entry = gdata.GDataEntry() new_media_entry.title = atom.Title(text='testimage1.jpg') new_media_entry.summary = atom.Summary(text='Test Image') new_media_entry.category.append(atom.Category(scheme = 'http://schemas.google.com/g/2005#kind', term = 'http://schemas.google.com/photos/2007#photo')) media_entry = self.gd_client.Post(new_media_entry, self.album_entry.GetFeedLink().href, media_source = ms) self.assert_(media_entry is not None) self.assert_(isinstance(media_entry, gdata.GDataEntry)) self.assert_(media_entry.IsMedia()) self.assert_(media_entry.summary.text == 'Test Image') # Update media only ms = gdata.MediaSource() ms.setFile(test_image_location, 'image/jpeg') media_entry = self.gd_client.Put(None, media_entry.GetEditMediaLink().href, media_source = ms) self.assert_(media_entry is not None) self.assert_(isinstance(media_entry, gdata.GDataEntry)) self.assert_(media_entry.IsMedia()) # Delete entry response = self.gd_client.Delete(media_entry.GetEditLink().href) self.assert_(response) def testMediaConstructorDefaults(self): ms = gdata.MediaSource() ms.setFile(test_image_location, 'image/jpeg') self.assert_(ms is not None) self.assert_(isinstance(ms, gdata.MediaSource)) self.assertEquals(ms.file_name, test_image_name) self.assertEquals(ms.content_type, 'image/jpeg') def testMediaConstructorWithFilePath(self): ms = gdata.MediaSource(file_path=test_image_location, content_type='image/jpeg') self.assert_(ms is not None) self.assert_(isinstance(ms, gdata.MediaSource)) self.assertEquals(ms.file_name, test_image_name) self.assertEquals(ms.content_type, 'image/jpeg') def testMediaConstructorWithFileHandle(self): fh = open(test_image_location, 'r') len = os.path.getsize(test_image_location) ms = gdata.MediaSource(fh, 'image/jpeg', len, file_name=test_image_location) self.assert_(ms is not None) self.assert_(isinstance(ms, gdata.MediaSource)) self.assertEquals(ms.file_name, test_image_location) self.assertEquals(ms.content_type, 'image/jpeg') class GDataServiceUnitTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.service.GDataService() self.gd_client.email = username self.gd_client.password = password self.gd_client.service = 'gbase' self.gd_client.source = 'GDataClient "Unit" Tests' def testProperties(self): email_string = 'Test Email' password_string = 'Passwd' self.gd_client.email = email_string self.assertEquals(self.gd_client.email, email_string) self.gd_client.password = password_string self.assertEquals(self.gd_client.password, password_string) def testCorrectLogin(self): try: self.gd_client.ProgrammaticLogin() self.assert_(isinstance( self.gd_client.token_store.find_token( 'http://base.google.com/base/feeds/'), gdata.auth.ClientLoginToken)) self.assert_(self.gd_client.captcha_token is None) self.assert_(self.gd_client.captcha_url is None) except gdata.service.CaptchaRequired: self.fail('Required Captcha') def testDefaultHttpClient(self): self.assert_(isinstance(self.gd_client.http_client, atom.http.HttpClient)) def testGet(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.additional_headers = {'X-Google-Key': 'ABQIAAAAoLioN3buSs9KqIIq9V' + 'mkFxT2yXp_ZAY8_ufC3CFXhHIE' + '1NvwkxRK8C1Q8OWhsWA2AIKv-c' + 'VKlVrNhQ'} self.gd_client.server = 'base.google.com' result = self.gd_client.Get('/base/feeds/snippets?bq=digital+camera') self.assert_(result is not None) self.assert_(isinstance(result, atom.Feed)) def testGetWithAuthentication(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.additional_headers = {'X-Google-Key': 'ABQIAAAAoLioN3buSs9KqIIq9V' + 'mkFxT2yXp_ZAY8_ufC3CFXhHIE' + '1NvwkxRK8C1Q8OWhsWA2AIKv-c' + 'VKlVrNhQ'} self.gd_client.server = 'base.google.com' result = self.gd_client.Get('/base/feeds/items?bq=digital+camera') self.assert_(result is not None) self.assert_(isinstance(result, atom.Feed)) def testGetEntry(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.server = 'base.google.com' try: result = self.gd_client.GetEntry('/base/feeds/items?bq=digital+camera') self.fail( 'Result from server in GetEntry should have raised an exception') except gdata.service.UnexpectedReturnType: pass def testGetFeed(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.server = 'base.google.com' result = self.gd_client.GetFeed('/base/feeds/items?bq=digital+camera') self.assert_(result is not None) self.assert_(isinstance(result, atom.Feed)) def testGetWithResponseTransformer(self): # Query Google Base and interpret the results as a GBaseSnippetFeed. feed = self.gd_client.Get( 'http://www.google.com/base/feeds/snippets?bq=digital+camera', converter=gdata.base.GBaseSnippetFeedFromString) self.assertEquals(isinstance(feed, gdata.base.GBaseSnippetFeed), True) def testPostPutAndDelete(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.additional_headers = {'X-Google-Key': 'ABQIAAAAoLioN3buSs9KqIIq9V' + 'mkFxT2yXp_ZAY8_ufC3CFXhHIE' + '1NvwkxRK8C1Q8OWhsWA2AIKv-c' + 'VKlVrNhQ'} self.gd_client.server = 'base.google.com' # Insert a new item response = self.gd_client.Post(test_data.TEST_BASE_ENTRY, '/base/feeds/items') self.assert_(response is not None) self.assert_(isinstance(response, atom.Entry)) self.assert_(response.category[0].term == 'products') # Find the item id of the created item item_id = response.id.text.lstrip( 'http://www.google.com/base/feeds/items/') self.assert_(item_id is not None) updated_xml = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) # Change one of the labels in the item updated_xml.label[2].text = 'beach ball' # Update the item response = self.gd_client.Put(updated_xml, '/base/feeds/items/%s' % item_id) self.assert_(response is not None) new_base_item = gdata.base.GBaseItemFromString(str(response)) self.assert_(isinstance(new_base_item, atom.Entry)) # Delete the item the test just created. response = self.gd_client.Delete('/base/feeds/items/%s' % item_id) self.assert_(response) def testPostPutAndDeleteWithConverters(self): try: self.gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: self.fail('Required Captcha') except gdata.service.BadAuthentication: self.fail('Bad Authentication') except gdata.service.Error: self.fail('Login Error') self.gd_client.additional_headers = {'X-Google-Key': 'ABQIAAAAoLioN3buSs9KqIIq9V' + 'mkFxT2yXp_ZAY8_ufC3CFXhHIE' + '1NvwkxRK8C1Q8OWhsWA2AIKv-c' + 'VKlVrNhQ'} self.gd_client.server = 'base.google.com' # Insert a new item response = self.gd_client.Post(test_data.TEST_BASE_ENTRY, '/base/feeds/items', converter=gdata.base.GBaseItemFromString) self.assert_(response is not None) self.assert_(isinstance(response, atom.Entry)) self.assert_(isinstance(response, gdata.base.GBaseItem)) self.assert_(response.category[0].term == 'products') updated_xml = gdata.base.GBaseItemFromString(test_data.TEST_BASE_ENTRY) # Change one of the labels in the item updated_xml.label[2].text = 'beach ball' # Update the item response = self.gd_client.Put(updated_xml, response.id.text, converter=gdata.base.GBaseItemFromString) self.assertEquals(response is not None, True) self.assertEquals(isinstance(response, gdata.base.GBaseItem), True) # Delete the item the test just created. response = self.gd_client.Delete(response.id.text) self.assert_(response) def testCaptchaUrlGeneration(self): # Populate the mock server with a pairing for a ClientLogin request to a # CAPTCHA challenge. mock_client = atom.mock_http.MockHttpClient() captcha_response = atom.mock_http.MockResponse( body="""Url=http://www.google.com/login/captcha Error=CaptchaRequired CaptchaToken=DQAAAGgAdkI1LK9 CaptchaUrl=Captcha?ctoken=HiteT4b0Bk5Xg18_AcVoP6-yFkHPibe7O9EqxeiI7lUSN """, status=403, reason='Access Forbidden') mock_client.add_response(captcha_response, 'POST', 'https://www.google.com/accounts/ClientLogin') # Set the exising client's handler so that it will make requests to the # mock service instead of the real server. self.gd_client.http_client = mock_client try: self.gd_client.ProgrammaticLogin() self.fail('Login attempt should have caused a CAPTCHA challenge.') except gdata.service.CaptchaRequired, error: self.assertEquals(self.gd_client.captcha_url, ('https://www.google.com/accounts/Captcha?ctoken=HiteT4b0Bk5Xg18_' 'AcVoP6-yFkHPibe7O9EqxeiI7lUSN')) class DeleteWithUrlParamsTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.service.GDataService() # Set the client to echo the request back in the response. self.gd_client.http_client.v2_http_client = ( atom.mock_http_core.SettableHttpClient(200, 'OK', '', {})) def testDeleteWithUrlParams(self): self.assert_(self.gd_client.Delete('http://example.com/test', {'TestHeader': '123'}, {'urlParam1': 'a', 'urlParam2': 'test'})) request = self.gd_client.http_client.v2_http_client.last_request self.assertEqual(request.uri.host, 'example.com') self.assertEqual(request.uri.path, '/test') self.assertEqual(request.uri.query, {'urlParam1': 'a', 'urlParam2': 'test'}) def testDeleteWithSessionId(self): self.gd_client._SetSessionId('test_session_id') self.assert_(self.gd_client.Delete('http://example.com/test', {'TestHeader': '123'}, {'urlParam1': 'a', 'urlParam2': 'test'})) request = self.gd_client.http_client.v2_http_client.last_request self.assertEqual(request.uri.host, 'example.com') self.assertEqual(request.uri.path, '/test') self.assertEqual(request.uri.query, {'urlParam1': 'a', 'urlParam2': 'test', 'gsessionid': 'test_session_id'}) class QueryTest(unittest.TestCase): def setUp(self): self.query = gdata.service.Query() def testQueryShouldBehaveLikeDict(self): try: self.query['zap'] self.fail() except KeyError: pass self.query['zap'] = 'x' self.assert_(self.query['zap'] == 'x') def testContructorShouldRejectBadInputs(self): test_q = gdata.service.Query(params=[1,2,3,4]) self.assert_(len(test_q.keys()) == 0) def testTextQueryProperty(self): self.assert_(self.query.text_query is None) self.query['q'] = 'test1' self.assert_(self.query.text_query == 'test1') self.query.text_query = 'test2' self.assert_(self.query.text_query == 'test2') def testOrderByQueryProperty(self): self.assert_(self.query.orderby is None) self.query['orderby'] = 'updated' self.assert_(self.query.orderby == 'updated') self.query.orderby = 'starttime' self.assert_(self.query.orderby == 'starttime') def testQueryShouldProduceExampleUris(self): self.query.feed = '/base/feeds/snippets' self.query.text_query = 'This is a test' self.assert_(self.query.ToUri() == '/base/feeds/snippets?q=This+is+a+test') def testCategoriesFormattedCorrectly(self): self.query.feed = '/x' self.query.categories.append('Fritz') self.query.categories.append('Laurie') self.assert_(self.query.ToUri() == '/x/-/Fritz/Laurie') # The query's feed should not have been changed self.assert_(self.query.feed == '/x') self.assert_(self.query.ToUri() == '/x/-/Fritz/Laurie') def testCategoryQueriesShouldEscapeOrSymbols(self): self.query.feed = '/x' self.query.categories.append('Fritz|Laurie') self.assert_(self.query.ToUri() == '/x/-/Fritz%7CLaurie') def testTypeCoercionOnIntParams(self): self.query.feed = '/x' self.query.max_results = 10 self.query.start_index = 5 self.assert_(isinstance(self.query.max_results, str)) self.assert_(isinstance(self.query.start_index, str)) self.assertEquals(self.query['max-results'], '10') self.assertEquals(self.query['start-index'], '5') def testPassInCategoryListToConstructor(self): query = gdata.service.Query(feed='/feed/sample', categories=['foo', 'bar', 'eggs|spam']) url = query.ToUri() self.assert_(url.find('/foo') > -1) self.assert_(url.find('/bar') > -1) self.assert_(url.find('/eggs%7Cspam') > -1) class GetNextPageInFeedTest(unittest.TestCase): def setUp(self): self.gd_client = gdata.service.GDataService() def testGetNextPage(self): feed = self.gd_client.Get( 'http://www.google.com/base/feeds/snippets?max-results=2', converter=gdata.base.GBaseSnippetFeedFromString) self.assert_(len(feed.entry) > 0) first_id = feed.entry[0].id.text feed2 = self.gd_client.GetNext(feed) self.assert_(len(feed2.entry) > 0) next_id = feed2.entry[0].id.text self.assert_(first_id != next_id) self.assert_(feed2.__class__ == feed.__class__) class ScopeLookupTest(unittest.TestCase): def testLookupScopes(self): scopes = gdata.service.lookup_scopes('cl') self.assertEquals(scopes, gdata.service.CLIENT_LOGIN_SCOPES['cl']) scopes = gdata.service.lookup_scopes(None) self.assert_(scopes is None) scopes = gdata.service.lookup_scopes('UNKNOWN_SERVICE') self.assert_(scopes is None) class TokenLookupTest(unittest.TestCase): def setUp(self): self.client = gdata.service.GDataService() def testSetAndGetClientLoginTokenWithNoService(self): self.assert_(self.client.auth_token is None) self.client.SetClientLoginToken('foo') self.assert_(self.client.auth_token is None) self.assert_(self.client.token_store.find_token( atom.token_store.SCOPE_ALL) is not None) self.assertEquals(self.client.GetClientLoginToken(), 'foo') self.client.SetClientLoginToken('foo2') self.assertEquals(self.client.GetClientLoginToken(), 'foo2') def testSetAndGetClientLoginTokenWithService(self): self.client.service = 'cp' self.client.SetClientLoginToken('bar') self.assertEquals(self.client.GetClientLoginToken(), 'bar') # Changing the service should cause the token to no longer be found. self.client.service = 'gbase' self.client.current_token = None self.assert_(self.client.GetClientLoginToken() is None) def testSetAndGetClientLoginTokenWithScopes(self): scopes = gdata.service.CLIENT_LOGIN_SCOPES['cl'][:] scopes.extend(gdata.service.CLIENT_LOGIN_SCOPES['gbase']) self.client.SetClientLoginToken('baz', scopes=scopes) self.client.current_token = None self.assert_(self.client.GetClientLoginToken() is None) self.client.service = 'cl' self.assertEquals(self.client.GetClientLoginToken(), 'baz') self.client.service = 'gbase' self.assertEquals(self.client.GetClientLoginToken(), 'baz') self.client.service = 'wise' self.assert_(self.client.GetClientLoginToken() is None) def testLookupUsingTokenStore(self): scopes = gdata.service.CLIENT_LOGIN_SCOPES['cl'][:] scopes.extend(gdata.service.CLIENT_LOGIN_SCOPES['gbase']) self.client.SetClientLoginToken('baz', scopes=scopes) token = self.client.token_store.find_token( 'http://www.google.com/calendar/feeds/foo') self.assertEquals(token.get_token_string(), 'baz') self.assertEquals(token.auth_header, '%s%s' % ( gdata.auth.PROGRAMMATIC_AUTH_LABEL, 'baz')) token = self.client.token_store.find_token( 'http://www.google.com/calendar/') self.assert_(isinstance(token, gdata.auth.ClientLoginToken) == False) token = self.client.token_store.find_token( 'http://www.google.com/base/feeds/snippets') self.assertEquals(token.get_token_string(), 'baz') if __name__ == '__main__': print ('GData Service Media Unit Tests\nNOTE: Please run these tests only ' 'with a test account. The tests may delete or update your data.') username = raw_input('Please enter your username: ') password = getpass.getpass() unittest.main()
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jhartmann@gmail.com (Jochen Hartmann)' import unittest from gdata import test_data import gdata.youtube import gdata.youtube.service import atom YOUTUBE_TEMPLATE = '{http://gdata.youtube.com/schemas/2007}%s' YT_FORMAT = YOUTUBE_TEMPLATE % ('format') class VideoEntryTest(unittest.TestCase): def setUp(self): self.video_feed = gdata.youtube.YouTubeVideoFeedFromString( test_data.YOUTUBE_VIDEO_FEED) def testCorrectXmlParsing(self): self.assertEquals(self.video_feed.id.text, 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated') self.assertEquals(len(self.video_feed.entry), 2) for entry in self.video_feed.entry: if (entry.id.text == 'http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8'): self.assertEquals(entry.published.text, '2008-03-20T10:17:27.000-07:00') self.assertEquals(entry.updated.text, '2008-05-14T04:26:37.000-07:00') self.assertEquals(entry.category[0].scheme, 'http://gdata.youtube.com/schemas/2007/keywords.cat') self.assertEquals(entry.category[0].term, 'karyn') self.assertEquals(entry.category[1].scheme, 'http://gdata.youtube.com/schemas/2007/keywords.cat') self.assertEquals(entry.category[1].term, 'garcia') self.assertEquals(entry.category[2].scheme, 'http://gdata.youtube.com/schemas/2007/keywords.cat') self.assertEquals(entry.category[2].term, 'me') self.assertEquals(entry.category[3].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(entry.category[3].term, 'http://gdata.youtube.com/schemas/2007#video') self.assertEquals(entry.title.text, 'Me odeio por te amar - KARYN GARCIA') self.assertEquals(entry.content.text, 'http://www.karyngarcia.com.br') self.assertEquals(entry.link[0].rel, 'alternate') self.assertEquals(entry.link[0].href, 'http://www.youtube.com/watch?v=C71ypXYGho8') self.assertEquals(entry.link[1].rel, 'http://gdata.youtube.com/schemas/2007#video.related') self.assertEquals(entry.link[1].href, 'http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/related') self.assertEquals(entry.link[2].rel, 'self') self.assertEquals(entry.link[2].href, ('http://gdata.youtube.com/feeds/api/standardfeeds' '/top_rated/C71ypXYGho8')) self.assertEquals(entry.author[0].name.text, 'TvKarynGarcia') self.assertEquals(entry.author[0].uri.text, 'http://gdata.youtube.com/feeds/api/users/tvkaryngarcia') self.assertEquals(entry.media.title.text, 'Me odeio por te amar - KARYN GARCIA') self.assertEquals(entry.media.description.text, 'http://www.karyngarcia.com.br') self.assertEquals(entry.media.keywords.text, 'amar, boyfriend, garcia, karyn, me, odeio, por, te') self.assertEquals(entry.media.duration.seconds, '203') self.assertEquals(entry.media.category[0].label, 'Music') self.assertEquals(entry.media.category[0].scheme, 'http://gdata.youtube.com/schemas/2007/categories.cat') self.assertEquals(entry.media.category[0].text, 'Music') self.assertEquals(entry.media.category[1].label, 'test111') self.assertEquals(entry.media.category[1].scheme, 'http://gdata.youtube.com/schemas/2007/developertags.cat') self.assertEquals(entry.media.category[1].text, 'test111') self.assertEquals(entry.media.category[2].label, 'test222') self.assertEquals(entry.media.category[2].scheme, 'http://gdata.youtube.com/schemas/2007/developertags.cat') self.assertEquals(entry.media.category[2].text, 'test222') self.assertEquals(entry.media.content[0].url, 'http://www.youtube.com/v/C71ypXYGho8') self.assertEquals(entry.media.content[0].type, 'application/x-shockwave-flash') self.assertEquals(entry.media.content[0].medium, 'video') self.assertEquals( entry.media.content[0].extension_attributes['isDefault'], 'true') self.assertEquals( entry.media.content[0].extension_attributes['expression'], 'full') self.assertEquals( entry.media.content[0].extension_attributes['duration'], '203') self.assertEquals( entry.media.content[0].extension_attributes[YT_FORMAT], '5') self.assertEquals(entry.media.content[1].url, ('rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYDSANFEgGDA' '==/0/0/0/video.3gp')) self.assertEquals(entry.media.content[1].type, 'video/3gpp') self.assertEquals(entry.media.content[1].medium, 'video') self.assertEquals( entry.media.content[1].extension_attributes['expression'], 'full') self.assertEquals( entry.media.content[1].extension_attributes['duration'], '203') self.assertEquals( entry.media.content[1].extension_attributes[YT_FORMAT], '1') self.assertEquals(entry.media.content[2].url, ('rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYESARFEgGDA==' '/0/0/0/video.3gp')) self.assertEquals(entry.media.content[2].type, 'video/3gpp') self.assertEquals(entry.media.content[2].medium, 'video') self.assertEquals( entry.media.content[2].extension_attributes['expression'], 'full') self.assertEquals( entry.media.content[2].extension_attributes['duration'], '203') self.assertEquals( entry.media.content[2].extension_attributes[YT_FORMAT], '6') self.assertEquals(entry.media.player.url, 'http://www.youtube.com/watch?v=C71ypXYGho8') self.assertEquals(entry.media.thumbnail[0].url, 'http://img.youtube.com/vi/C71ypXYGho8/2.jpg') self.assertEquals(entry.media.thumbnail[0].height, '97') self.assertEquals(entry.media.thumbnail[0].width, '130') self.assertEquals(entry.media.thumbnail[0].extension_attributes['time'], '00:01:41.500') self.assertEquals(entry.media.thumbnail[1].url, 'http://img.youtube.com/vi/C71ypXYGho8/1.jpg') self.assertEquals(entry.media.thumbnail[1].height, '97') self.assertEquals(entry.media.thumbnail[1].width, '130') self.assertEquals(entry.media.thumbnail[1].extension_attributes['time'], '00:00:50.750') self.assertEquals(entry.media.thumbnail[2].url, 'http://img.youtube.com/vi/C71ypXYGho8/3.jpg') self.assertEquals(entry.media.thumbnail[2].height, '97') self.assertEquals(entry.media.thumbnail[2].width, '130') self.assertEquals(entry.media.thumbnail[2].extension_attributes['time'], '00:02:32.250') self.assertEquals(entry.media.thumbnail[3].url, 'http://img.youtube.com/vi/C71ypXYGho8/0.jpg') self.assertEquals(entry.media.thumbnail[3].height, '240') self.assertEquals(entry.media.thumbnail[3].width, '320') self.assertEquals(entry.media.thumbnail[3].extension_attributes['time'], '00:01:41.500') self.assertEquals(entry.statistics.view_count, '138864') self.assertEquals(entry.statistics.favorite_count, '2474') self.assertEquals(entry.rating.min, '1') self.assertEquals(entry.rating.max, '5') self.assertEquals(entry.rating.num_raters, '4626') self.assertEquals(entry.rating.average, '4.95') self.assertEquals(entry.comments.feed_link[0].href, ('http://gdata.youtube.com/feeds/api/videos/' 'C71ypXYGho8/comments')) self.assertEquals(entry.comments.feed_link[0].count_hint, '27') self.assertEquals(entry.GetSwfUrl(), 'http://www.youtube.com/v/C71ypXYGho8') self.assertEquals(entry.GetYouTubeCategoryAsString(), 'Music') class VideoEntryPrivateTest(unittest.TestCase): def setUp(self): self.entry = gdata.youtube.YouTubeVideoEntryFromString( test_data.YOUTUBE_ENTRY_PRIVATE) def testCorrectXmlParsing(self): self.assert_(isinstance(self.entry, gdata.youtube.YouTubeVideoEntry)) self.assert_(self.entry.media.private) class VideoFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeVideoFeedFromString( test_data.YOUTUBE_VIDEO_FEED) def testCorrectXmlParsing(self): self.assertEquals(self.feed.id.text, 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated') self.assertEquals(self.feed.generator.text, 'YouTube data API') self.assertEquals(self.feed.generator.uri, 'http://gdata.youtube.com/') self.assertEquals(len(self.feed.author), 1) self.assertEquals(self.feed.author[0].name.text, 'YouTube') self.assertEquals(len(self.feed.category), 1) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#video') self.assertEquals(self.feed.items_per_page.text, '25') self.assertEquals(len(self.feed.link), 4) self.assertEquals(self.feed.link[0].href, 'http://www.youtube.com/browse?s=tr') self.assertEquals(self.feed.link[0].rel, 'alternate') self.assertEquals(self.feed.link[1].href, 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated') self.assertEquals(self.feed.link[1].rel, 'http://schemas.google.com/g/2005#feed') self.assertEquals(self.feed.link[2].href, ('http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?' 'start-index=1&max-results=25')) self.assertEquals(self.feed.link[2].rel, 'self') self.assertEquals(self.feed.link[3].href, ('http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?' 'start-index=26&max-results=25')) self.assertEquals(self.feed.link[3].rel, 'next') self.assertEquals(self.feed.start_index.text, '1') self.assertEquals(self.feed.title.text, 'Top Rated') self.assertEquals(self.feed.total_results.text, '100') self.assertEquals(self.feed.updated.text, '2008-05-14T02:24:07.000-07:00') self.assertEquals(len(self.feed.entry), 2) class YouTubePlaylistFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubePlaylistFeedFromString( test_data.YOUTUBE_PLAYLIST_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.entry), 1) self.assertEquals( self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#playlistLink') class YouTubePlaylistEntryTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubePlaylistFeedFromString( test_data.YOUTUBE_PLAYLIST_FEED) def testCorrectXmlParsing(self): for entry in self.feed.entry: self.assertEquals(entry.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(entry.category[0].term, 'http://gdata.youtube.com/schemas/2007#playlistLink') self.assertEquals(entry.description.text, 'My new playlist Description') self.assertEquals(entry.feed_link[0].href, 'http://gdata.youtube.com/feeds/playlists/8BCDD04DE8F771B2') self.assertEquals(entry.feed_link[0].rel, 'http://gdata.youtube.com/schemas/2007#playlist') class YouTubePlaylistVideoFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubePlaylistVideoFeedFromString( test_data.YOUTUBE_PLAYLIST_VIDEO_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.entry), 1) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#playlist') self.assertEquals(self.feed.category[1].scheme, 'http://gdata.youtube.com/schemas/2007/tags.cat') self.assertEquals(self.feed.category[1].term, 'videos') self.assertEquals(self.feed.category[2].scheme, 'http://gdata.youtube.com/schemas/2007/tags.cat') self.assertEquals(self.feed.category[2].term, 'python') class YouTubePlaylistVideoEntryTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubePlaylistVideoFeedFromString( test_data.YOUTUBE_PLAYLIST_VIDEO_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.entry), 1) for entry in self.feed.entry: self.assertEquals(entry.position.text, '1') class YouTubeVideoCommentFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeVideoCommentFeedFromString( test_data.YOUTUBE_COMMENT_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.category), 1) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#comment') self.assertEquals(len(self.feed.link), 4) self.assertEquals(self.feed.link[0].rel, 'related') self.assertEquals(self.feed.link[0].href, 'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU') self.assertEquals(self.feed.link[1].rel, 'alternate') self.assertEquals(self.feed.link[1].href, 'http://www.youtube.com/watch?v=2Idhz9ef5oU') self.assertEquals(self.feed.link[2].rel, 'http://schemas.google.com/g/2005#feed') self.assertEquals(self.feed.link[2].href, 'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments') self.assertEquals(self.feed.link[3].rel, 'self') self.assertEquals(self.feed.link[3].href, ('http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments?' 'start-index=1&max-results=25')) self.assertEquals(len(self.feed.entry), 3) class YouTubeVideoCommentEntryTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeVideoCommentFeedFromString( test_data.YOUTUBE_COMMENT_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.entry), 3) self.assert_(isinstance(self.feed.entry[0], gdata.youtube.YouTubeVideoCommentEntry)) for entry in self.feed.entry: if (entry.id.text == ('http://gdata.youtube.com/feeds/videos/' '2Idhz9ef5oU/comments/91F809A3DE2EB81B')): self.assertEquals(entry.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(entry.category[0].term, 'http://gdata.youtube.com/schemas/2007#comment') self.assertEquals(entry.link[0].href, 'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU') self.assertEquals(entry.link[0].rel, 'related') self.assertEquals(entry.content.text, 'test66') class YouTubeVideoSubscriptionFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeSubscriptionFeedFromString( test_data.YOUTUBE_SUBSCRIPTION_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.category), 1) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#subscription') self.assertEquals(len(self.feed.link), 4) self.assertEquals(self.feed.link[0].rel, 'related') self.assertEquals(self.feed.link[0].href, 'http://gdata.youtube.com/feeds/users/andyland74') self.assertEquals(self.feed.link[1].rel, 'alternate') self.assertEquals(self.feed.link[1].href, 'http://www.youtube.com/profile_subscriptions?user=andyland74') self.assertEquals(self.feed.link[2].rel, 'http://schemas.google.com/g/2005#feed') self.assertEquals(self.feed.link[2].href, 'http://gdata.youtube.com/feeds/users/andyland74/subscriptions') self.assertEquals(self.feed.link[3].rel, 'self') self.assertEquals(self.feed.link[3].href, ('http://gdata.youtube.com/feeds/users/andyland74/subscriptions?' 'start-index=1&max-results=25')) self.assertEquals(len(self.feed.entry), 1) class YouTubeVideoSubscriptionEntryTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeSubscriptionFeedFromString( test_data.YOUTUBE_SUBSCRIPTION_FEED) def testCorrectXmlParsing(self): for entry in self.feed.entry: self.assertEquals(len(entry.category), 2) self.assertEquals(entry.category[0].scheme, 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat') self.assertEquals(entry.category[0].term, 'channel') self.assertEquals(entry.category[1].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(entry.category[1].term, 'http://gdata.youtube.com/schemas/2007#subscription') self.assertEquals(len(entry.link), 3) self.assertEquals(entry.link[0].href, 'http://gdata.youtube.com/feeds/users/andyland74') self.assertEquals(entry.link[0].rel, 'related') self.assertEquals(entry.link[1].href, 'http://www.youtube.com/profile_videos?user=NBC') self.assertEquals(entry.link[1].rel, 'alternate') self.assertEquals(entry.link[2].href, ('http://gdata.youtube.com/feeds/users/andyland74/subscriptions/' 'd411759045e2ad8c')) self.assertEquals(entry.link[2].rel, 'self') self.assertEquals(len(entry.feed_link), 1) self.assertEquals(entry.feed_link[0].href, 'http://gdata.youtube.com/feeds/api/users/nbc/uploads') self.assertEquals(entry.feed_link[0].rel, 'http://gdata.youtube.com/schemas/2007#user.uploads') self.assertEquals(entry.username.text, 'NBC') class YouTubeVideoResponseFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeVideoFeedFromString( test_data.YOUTUBE_VIDEO_RESPONSE_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.category), 1) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#video') self.assertEquals(len(self.feed.link), 4) self.assertEquals(self.feed.link[0].href, 'http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY') self.assertEquals(self.feed.link[0].rel, 'related') self.assertEquals(self.feed.link[1].href, 'http://www.youtube.com/video_response_view_all?v=2c3q9K4cHzY') self.assertEquals(self.feed.link[1].rel, 'alternate') self.assertEquals(self.feed.link[2].href, 'http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses') self.assertEquals(self.feed.link[2].rel, 'http://schemas.google.com/g/2005#feed') self.assertEquals(self.feed.link[3].href, ('http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses?' 'start-index=1&max-results=25')) self.assertEquals(self.feed.link[3].rel, 'self') self.assertEquals(len(self.feed.entry), 1) class YouTubeVideoResponseEntryTest(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeVideoFeedFromString( test_data.YOUTUBE_VIDEO_RESPONSE_FEED) def testCorrectXmlParsing(self): for entry in self.feed.entry: self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry)) class YouTubeContactFeed(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeContactFeedFromString( test_data.YOUTUBE_CONTACTS_FEED) def testCorrectXmlParsing(self): self.assertEquals(len(self.feed.entry), 2) self.assertEquals(self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[0].term, 'http://gdata.youtube.com/schemas/2007#friend') class YouTubeContactEntry(unittest.TestCase): def setUp(self): self.feed= gdata.youtube.YouTubeContactFeedFromString( test_data.YOUTUBE_CONTACTS_FEED) def testCorrectXmlParsing(self): for entry in self.feed.entry: if (entry.id.text == ('http://gdata.youtube.com/feeds/users/' 'apitestjhartmann/contacts/testjfisher')): self.assertEquals(entry.username.text, 'testjfisher') self.assertEquals(entry.status.text, 'pending') class YouTubeUserEntry(unittest.TestCase): def setUp(self): self.feed = gdata.youtube.YouTubeUserEntryFromString( test_data.YOUTUBE_PROFILE) def testCorrectXmlParsing(self): self.assertEquals(self.feed.author[0].name.text, 'andyland74') self.assertEquals(self.feed.books.text, 'Catch-22') self.assertEquals(self.feed.category[0].scheme, 'http://gdata.youtube.com/schemas/2007/channeltypes.cat') self.assertEquals(self.feed.category[0].term, 'Standard') self.assertEquals(self.feed.category[1].scheme, 'http://schemas.google.com/g/2005#kind') self.assertEquals(self.feed.category[1].term, 'http://gdata.youtube.com/schemas/2007#userProfile') self.assertEquals(self.feed.company.text, 'Google') self.assertEquals(self.feed.gender.text, 'm') self.assertEquals(self.feed.hobbies.text, 'Testing YouTube APIs') self.assertEquals(self.feed.hometown.text, 'Somewhere') self.assertEquals(len(self.feed.feed_link), 6) self.assertEquals(self.feed.feed_link[0].count_hint, '4') self.assertEquals(self.feed.feed_link[0].href, 'http://gdata.youtube.com/feeds/users/andyland74/favorites') self.assertEquals(self.feed.feed_link[0].rel, 'http://gdata.youtube.com/schemas/2007#user.favorites') self.assertEquals(self.feed.feed_link[1].count_hint, '1') self.assertEquals(self.feed.feed_link[1].href, 'http://gdata.youtube.com/feeds/users/andyland74/contacts') self.assertEquals(self.feed.feed_link[1].rel, 'http://gdata.youtube.com/schemas/2007#user.contacts') self.assertEquals(self.feed.feed_link[2].count_hint, '0') self.assertEquals(self.feed.feed_link[2].href, 'http://gdata.youtube.com/feeds/users/andyland74/inbox') self.assertEquals(self.feed.feed_link[2].rel, 'http://gdata.youtube.com/schemas/2007#user.inbox') self.assertEquals(self.feed.feed_link[3].count_hint, None) self.assertEquals(self.feed.feed_link[3].href, 'http://gdata.youtube.com/feeds/users/andyland74/playlists') self.assertEquals(self.feed.feed_link[3].rel, 'http://gdata.youtube.com/schemas/2007#user.playlists') self.assertEquals(self.feed.feed_link[4].count_hint, '4') self.assertEquals(self.feed.feed_link[4].href, 'http://gdata.youtube.com/feeds/users/andyland74/subscriptions') self.assertEquals(self.feed.feed_link[4].rel, 'http://gdata.youtube.com/schemas/2007#user.subscriptions') self.assertEquals(self.feed.feed_link[5].count_hint, '1') self.assertEquals(self.feed.feed_link[5].href, 'http://gdata.youtube.com/feeds/users/andyland74/uploads') self.assertEquals(self.feed.feed_link[5].rel, 'http://gdata.youtube.com/schemas/2007#user.uploads') self.assertEquals(self.feed.first_name.text, 'andy') self.assertEquals(self.feed.last_name.text, 'example') self.assertEquals(self.feed.link[0].href, 'http://www.youtube.com/profile?user=andyland74') self.assertEquals(self.feed.link[0].rel, 'alternate') self.assertEquals(self.feed.link[1].href, 'http://gdata.youtube.com/feeds/users/andyland74') self.assertEquals(self.feed.link[1].rel, 'self') self.assertEquals(self.feed.location.text, 'US') self.assertEquals(self.feed.movies.text, 'Aqua Teen Hungerforce') self.assertEquals(self.feed.music.text, 'Elliott Smith') self.assertEquals(self.feed.occupation.text, 'Technical Writer') self.assertEquals(self.feed.published.text, '2006-10-16T00:09:45.000-07:00') self.assertEquals(self.feed.school.text, 'University of North Carolina') self.assertEquals(self.feed.statistics.last_web_access, '2008-02-25T16:03:38.000-08:00') self.assertEquals(self.feed.statistics.subscriber_count, '1') self.assertEquals(self.feed.statistics.video_watch_count, '21') self.assertEquals(self.feed.statistics.view_count, '9') self.assertEquals(self.feed.thumbnail.url, 'http://i.ytimg.com/vi/YFbSxcdOL-w/default.jpg') self.assertEquals(self.feed.title.text, 'andyland74 Channel') self.assertEquals(self.feed.updated.text, '2008-02-26T11:48:21.000-08:00') self.assertEquals(self.feed.username.text, 'andyland74') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'j.s@google.com (Jeff Scudder)' import os import unittest import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data import gdata.core # TODO: switch to using v2 atom data once it is available. import atom import gdata.test_config as conf conf.options.register_option(conf.BLOG_ID_OPTION) class BloggerTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.client.GDClient() conf.configure_client(self.client, 'BloggerTest', 'blogger') def tearDown(self): conf.close_client(self.client) def test_create_update_delete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') blog_post = atom.Entry( title=atom.Title(text='test from python BloggerTest'), content=atom.Content(text='This is only a test.')) http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(blog_post), 'application/atom+xml') def entry_from_string_wrapper(response): self.assert_(response.getheader('content-type') is not None) self.assert_(response.getheader('gdata-version') is not None) return atom.EntryFromString(response.read()) entry = self.client.request('POST', 'http://www.blogger.com/feeds/%s/posts/default' % ( conf.options.get_value('blogid')), converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(entry.title.text, 'test from python BloggerTest') self.assertEqual(entry.content.text, 'This is only a test.') # Edit the test entry. edit_link = None for link in entry.link: # Find the edit link for this entry. if link.rel == 'edit': edit_link = link.href entry.title.text = 'Edited' http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(entry), 'application/atom+xml') edited_entry = self.client.request('PUT', edit_link, converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(edited_entry.title.text, 'Edited') self.assertEqual(edited_entry.content.text, entry.content.text) # Delete the test entry from the blog. edit_link = None for link in edited_entry.link: if link.rel == 'edit': edit_link = link.href response = self.client.request('DELETE', edit_link) self.assertEqual(response.status, 200) def test_use_version_two(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_use_version_two') # Use version 2 of the Blogger API. self.client.api_version = '2' # Create a v2 blog post entry to post on the blog. entry = create_element('entry') entry._other_elements.append( create_element('title', text='Marriage!', attributes={'type': 'text'})) entry._other_elements.append( create_element('content', attributes={'type': 'text'}, text='Mr. Darcy has proposed marriage to me!')) entry._other_elements.append( create_element('category', attributes={'scheme': TAG, 'term': 'marriage'})) entry._other_elements.append( create_element('category', attributes={'scheme': TAG, 'term': 'Mr. Darcy'})) http_request = atom.http_core.HttpRequest() http_request.add_body_part(entry.to_string(), 'application/atom+xml') posted = self.client.request('POST', 'http://www.blogger.com/feeds/%s/posts/default' % ( conf.options.get_value('blogid')), converter=element_from_string, http_request=http_request) # Verify that the blog post content is correct. self.assertEqual(posted.get_elements('title', ATOM)[0].text, 'Marriage!') # TODO: uncomment once server bug is fixed. #self.assertEqual(posted.get_elements('content', ATOM)[0].text, # 'Mr. Darcy has proposed marriage to me!') found_tags = [False, False] categories = posted.get_elements('category', ATOM) self.assertEqual(len(categories), 2) for category in categories: if category.get_attributes('term')[0].value == 'marriage': found_tags[0] = True elif category.get_attributes('term')[0].value == 'Mr. Darcy': found_tags[1] = True self.assert_(found_tags[0]) self.assert_(found_tags[1]) # Find the blog post on the blog. self_link = None edit_link = None for link in posted.get_elements('link', ATOM): if link.get_attributes('rel')[0].value == 'self': self_link = link.get_attributes('href')[0].value elif link.get_attributes('rel')[0].value == 'edit': edit_link = link.get_attributes('href')[0].value self.assert_(self_link is not None) self.assert_(edit_link is not None) queried = self.client.request('GET', self_link, converter=element_from_string) # TODO: add additional asserts to check content and etags. # Test queries using ETags. entry = self.client.get_entry(self_link) self.assert_(entry.etag is not None) self.assertRaises(gdata.client.NotModified, self.client.get_entry, self_link, etag=entry.etag) # Delete the test blog post. self.client.request('DELETE', edit_link) class ContactsTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.client.GDClient() conf.configure_client(self.client, 'ContactsTest', 'cp') def tearDown(self): conf.close_client(self.client) # Run this test and profiles fails def test_crud_version_two(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_crud_version_two') self.client.api_version = '2' entry = create_element('entry') entry._other_elements.append( create_element('title', ATOM, 'Jeff', {'type': 'text'})) entry._other_elements.append( create_element('email', GD, attributes={'address': 'j.s@google.com', 'rel': WORK_REL})) http_request = atom.http_core.HttpRequest() http_request.add_body_part(entry.to_string(), 'application/atom+xml') posted = self.client.request('POST', 'http://www.google.com/m8/feeds/contacts/default/full', converter=element_from_string, http_request=http_request) self_link = None edit_link = None for link in posted.get_elements('link', ATOM): if link.get_attributes('rel')[0].value == 'self': self_link = link.get_attributes('href')[0].value elif link.get_attributes('rel')[0].value == 'edit': edit_link = link.get_attributes('href')[0].value self.assert_(self_link is not None) self.assert_(edit_link is not None) etag = posted.get_attributes('etag')[0].value self.assert_(etag is not None) self.assert_(len(etag) > 0) # Delete the test contact. http_request = atom.http_core.HttpRequest() http_request.headers['If-Match'] = etag self.client.request('DELETE', edit_link, http_request=http_request) class VersionTwoClientContactsTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.client.GDClient() self.client.api_version = '2' conf.configure_client(self.client, 'VersionTwoClientContactsTest', 'cp') self.old_proxy = os.environ.get('https_proxy') def tearDown(self): if self.old_proxy: os.environ['https_proxy'] = self.old_proxy elif 'https_proxy' in os.environ: del os.environ['https_proxy'] conf.close_client(self.client) def test_version_two_client(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'test_version_two_client') entry = gdata.data.GDEntry() entry._other_elements.append( create_element('title', ATOM, 'Test', {'type': 'text'})) entry._other_elements.append( create_element('email', GD, attributes={'address': 'test@example.com', 'rel': WORK_REL})) # Create the test contact. posted = self.client.post(entry, 'https://www.google.com/m8/feeds/contacts/default/full') self.assert_(isinstance(posted, gdata.data.GDEntry)) self.assertEqual(posted.get_elements('title')[0].text, 'Test') self.assertEqual(posted.get_elements('email')[0].get_attributes( 'address')[0].value, 'test@example.com') posted.get_elements('title')[0].text = 'Doug' edited = self.client.update(posted) self.assert_(isinstance(edited, gdata.data.GDEntry)) self.assertEqual(edited.get_elements('title')[0].text, 'Doug') self.assertEqual(edited.get_elements('email')[0].get_attributes( 'address')[0].value, 'test@example.com') # Delete the test contact. self.client.delete(edited) def notest_crud_over_https_proxy(self): import urllib PROXY_ADDR = '98.192.125.23' try: response = urllib.urlopen('http://' + PROXY_ADDR) except IOError: return # Only bother running the test if the proxy is up if response.getcode() == 200: os.environ['https_proxy'] = PROXY_ADDR # Perform the CRUD test above, this time over a proxy. self.test_version_two_client() class JsoncRequestTest(unittest.TestCase): def setUp(self): self.client = gdata.client.GDClient() def test_get_jsonc(self): jsonc = self.client.get_feed( 'http://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc', converter=gdata.core.parse_json_file) self.assertTrue(len(jsonc.data.items) > 0) # Utility methods. # The Atom XML namespace. ATOM = 'http://www.w3.org/2005/Atom' # URL used as the scheme for a blog post tag. TAG = 'http://www.blogger.com/atom/ns#' # Namespace for Google Data API elements. GD = 'http://schemas.google.com/g/2005' WORK_REL = 'http://schemas.google.com/g/2005#work' def create_element(tag, namespace=ATOM, text=None, attributes=None): element = atom.core.XmlElement() element._qname = '{%s}%s' % (namespace, tag) if text is not None: element.text = text if attributes is not None: element._other_attributes = attributes.copy() return element def element_from_string(response): return atom.core.xml_element_from_string(response.read(), atom.core.XmlElement) def suite(): return conf.build_suite([BloggerTest, ContactsTest, VersionTwoClientContactsTest, JsoncRequestTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit Tests for Google Analytics API query objects. AnalyticsClientTest: Tests making live requests to Google Analytics API. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import unittest from gdata.analytics import client class DataExportQueryTest(unittest.TestCase): """Tests making Data Export API Queries.""" def testAccountFeed(self): """Tests Account Feed queries.""" queryTest1 = client.AccountFeedQuery() self.assertEquals(str(queryTest1), 'https://www.google.com/analytics/feeds/accounts/default') queryTest2 = client.AccountFeedQuery({'max-results': 50}) self.assertEquals(str(queryTest2), 'https://www.google.com/analytics/feeds/accounts/default' '?max-results=50') queryTest3 = client.AccountFeedQuery() queryTest3.query['max-results'] = 100 self.assertEquals(str(queryTest3), 'https://www.google.com/analytics/feeds/accounts/default' '?max-results=100') def testDataFeed(self): """Tests Data Feed queries.""" queryTest1 = client.DataFeedQuery() self.assertEquals(str(queryTest1), 'https://www.google.com/analytics/feeds/data') queryTest2 = client.DataFeedQuery({'ids': 'ga:1234'}) self.assertEquals(str(queryTest2), 'https://www.google.com/analytics/feeds/data?ids=ga%3A1234') queryTest3 = client.DataFeedQuery() queryTest3.query['ids'] = 'ga:1234' self.assertEquals(str(queryTest3), 'https://www.google.com/analytics/feeds/data?ids=ga%3A1234') class ManagementQueryTest(unittest.TestCase): """Tests making Management API queries.""" def setUp(self): self.base_url = 'https://www.google.com/analytics/feeds/datasources/ga' def testAccountFeedQuery(self): """Tests Account Feed queries.""" queryTest1 = client.AccountQuery() self.assertEquals(str(queryTest1), '%s/accounts' % self.base_url) queryTest2 = client.AccountQuery({'max-results': 50}) self.assertEquals(str(queryTest2), '%s/accounts?max-results=50' % self.base_url) def testWebPropertyFeedQuery(self): """Tests Web Property Feed queries.""" queryTest1 = client.WebPropertyQuery() self.assertEquals(str(queryTest1), '%s/accounts/~all/webproperties' % self.base_url) queryTest2 = client.WebPropertyQuery('123') self.assertEquals(str(queryTest2), '%s/accounts/123/webproperties' % self.base_url) queryTest3 = client.WebPropertyQuery('123', {'max-results': 100}) self.assertEquals(str(queryTest3), '%s/accounts/123/webproperties?max-results=100' % self.base_url) def testProfileFeedQuery(self): """Tests Profile Feed queries.""" queryTest1 = client.ProfileQuery() self.assertEquals(str(queryTest1), '%s/accounts/~all/webproperties/~all/profiles' % self.base_url) queryTest2 = client.ProfileQuery('123', 'UA-123-1') self.assertEquals(str(queryTest2), '%s/accounts/123/webproperties/UA-123-1/profiles' % self.base_url) queryTest3 = client.ProfileQuery('123', 'UA-123-1', {'max-results': 100}) self.assertEquals(str(queryTest3), '%s/accounts/123/webproperties/UA-123-1/profiles?max-results=100' % self.base_url) queryTest4 = client.ProfileQuery() queryTest4.acct_id = '123' queryTest4.web_prop_id = 'UA-123-1' queryTest4.query['max-results'] = 100 self.assertEquals(str(queryTest4), '%s/accounts/123/webproperties/UA-123-1/profiles?max-results=100' % self.base_url) def testGoalFeedQuery(self): """Tests Goal Feed queries.""" queryTest1 = client.GoalQuery() self.assertEquals(str(queryTest1), '%s/accounts/~all/webproperties/~all/profiles/~all/goals' % self.base_url) queryTest2 = client.GoalQuery('123', 'UA-123-1', '555') self.assertEquals(str(queryTest2), '%s/accounts/123/webproperties/UA-123-1/profiles/555/goals' % self.base_url) queryTest3 = client.GoalQuery('123', 'UA-123-1', '555', {'max-results': 100}) self.assertEquals(str(queryTest3), '%s/accounts/123/webproperties/UA-123-1/profiles/555/goals' '?max-results=100' % self.base_url) queryTest4 = client.GoalQuery() queryTest4.acct_id = '123' queryTest4.web_prop_id = 'UA-123-1' queryTest4.profile_id = '555' queryTest4.query['max-results'] = 100 self.assertEquals(str(queryTest3), '%s/accounts/123/webproperties/UA-123-1/profiles/555/goals' '?max-results=100' % self.base_url) def testAdvSegQuery(self): """Tests Advanced Segment Feed queries.""" queryTest1 = client.AdvSegQuery() self.assertEquals(str(queryTest1), '%s/segments' % self.base_url) queryTest2 = client.AdvSegQuery({'max-results': 100}) self.assertEquals(str(queryTest2), '%s/segments?max-results=100' % self.base_url) def suite(): return conf.build_suite([DataExportQueryTest, ManagementQueryTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit Tests for Google Analytics Data Export API and Management APIs. Although the Data Export API and Management API conceptually operate on different parts of Google Analytics, the APIs share some code so they are released in the same module. AccountFeedTest: All unit tests for AccountFeed class. DataFeedTest: All unit tests for DataFeed class. ManagementFeedAccountTest: Unit tests for ManagementFeed class. ManagementFeedGoalTest: Unit tests for ManagementFeed class. ManagementFeedAdvSegTest: Unit tests for ManagementFeed class. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import unittest from gdata import test_data import gdata.analytics.data import atom.core import gdata.test_config as conf class AccountFeedTest(unittest.TestCase): """Unit test for all custom elements in the Account Feed.""" def setUp(self): """Retrieves the test XML feed into a AccountFeed object.""" self.feed = atom.core.parse(test_data.ANALYTICS_ACCOUNT_FEED, gdata.analytics.data.AccountFeed) def testSegment(self): """Tests Segment class in Google Analytics Account Feed.""" segment = self.feed.segment[0] self.assertEquals(segment.id, 'gaid::-11') self.assertEquals(segment.name, 'Visits from iPhones') def testSegmentDefinition(self): """Tests Definition class in Google Analytics Account Feed.""" definition = self.feed.segment[0].definition self.assertEquals(definition.text, 'ga:operatingSystem==iPhone') def testEntryTableId(self): """Tests custom classes in Google Analytics Account Feed.""" entry = self.feed.entry[0] self.assertEquals(entry.table_id.text, 'ga:1174') def testEntryProperty(self): """Tests the property classes in Google Analytics Account Feed.""" property = self.feed.entry[0].property self.assertEquals(property[0].name, 'ga:accountId') self.assertEquals(property[0].value, '30481') self.assertEquals(property[1].name, 'ga:accountName') self.assertEquals(property[1].value, 'Google Store') self.assertEquals(property[2].name, 'ga:profileId') self.assertEquals(property[2].value, '1174') self.assertEquals(property[3].name, 'ga:webPropertyId') self.assertEquals(property[3].value, 'UA-30481-1') self.assertEquals(property[4].name, 'ga:currency') self.assertEquals(property[4].value, 'USD') self.assertEquals(property[5].name, 'ga:timezone') self.assertEquals(property[5].value, 'America/Los_Angeles') def testEntryGetProperty(self): """Tests GetProperty inherited class in the AccountEntry class.""" entry = self.feed.entry[0] self.assertEquals(entry.GetProperty('ga:accountId').value, '30481') self.assertEquals(entry.GetProperty('ga:accountName').value, 'Google Store') self.assertEquals(entry.GetProperty('ga:profileId').value, '1174') self.assertEquals(entry.GetProperty('ga:webPropertyId').value, 'UA-30481-1') self.assertEquals(entry.GetProperty('ga:currency').value, 'USD') self.assertEquals(entry.GetProperty('ga:timezone').value, 'America/Los_Angeles') def testGoal(self): """Tests Goal class in Google Anlaytics Account Feed.""" goal = self.feed.entry[0].goal[0] self.assertEquals(goal.number, '1') self.assertEquals(goal.name, 'Completing Order') self.assertEquals(goal.value, '10.0') self.assertEquals(goal.active, 'true') def testDestination(self): """Tests Destination class in Google Analytics Account Feed.""" destination = self.feed.entry[0].goal[0].destination self.assertEquals(destination.expression, '/purchaseComplete.html') self.assertEquals(destination.case_sensitive, 'false') self.assertEquals(destination.match_type, 'regex') self.assertEquals(destination.step1_required, 'false') def testStep(self): """Tests Step class in Google Analytics Account Feed.""" step = self.feed.entry[0].goal[0].destination.step[0] self.assertEquals(step.number, '1') self.assertEquals(step.name, 'View Product Categories') self.assertEquals(step.path, '/Apps|Accessories|Fun|Kid\+s|Office') def testEngagemet(self): """Tests Engagement class in Google Analytics Account Feed.""" engagement = self.feed.entry[0].goal[1].engagement self.assertEquals(engagement.type, 'timeOnSite') self.assertEquals(engagement.comparison, '>') self.assertEquals(engagement.threshold_value, '300') def testCustomVariable(self): """Tests CustomVariable class in Google Analytics Account Feed.""" customVar = self.feed.entry[0].custom_variable[0] self.assertEquals(customVar.index, '1') self.assertEquals(customVar.name, 'My Custom Variable') self.assertEquals(customVar.scope, '3') class DataFeedTest(unittest.TestCase): """Unit test for all custom elements in the Data Feed.""" def setUp(self): """Retrieves the test XML feed into a DataFeed object.""" self.feed = atom.core.parse(test_data.ANALYTICS_DATA_FEED, gdata.analytics.data.DataFeed) def testDataFeed(self): """Tests custom classes in Google Analytics Data Feed.""" self.assertEquals(self.feed.start_date.text, '2008-10-01') self.assertEquals(self.feed.end_date.text, '2008-10-31') def testAggregates(self): """Tests Aggregates class in Google Analytics Data Feed.""" self.assert_(self.feed.aggregates is not None) def testContainsSampledData(self): """Tests ContainsSampledData class in Google Analytics Data Feed.""" contains_sampled_data = self.feed.contains_sampled_data.text self.assertEquals(contains_sampled_data, 'true') self.assertTrue(self.feed.HasSampledData()) def testAggregatesElements(self): """Tests Metrics class in Aggregates class.""" metric = self.feed.aggregates.metric[0] self.assertEquals(metric.confidence_interval, '0.0') self.assertEquals(metric.name, 'ga:visits') self.assertEquals(metric.type, 'integer') self.assertEquals(metric.value, '136540') metric = self.feed.aggregates.GetMetric('ga:visits') self.assertEquals(metric.confidence_interval, '0.0') self.assertEquals(metric.name, 'ga:visits') self.assertEquals(metric.type, 'integer') self.assertEquals(metric.value, '136540') def testDataSource(self): """Tests DataSources class in Google Analytics Data Feed.""" self.assert_(self.feed.data_source[0] is not None) def testDataSourceTableId(self): """Tests TableId class in the DataSource class.""" table_id = self.feed.data_source[0].table_id self.assertEquals(table_id.text, 'ga:1174') def testDataSourceTableName(self): """Tests TableName class in the DataSource class.""" table_name = self.feed.data_source[0].table_name self.assertEquals(table_name.text, 'www.googlestore.com') def testDataSourceProperty(self): """Tests Property class in the DataSource class.""" property = self.feed.data_source[0].property self.assertEquals(property[0].name, 'ga:profileId') self.assertEquals(property[0].value, '1174') self.assertEquals(property[1].name, 'ga:webPropertyId') self.assertEquals(property[1].value, 'UA-30481-1') self.assertEquals(property[2].name, 'ga:accountName') self.assertEquals(property[2].value, 'Google Store') def testDataSourceGetProperty(self): """Tests GetProperty utility method in the DataSource class.""" ds = self.feed.data_source[0] self.assertEquals(ds.GetProperty('ga:profileId').value, '1174') self.assertEquals(ds.GetProperty('ga:webPropertyId').value, 'UA-30481-1') self.assertEquals(ds.GetProperty('ga:accountName').value, 'Google Store') def testSegment(self): """Tests Segment class in DataFeed class.""" segment = self.feed.segment self.assertEquals(segment.id, 'gaid::-11') self.assertEquals(segment.name, 'Visits from iPhones') def testSegmentDefinition(self): """Tests Definition class in Segment class.""" definition = self.feed.segment.definition self.assertEquals(definition.text, 'ga:operatingSystem==iPhone') def testEntryDimension(self): """Tests Dimension class in Entry class.""" dim = self.feed.entry[0].dimension[0] self.assertEquals(dim.name, 'ga:source') self.assertEquals(dim.value, 'blogger.com') def testEntryGetDimension(self): """Tests GetDimension utility method in the Entry class.""" dim = self.feed.entry[0].GetDimension('ga:source') self.assertEquals(dim.name, 'ga:source') self.assertEquals(dim.value, 'blogger.com') error = self.feed.entry[0].GetDimension('foo') self.assertEquals(error, None) def testEntryMetric(self): """Tests Metric class in Entry class.""" met = self.feed.entry[0].metric[0] self.assertEquals(met.confidence_interval, '0.0') self.assertEquals(met.name, 'ga:visits') self.assertEquals(met.type, 'integer') self.assertEquals(met.value, '68140') def testEntryGetMetric(self): """Tests GetMetric utility method in the Entry class.""" met = self.feed.entry[0].GetMetric('ga:visits') self.assertEquals(met.confidence_interval, '0.0') self.assertEquals(met.name, 'ga:visits') self.assertEquals(met.type, 'integer') self.assertEquals(met.value, '68140') error = self.feed.entry[0].GetMetric('foo') self.assertEquals(error, None) def testEntryGetObject(self): """Tests GetObjectOf utility method in Entry class.""" entry = self.feed.entry[0] dimension = entry.GetObject('ga:source') self.assertEquals(dimension.name, 'ga:source') self.assertEquals(dimension.value, 'blogger.com') metric = entry.GetObject('ga:visits') self.assertEquals(metric.name, 'ga:visits') self.assertEquals(metric.value, '68140') self.assertEquals(metric.type, 'integer') self.assertEquals(metric.confidence_interval, '0.0') error = entry.GetObject('foo') self.assertEquals(error, None) class ManagementFeedProfileTest(unittest.TestCase): """Unit test for all property elements in Google Analytics Management Feed. Since the Account, Web Property and Profile feed all have the same structure and XML elements, this single test case covers all three feeds. """ def setUp(self): """Retrieves the test XML feed into a DataFeed object.""" self.feed = atom.core.parse(test_data.ANALYTICS_MGMT_PROFILE_FEED, gdata.analytics.data.ManagementFeed) def testFeedKindAttribute(self): """Tests the kind attribute in the feed.""" self.assertEqual(self.feed.kind, 'analytics#profiles') def testEntryKindAttribute(self): """tests the kind attribute in the entry.""" entry_kind = self.feed.entry[0].kind self.assertEqual(entry_kind, 'analytics#profile') def testEntryProperty(self): """Tests property classes in Managment Entry class.""" property = self.feed.entry[0].property self.assertEquals(property[0].name, 'ga:accountId') self.assertEquals(property[0].value, '30481') def testEntryGetProperty(self): """Tests GetProperty helper method in Management Entry class.""" entry = self.feed.entry[0] self.assertEquals(entry.GetProperty('ga:accountId').value, '30481') def testGetParentLinks(self): """Tests GetParentLinks utility method.""" parent_links = self.feed.entry[0].GetParentLinks() self.assertEquals(len(parent_links), 1) parent_link = parent_links[0] self.assertEquals(parent_link.rel, 'http://schemas.google.com/ga/2009#parent') self.assertEquals(parent_link.type, 'application/atom+xml') self.assertEquals(parent_link.href, 'https://www.google.com/analytics/feeds/datasources' '/ga/accounts/30481/webproperties/UA-30481-1') self.assertEquals(parent_link.target_kind, 'analytics#webproperty') def testGetChildLinks(self): """Tests GetChildLinks utility method.""" child_links = self.feed.entry[0].GetChildLinks() self.assertEquals(len(child_links), 1) self.ChildLinkTestHelper(child_links[0]) def testGetChildLink(self): """Tests getChildLink utility method.""" child_link = self.feed.entry[0].GetChildLink('analytics#goals') self.ChildLinkTestHelper(child_link) child_link = self.feed.entry[0].GetChildLink('foo_bar') self.assertEquals(child_link, None) def ChildLinkTestHelper(self, child_link): """Common method to test a child link.""" self.assertEquals(child_link.rel, 'http://schemas.google.com/ga/2009#child') self.assertEquals(child_link.type, 'application/atom+xml') self.assertEquals(child_link.href, 'https://www.google.com/analytics/feeds/datasources' '/ga/accounts/30481/webproperties/UA-30481-1/profiles/1174/goals') self.assertEquals(child_link.target_kind, 'analytics#goals') class ManagementFeedGoalTest(unittest.TestCase): """Unit test for all Goal elements in Management Feed.""" def setUp(self): """Retrieves the test XML feed into a DataFeed object.""" self.feed = atom.core.parse(test_data.ANALYTICS_MGMT_GOAL_FEED, gdata.analytics.data.ManagementFeed) def testEntryGoal(self): """Tests Goal class in Google Anlaytics Account Feed.""" goal = self.feed.entry[0].goal self.assertEquals(goal.number, '1') self.assertEquals(goal.name, 'Completing Order') self.assertEquals(goal.value, '10.0') self.assertEquals(goal.active, 'true') def testGoalDestination(self): """Tests Destination class in Google Analytics Account Feed.""" destination = self.feed.entry[0].goal.destination self.assertEquals(destination.expression, '/purchaseComplete.html') self.assertEquals(destination.case_sensitive, 'false') self.assertEquals(destination.match_type, 'regex') self.assertEquals(destination.step1_required, 'false') def testGoalDestinationStep(self): """Tests Step class in Google Analytics Account Feed.""" step = self.feed.entry[0].goal.destination.step[0] self.assertEquals(step.number, '1') self.assertEquals(step.name, 'View Product Categories') self.assertEquals(step.path, '/Apps|Accessories') def testGoalEngagemet(self): """Tests Engagement class in Google Analytics Account Feed.""" engagement = self.feed.entry[1].goal.engagement self.assertEquals(engagement.type, 'timeOnSite') self.assertEquals(engagement.comparison, '>') self.assertEquals(engagement.threshold_value, '300') class ManagementFeedAdvSegTest(unittest.TestCase): """Unit test for all Advanced Segment elements in Management Feed.""" def setUp(self): """Retrieves the test XML feed into a DataFeed object.""" self.feed = atom.core.parse(test_data.ANALYTICS_MGMT_ADV_SEGMENT_FEED, gdata.analytics.data.ManagementFeed) def testEntrySegment(self): """Tests Segment class in ManagementEntry class.""" segment = self.feed.entry[0].segment self.assertEquals(segment.id, 'gaid::0') self.assertEquals(segment.name, 'Sources Form Google') def testSegmentDefinition(self): """Tests Definition class in Segment class.""" definition = self.feed.entry[0].segment.definition self.assertEquals(definition.text, 'ga:source=~^\Qgoogle\E') def suite(): """Test Account Feed, Data Feed and Management API Feeds.""" return conf.build_suite([ AccountFeedTest, DataFeedTest, ManagementFeedProfileTest, ManagementFeedGoalTest, ManagementFeedAdvSegTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional Tests for Google Analytics Account Feed and Data Feed. AnalyticsClientTest: Tests making live requests to Google Analytics API. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import unittest import gdata.client import gdata.data import gdata.gauth import gdata.analytics.client import gdata.test_config as conf conf.options.register_option(conf.GA_TABLE_ID) class AnalyticsClientTest(unittest.TestCase): """Tests creating an Account Feed query and making a request to the Google Analytics Account Feed.""" def setUp(self): """Creates an AnalyticsClient object.""" self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.analytics.client.AnalyticsClient() self.client.http_client.debug = True conf.configure_client( self.client, 'AnalyticsClientTest', self.client.auth_service) def testAccountFeed(self): """Tests if the Account Feed exists.""" if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'testAccountFeed') account_query = gdata.analytics.client.AccountFeedQuery({ 'max-results': '1' }) feed = self.client.GetAccountFeed(account_query) self.assert_(feed.entry is not None) properties = [ 'ga:accountId', 'ga:accountName', 'ga:profileId', 'ga:webPropertyId', 'ga:currency', 'ga:timezone' ] entry = feed.entry[0] for prop in properties: property = entry.GetProperty(prop) self.assertEquals(property.name, prop) def testDataFeed(self): """Tests if the Data Feed exists.""" start_date = '2008-10-01' end_date = '2008-10-02' metrics = 'ga:visits' if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'testDataFeed') data_query = gdata.analytics.client.DataFeedQuery({ 'ids': conf.options.get_value('table_id'), 'start-date': start_date, 'end-date': end_date, 'metrics' : metrics, 'max-results': '1' }) feed = self.client.GetDataFeed(data_query) self.assert_(feed.entry is not None) self.assertEquals(feed.start_date.text, start_date) self.assertEquals(feed.end_date.text, end_date) self.assertEquals(feed.entry[0].GetMetric(metrics).name, metrics) def testManagementFeed(self): """Tests of the Management Feed exists.""" if not conf.options.get_value('runlive') == 'true': return conf.configure_cache(self.client, 'testManagementFeed') account_query = gdata.analytics.client.AccountQuery() feed = self.client.GetManagementFeed(account_query) self.assert_(feed.entry is not None) def tearDown(self): """Closes client connection.""" conf.close_client(self.client) def suite(): return conf.build_suite([AnalyticsClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'livibetter (Yu-Jie Lin)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata from gdata import test_data import gdata.webmastertools as webmastertools class IndexedTest(unittest.TestCase): def setUp(self): self.indexed = webmastertools.Indexed() def testToAndFromString(self): self.indexed.text = 'true' self.assert_(self.indexed.text == 'true') new_indexed = webmastertools.IndexedFromString(self.indexed.ToString()) self.assert_(self.indexed.text == new_indexed.text) class CrawledTest(unittest.TestCase): def setUp(self): self.crawled = webmastertools.Crawled() def testToAndFromString(self): self.crawled.text = 'true' self.assert_(self.crawled.text == 'true') new_crawled = webmastertools.CrawledFromString(self.crawled.ToString()) self.assert_(self.crawled.text == new_crawled.text) class GeoLocationTest(unittest.TestCase): def setUp(self): self.geolocation = webmastertools.GeoLocation() def testToAndFromString(self): self.geolocation.text = 'US' self.assert_(self.geolocation.text == 'US') new_geolocation = webmastertools.GeoLocationFromString( self.geolocation.ToString()) self.assert_(self.geolocation.text == new_geolocation.text) class PreferredDomainTest(unittest.TestCase): def setUp(self): self.preferred_domain = webmastertools.PreferredDomain() def testToAndFromString(self): self.preferred_domain.text = 'none' self.assert_(self.preferred_domain.text == 'none') new_preferred_domain = webmastertools.PreferredDomainFromString( self.preferred_domain.ToString()) self.assert_(self.preferred_domain.text == new_preferred_domain.text) class CrawlRateTest(unittest.TestCase): def setUp(self): self.crawl_rate = webmastertools.CrawlRate() def testToAndFromString(self): self.crawl_rate.text = 'normal' self.assert_(self.crawl_rate.text == 'normal') new_crawl_rate = webmastertools.CrawlRateFromString( self.crawl_rate.ToString()) self.assert_(self.crawl_rate.text == new_crawl_rate.text) class EnhancedImageSearchTest(unittest.TestCase): def setUp(self): self.enhanced_image_search = webmastertools.EnhancedImageSearch() def testToAndFromString(self): self.enhanced_image_search.text = 'true' self.assert_(self.enhanced_image_search.text == 'true') new_enhanced_image_search = webmastertools.EnhancedImageSearchFromString( self.enhanced_image_search.ToString()) self.assert_(self.enhanced_image_search.text == new_enhanced_image_search.text) class VerifiedTest(unittest.TestCase): def setUp(self): self.verified = webmastertools.Verified() def testToAndFromString(self): self.verified.text = 'true' self.assert_(self.verified.text == 'true') new_verified = webmastertools.VerifiedFromString(self.verified.ToString()) self.assert_(self.verified.text == new_verified.text) class VerificationMethodMetaTest(unittest.TestCase): def setUp(self): self.meta = webmastertools.VerificationMethodMeta() def testToAndFromString(self): self.meta.name = 'verify-vf1' self.meta.content = 'a2Ai' self.assert_(self.meta.name == 'verify-vf1') self.assert_(self.meta.content == 'a2Ai') new_meta = webmastertools.VerificationMethodMetaFromString( self.meta.ToString()) self.assert_(self.meta.name == new_meta.name) self.assert_(self.meta.content == new_meta.content) class VerificationMethodTest(unittest.TestCase): def setUp(self): pass def testMetaTagToAndFromString(self): self.method = webmastertools.VerificationMethod() self.method.type = 'metatag' self.method.in_use = 'false' self.assert_(self.method.type == 'metatag') self.assert_(self.method.in_use == 'false') self.method.meta = webmastertools.VerificationMethodMeta(name='verify-vf1', content='a2Ai') self.assert_(self.method.meta.name == 'verify-vf1') self.assert_(self.method.meta.content == 'a2Ai') new_method = webmastertools.VerificationMethodFromString( self.method.ToString()) self.assert_(self.method.type == new_method.type) self.assert_(self.method.in_use == new_method.in_use) self.assert_(self.method.meta.name == new_method.meta.name) self.assert_(self.method.meta.content == new_method.meta.content) method = webmastertools.VerificationMethod(type='xyz') self.assertEqual(method.type, 'xyz') method = webmastertools.VerificationMethod() self.assert_(method.type is None) def testHtmlPageToAndFromString(self): self.method = webmastertools.VerificationMethod() self.method.type = 'htmlpage' self.method.in_use = 'false' self.method.text = '456456-google.html' self.assert_(self.method.type == 'htmlpage') self.assert_(self.method.in_use == 'false') self.assert_(self.method.text == '456456-google.html') self.assert_(self.method.meta is None) new_method = webmastertools.VerificationMethodFromString( self.method.ToString()) self.assert_(self.method.type == new_method.type) self.assert_(self.method.in_use == new_method.in_use) self.assert_(self.method.text == new_method.text) self.assert_(self.method.meta is None) def testConvertActualData(self): feed = webmastertools.SitesFeedFromString(test_data.SITES_FEED) self.assert_(len(feed.entry[0].verification_method) == 2) check = 0 for method in feed.entry[0].verification_method: self.assert_(isinstance(method, webmastertools.VerificationMethod)) if method.type == 'metatag': self.assert_(method.in_use == 'false') self.assert_(method.text is None) self.assert_(method.meta.name == 'verify-v1') self.assert_(method.meta.content == 'a2Ai') check = check | 1 elif method.type == 'htmlpage': self.assert_(method.in_use == 'false') self.assert_(method.text == '456456-google.html') check = check | 2 else: self.fail('Wrong Verification Method: %s' % method.type) self.assert_(check == 2 ** 2 - 1, 'Should only have two Verification Methods, metatag and htmlpage') class MarkupLanguageTest(unittest.TestCase): def setUp(self): self.markup_language = webmastertools.MarkupLanguage() def testToAndFromString(self): self.markup_language.text = 'HTML' self.assert_(self.markup_language.text == 'HTML') new_markup_language = webmastertools.MarkupLanguageFromString( self.markup_language.ToString()) self.assert_(self.markup_language.text == new_markup_language.text) class SitemapMobileTest(unittest.TestCase): def setUp(self): self.sitemap_mobile = webmastertools.SitemapMobile() def testToAndFromString(self): self.sitemap_mobile.markup_language.append(webmastertools.MarkupLanguage( text = 'HTML')) self.assert_(self.sitemap_mobile.text is None) self.assert_(self.sitemap_mobile.markup_language[0].text == 'HTML') new_sitemap_mobile = webmastertools.SitemapMobileFromString( self.sitemap_mobile.ToString()) self.assert_(new_sitemap_mobile.text is None) self.assert_(self.sitemap_mobile.markup_language[0].text == new_sitemap_mobile.markup_language[0].text) def testConvertActualData(self): feed = webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED) self.assert_(feed.sitemap_mobile.text.strip() == '') self.assert_(len(feed.sitemap_mobile.markup_language) == 2) check = 0 for markup_language in feed.sitemap_mobile.markup_language: self.assert_(isinstance(markup_language, webmastertools.MarkupLanguage)) if markup_language.text == "HTML": check = check | 1 elif markup_language.text == "WAP": check = check | 2 else: self.fail('Unexpected markup language: %s' % markup_language.text) self.assert_(check == 2 ** 2 - 1, "Something is wrong with markup language") class SitemapMobileMarkupLanguageTest(unittest.TestCase): def setUp(self): self.sitemap_mobile_markup_language =\ webmastertools.SitemapMobileMarkupLanguage() def testToAndFromString(self): self.sitemap_mobile_markup_language.text = 'HTML' self.assert_(self.sitemap_mobile_markup_language.text == 'HTML') new_sitemap_mobile_markup_language =\ webmastertools.SitemapMobileMarkupLanguageFromString( self.sitemap_mobile_markup_language.ToString()) self.assert_(self.sitemap_mobile_markup_language.text ==\ new_sitemap_mobile_markup_language.text) class PublicationLabelTest(unittest.TestCase): def setUp(self): self.publication_label = webmastertools.PublicationLabel() def testToAndFromString(self): self.publication_label.text = 'Value1' self.assert_(self.publication_label.text == 'Value1') new_publication_label = webmastertools.PublicationLabelFromString( self.publication_label.ToString()) self.assert_(self.publication_label.text == new_publication_label.text) class SitemapNewsTest(unittest.TestCase): def setUp(self): self.sitemap_news = webmastertools.SitemapNews() def testToAndFromString(self): self.sitemap_news.publication_label.append(webmastertools.PublicationLabel( text = 'Value1')) self.assert_(self.sitemap_news.text is None) self.assert_(self.sitemap_news.publication_label[0].text == 'Value1') new_sitemap_news = webmastertools.SitemapNewsFromString( self.sitemap_news.ToString()) self.assert_(new_sitemap_news.text is None) self.assert_(self.sitemap_news.publication_label[0].text == new_sitemap_news.publication_label[0].text) def testConvertActualData(self): feed = webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED) self.assert_(len(feed.sitemap_news.publication_label) == 3) check = 0 for publication_label in feed.sitemap_news.publication_label: if publication_label.text == "Value1": check = check | 1 elif publication_label.text == "Value2": check = check | 2 elif publication_label.text == "Value3": check = check | 4 else: self.fail('Unexpected publication label: %s' % markup_language.text) self.assert_(check == 2 ** 3 - 1, 'Something is wrong with publication label') class SitemapNewsPublicationLabelTest(unittest.TestCase): def setUp(self): self.sitemap_news_publication_label =\ webmastertools.SitemapNewsPublicationLabel() def testToAndFromString(self): self.sitemap_news_publication_label.text = 'LabelValue' self.assert_(self.sitemap_news_publication_label.text == 'LabelValue') new_sitemap_news_publication_label =\ webmastertools.SitemapNewsPublicationLabelFromString( self.sitemap_news_publication_label.ToString()) self.assert_(self.sitemap_news_publication_label.text ==\ new_sitemap_news_publication_label.text) class SitemapLastDownloadedTest(unittest.TestCase): def setUp(self): self.sitemap_last_downloaded = webmastertools.SitemapLastDownloaded() def testToAndFromString(self): self.sitemap_last_downloaded.text = '2006-11-18T19:27:32.543Z' self.assert_(self.sitemap_last_downloaded.text ==\ '2006-11-18T19:27:32.543Z') new_sitemap_last_downloaded =\ webmastertools.SitemapLastDownloadedFromString( self.sitemap_last_downloaded.ToString()) self.assert_(self.sitemap_last_downloaded.text ==\ new_sitemap_last_downloaded.text) class SitemapTypeTest(unittest.TestCase): def setUp(self): self.sitemap_type = webmastertools.SitemapType() def testToAndFromString(self): self.sitemap_type.text = 'WEB' self.assert_(self.sitemap_type.text == 'WEB') new_sitemap_type = webmastertools.SitemapTypeFromString( self.sitemap_type.ToString()) self.assert_(self.sitemap_type.text == new_sitemap_type.text) class SitemapStatusTest(unittest.TestCase): def setUp(self): self.sitemap_status = webmastertools.SitemapStatus() def testToAndFromString(self): self.sitemap_status.text = 'Pending' self.assert_(self.sitemap_status.text == 'Pending') new_sitemap_status = webmastertools.SitemapStatusFromString( self.sitemap_status.ToString()) self.assert_(self.sitemap_status.text == new_sitemap_status.text) class SitemapUrlCountTest(unittest.TestCase): def setUp(self): self.sitemap_url_count = webmastertools.SitemapUrlCount() def testToAndFromString(self): self.sitemap_url_count.text = '0' self.assert_(self.sitemap_url_count.text == '0') new_sitemap_url_count = webmastertools.SitemapUrlCountFromString( self.sitemap_url_count.ToString()) self.assert_(self.sitemap_url_count.text == new_sitemap_url_count.text) class SitesEntryTest(unittest.TestCase): def setUp(self): pass def testToAndFromString(self): entry = webmastertools.SitesEntry( indexed=webmastertools.Indexed(text='true'), crawled=webmastertools.Crawled(text='2008-09-14T08:59:28.000'), geolocation=webmastertools.GeoLocation(text='US'), preferred_domain=webmastertools.PreferredDomain(text='none'), crawl_rate=webmastertools.CrawlRate(text='normal'), enhanced_image_search=webmastertools.EnhancedImageSearch(text='true'), verified=webmastertools.Verified(text='false'), ) self.assert_(entry.indexed.text == 'true') self.assert_(entry.crawled.text == '2008-09-14T08:59:28.000') self.assert_(entry.geolocation.text == 'US') self.assert_(entry.preferred_domain.text == 'none') self.assert_(entry.crawl_rate.text == 'normal') self.assert_(entry.enhanced_image_search.text == 'true') self.assert_(entry.verified.text == 'false') new_entry = webmastertools.SitesEntryFromString(entry.ToString()) self.assert_(new_entry.indexed.text == 'true') self.assert_(new_entry.crawled.text == '2008-09-14T08:59:28.000') self.assert_(new_entry.geolocation.text == 'US') self.assert_(new_entry.preferred_domain.text == 'none') self.assert_(new_entry.crawl_rate.text == 'normal') self.assert_(new_entry.enhanced_image_search.text == 'true') self.assert_(new_entry.verified.text == 'false') def testConvertActualData(self): feed = webmastertools.SitesFeedFromString(test_data.SITES_FEED) self.assert_(len(feed.entry) == 1) entry = feed.entry[0] self.assert_(isinstance(entry, webmastertools.SitesEntry)) self.assert_(entry.indexed.text == 'true') self.assert_(entry.crawled.text == '2008-09-14T08:59:28.000') self.assert_(entry.geolocation.text == 'US') self.assert_(entry.preferred_domain.text == 'none') self.assert_(entry.crawl_rate.text == 'normal') self.assert_(entry.enhanced_image_search.text == 'true') self.assert_(entry.verified.text == 'false') class SitesFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.webmastertools.SitesFeedFromString(test_data.SITES_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 1) for entry in self.feed.entry: self.assert_(isinstance(entry, webmastertools.SitesEntry)) new_feed = webmastertools.SitesFeedFromString(self.feed.ToString()) self.assert_(len(new_feed.entry) == 1) for entry in new_feed.entry: self.assert_(isinstance(entry, webmastertools.SitesEntry)) class SitemapsEntryTest(unittest.TestCase): def testRegularToAndFromString(self): entry = webmastertools.SitemapsEntry( sitemap_type=webmastertools.SitemapType(text='WEB'), sitemap_status=webmastertools.SitemapStatus(text='Pending'), sitemap_last_downloaded=webmastertools.SitemapLastDownloaded( text='2006-11-18T19:27:32.543Z'), sitemap_url_count=webmastertools.SitemapUrlCount(text='102'), ) self.assert_(entry.sitemap_type.text == 'WEB') self.assert_(entry.sitemap_status.text == 'Pending') self.assert_(entry.sitemap_last_downloaded.text ==\ '2006-11-18T19:27:32.543Z') self.assert_(entry.sitemap_url_count.text == '102') new_entry = webmastertools.SitemapsEntryFromString(entry.ToString()) self.assert_(new_entry.sitemap_type.text == 'WEB') self.assert_(new_entry.sitemap_status.text == 'Pending') self.assert_(new_entry.sitemap_last_downloaded.text ==\ '2006-11-18T19:27:32.543Z') self.assert_(new_entry.sitemap_url_count.text == '102') def testConvertActualData(self): feed = gdata.webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED) self.assert_(len(feed.entry) == 3) for entry in feed.entry: self.assert_(entry, webmastertools.SitemapsEntry) self.assert_(entry.sitemap_status, webmastertools.SitemapStatus) self.assert_(entry.sitemap_last_downloaded, webmastertools.SitemapLastDownloaded) self.assert_(entry.sitemap_url_count, webmastertools.SitemapUrlCount) self.assert_(entry.sitemap_status.text == 'StatusValue') self.assert_(entry.sitemap_last_downloaded.text ==\ '2006-11-18T19:27:32.543Z') self.assert_(entry.sitemap_url_count.text == '102') if entry.id.text == 'http://www.example.com/sitemap-index.xml': self.assert_(entry.sitemap_type, webmastertools.SitemapType) self.assert_(entry.sitemap_type.text == 'WEB') self.assert_(entry.sitemap_mobile_markup_language is None) self.assert_(entry.sitemap_news_publication_label is None) elif entry.id.text == 'http://www.example.com/mobile/sitemap-index.xml': self.assert_(entry.sitemap_mobile_markup_language, webmastertools.SitemapMobileMarkupLanguage) self.assert_(entry.sitemap_mobile_markup_language.text == 'HTML') self.assert_(entry.sitemap_type is None) self.assert_(entry.sitemap_news_publication_label is None) elif entry.id.text == 'http://www.example.com/news/sitemap-index.xml': self.assert_(entry.sitemap_news_publication_label, webmastertools.SitemapNewsPublicationLabel) self.assert_(entry.sitemap_news_publication_label.text == 'LabelValue') self.assert_(entry.sitemap_type is None) self.assert_(entry.sitemap_mobile_markup_language is None) class SitemapsFeedTest(unittest.TestCase): def setUp(self): self.feed = gdata.webmastertools.SitemapsFeedFromString( test_data.SITEMAPS_FEED) def testToAndFromString(self): self.assert_(len(self.feed.entry) == 3) for entry in self.feed.entry: self.assert_(isinstance(entry, webmastertools.SitemapsEntry)) new_feed = webmastertools.SitemapsFeedFromString(self.feed.ToString()) self.assert_(len(new_feed.entry) == 3) for entry in new_feed.entry: self.assert_(isinstance(entry, webmastertools.SitemapsEntry)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python __author__ = "James Sams <sams.james@gmail.com>" import unittest from gdata import test_data import gdata.books import atom class BookEntryTest(unittest.TestCase): def testBookEntryFromString(self): entry = gdata.books.Book.FromString(test_data.BOOK_ENTRY) self.assert_(isinstance(entry, gdata.books.Book)) self.assertEquals([x.text for x in entry.creator], ['John Rawls']) self.assertEquals(entry.date.text, '1999') self.assertEquals(entry.format.text, '538 pages') self.assertEquals([x.text for x in entry.identifier], ['b7GZr5Btp30C', 'ISBN:0198250541', 'ISBN:9780198250548']) self.assertEquals([x.text for x in entry.publisher], ['Oxford University Press']) self.assertEquals(entry.subject, None) self.assertEquals([x.text for x in entry.dc_title], ['A theory of justice']) self.assertEquals(entry.viewability.value, 'http://schemas.google.com/books/2008#view_partial') self.assertEquals(entry.embeddability.value, 'http://schemas.google.com/books/2008#embeddable') self.assertEquals(entry.review, None) self.assertEquals([getattr(entry.rating, x) for x in ("min", "max", "average", "value")], ['1', '5', '4.00', None]) self.assertEquals(entry.GetThumbnailLink().href, 'http://bks0.books.google.com/books?id=b7GZr5Btp30C&printsec=frontcover&img=1&zoom=5&sig=ACfU3U121bWZsbjBfVwVRSK2o982jJTd1w&source=gbs_gdata') self.assertEquals(entry.GetInfoLink().href, 'http://books.google.com/books?id=b7GZr5Btp30C&ie=ISO-8859-1&source=gbs_gdata') self.assertEquals(entry.GetPreviewLink(), None) self.assertEquals(entry.GetAnnotationLink().href, 'http://www.google.com/books/feeds/users/me/volumes') self.assertEquals(entry.get_google_id(), 'b7GZr5Btp30C') def testBookFeedFromString(self): feed = gdata.books.BookFeed.FromString(test_data.BOOK_FEED) self.assert_(isinstance(feed, gdata.books.BookFeed)) self.assertEquals( len(feed.entry), 1) self.assert_(isinstance(feed.entry[0], gdata.books.Book)) def testBookEntryToDict(self): book = gdata.books.Book() book.dc_title.append(gdata.books.Title(text='a')) book.dc_title.append(gdata.books.Title(text='b')) book.dc_title.append(gdata.books.Title(text='c')) self.assertEqual(book.to_dict()['title'], 'a b c') if __name__ == "__main__": unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.spreadsheets.data import gdata.test_config as conf import atom.core SPREADSHEET = """<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='"BxAUSQUJRCp7ImBq"'> <id>http://spreadsheets.google.com/feeds/spreadsheets/private/full/key</id> <updated>2006-11-17T18:24:18.231Z</updated> <title type="text">Groceries R Us</title> <content type="text">Groceries R Us</content> <link rel="http://schemas.google.com/spreadsheets/2006#worksheetsfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/spreadsheets/private/full/key"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> </entry>""" WORKSHEETS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gs="http://schemas.google.com/spreadsheets/2006" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='W/"D0cERnk-eip7ImA9WBBXGEg."'> <id>http://spreadsheets.google.com/feeds/worksheets/key/private/full</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Groceries R Us</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/key/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:totalResults>1</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>1</openSearch:itemsPerPage> <entry gd:etag='"YDwqeyI."'> <id>http://spreadsheets.google.com/feeds/worksheets/0/private/full/1</id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Sheet1</title> <content type="text">Sheet1</content> <link rel="http://schemas.google.com/spreadsheets/2006#listfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/0/1/private/full"/> <link rel="http://schemas.google.com/spreadsheets/2006#cellsfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/0/1/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/0/private/full/1"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/.../0/.../1/version"/> <gs:rowCount>100</gs:rowCount> <gs:colCount>20</gs:colCount> </entry> </feed>""" NEW_WORKSHEET = """<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <title>Expenses</title> <gs:rowCount>50</gs:rowCount> <gs:colCount>10</gs:colCount> </entry>""" EDIT_WORKSHEET = """<entry> <id> http://spreadsheets.google.com/feeds/worksheets/k/private/full/w </id> <updated>2007-07-30T18:51:30.666Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#worksheet"/> <title type="text">Income</title> <content type="text">Expenses</content> <link rel="http://schemas.google.com/spreadsheets/2006#listfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full"/> <link rel="http://schemas.google.com/spreadsheets/2006#cellsfeed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/worksheets/k/private/full/w"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/.../k/private/full/w/v"/> <gs:rowCount>45</gs:rowCount> <gs:colCount>15</gs:colCount> </entry>""" NEW_TABLE = """<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <title type='text'>Table 1</title> <summary type='text'>This is a list of all who have registered to vote and whether or not they qualify to vote.</summary> <gs:worksheet name='Sheet1' /> <gs:header row='1' /> <gs:data numRows='0' startRow='2'> <gs:column index='B' name='Birthday' /> <gs:column index='C' name='Age' /> <gs:column index='A' name='Name' /> <gs:column index='D' name='CanVote' /> </gs:data> </entry>""" TABLES_FEED = """<?xml version='1.0' encoding='utf-8'?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gs="http://schemas.google.com/spreadsheets/2006" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='W/"DEQHQn84fCt7ImA9WxJTGEU."'> <id> http://spreadsheets.google.com/feeds/key/tables</id> <updated>2009-04-28T02:38:53.134Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#table' /> <title>Sample table and record feed</title> <link rel='alternate' type='text/html' href='http://spreadsheets.google.com/ccc?key=key' /> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables' /> <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables' /> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables' /> <author> <name>Liz</name> <email>liz@gmail.com</email> </author> <openSearch:totalResults>2</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <entry gd:etag='"HBcUVgtWASt7ImBq"'> <id> http://spreadsheets.google.com/feeds/key/tables/0</id> <updated>2009-04-28T01:20:32.707Z</updated> <app:edited xmlns:app="http://www.w3.org/2007/app"> 2009-04-28T01:20:32.707Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#table' /> <title>Table 1</title> <summary>This is a list of all who have registered to vote and whether or not they qualify to vote.</summary> <content type='application/atom+xml;type=feed' src='http://spreadsheets.google.com/feeds/key/records/0' /> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables/0' /> <link rel='edit' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables/0' /> <gs:worksheet name='Sheet1' /> <gs:header row='1' /> <gs:data insertionMode='overwrite' numRows='2' startRow='2'> <gs:column index='B' name='Birthday' /> <gs:column index='C' name='Age' /> <gs:column index='A' name='Name' /> <gs:column index='D' name='CanVote' /> </gs:data> </entry> <entry gd:etag='"HBcUVgdCGyt7ImBq"'> <id> http://spreadsheets.google.com/feeds/key/tables/1</id> <updated>2009-04-28T01:20:38.313Z</updated> <app:edited xmlns:app="http://www.w3.org/2007/app"> 2009-04-28T01:20:38.313Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#table' /> <title>Table 2</title> <summary>List of detailed information about each voter.</summary> <content type='application/atom+xml;type=feed' src='http://spreadsheets.google.com/feeds/key/records/1' /> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables/1' /> <link rel='edit' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/tables/1' /> <gs:worksheet name='Sheet1' /> <gs:header row='30' /> <gs:data insertionMode='overwrite' numRows='10' startRow='34'> <gs:column index='C' name='Last' /> <gs:column index='B' name='First' /> <gs:column index='D' name='DOB' /> <gs:column index='E' name='Driver License?' /> </gs:data> </entry> </feed>""" NEW_RECORD = """<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <title>Darcy</title> <gs:field name='Birthday'>2/10/1785</gs:field> <gs:field name='Age'>28</gs:field> <gs:field name='Name'>Darcy</gs:field> <gs:field name='CanVote'>No</gs:field> </entry>""" RECORDS_FEED = """<?xml version='1.0' encoding='utf-8'?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gs="http://schemas.google.com/spreadsheets/2006" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='W/"DEQHQn84fCt7ImA9WxJTGEU."'> <id>http://spreadsheets.google.com/feeds/key/records/0</id> <updated>2009-04-28T02:38:53.134Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#record' /> <title>Table 1</title> <link rel='alternate' type='text/html' href='http://spreadsheets.google.com/pub?key=key' /> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0' /> <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0' /> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0' /> <author> <name>Liz</name> <email>liz@gmail.com</email> </author> <openSearch:totalResults>2</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <entry gd:etag='"UB8DTlJAKSt7ImA-WkUT"'> <id> http://spreadsheets.google.com/feeds/key/records/0/cn6ca</id> <updated>2009-04-28T02:38:53.134Z</updated> <app:edited xmlns:app="http://www.w3.org/2007/app"> 2009-04-28T02:38:53.134Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#record' /> <title>Darcy</title> <content>Birthday: 2/10/1785, Age: 28, Name: Darcy, CanVote: No</content> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0/cn6ca' /> <link rel='edit' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0/cn6ca' /> <gs:field index='B' name='Birthday'>2/10/1785</gs:field> <gs:field index='C' name='Age'>28</gs:field> <gs:field index='A' name='Name'>Darcy</gs:field> <gs:field index='D' name='CanVote'>No</gs:field> </entry> <entry gd:etag='"UVBFUEcNRCt7ImA9DU8."'> <id> http://spreadsheets.google.com/feeds/key/records/0/cokwr</id> <updated>2009-04-28T02:38:53.134Z</updated> <app:edited xmlns:app="http://www.w3.org/2007/app"> 2009-04-28T02:38:53.134Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/spreadsheets/2006#record' /> <title>Jane</title> <content>Birthday: 1/6/1791, Age: 22, Name: Jane, CanVote: Yes</content> <link rel='self' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0/cokwr' /> <link rel='edit' type='application/atom+xml' href='http://spreadsheets.google.com/feeds/key/records/0/cokwr' /> <gs:field index='B' name='Birthday'>1/6/1791</gs:field> <gs:field index='C' name='Age'>22</gs:field> <gs:field index='A' name='Name'>Jane</gs:field> <gs:field index='D' name='CanVote'>Yes</gs:field> </entry> </feed>""" LIST_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='W/"D0cERnk-eip7ImA9WBBXGEg."'> <id> http://spreadsheets.google.com/feeds/list/key/worksheetId/private/full </id> <updated>2006-11-17T18:23:45.173Z</updated> <title type="text">Sheet1</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full"/> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:totalResults>8</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>8</openSearch:itemsPerPage> <entry gd:etag='"S0wCTlpIIip7ImA0X0QI"'> <id>http://spreadsheets.google.com/feeds/list/k/w/private/full/r</id> <updated>2006-11-17T18:23:45.173Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#list"/> <title type="text">Bingley</title> <content type="text">Hours: 10, Items: 2, IPM: 0.0033</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r/v"/> <gsx:name>Bingley</gsx:name> <gsx:hours>10</gsx:hours> <gsx:items>2</gsx:items> <gsx:ipm>0.0033</gsx:ipm> </entry> <entry gd:etag='"AxQDSXxjfyp7ImA0ChJVSBI."'> <id> http://spreadsheets.google.com/feeds/list/k/w/private/full/rowId </id> <updated>2006-11-17T18:23:45.173Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#list"/> <title type="text">Charlotte</title> <content type="text">Hours: 60, Items: 18000, IPM: 5</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r/v"/> <gsx:name>Charlotte</gsx:name> <gsx:hours>60</gsx:hours> <gsx:items>18000</gsx:items> <gsx:ipm>5</gsx:ipm> </entry> </feed>""" NEW_ROW = """<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:hours>1</gsx:hours> <gsx:ipm>1</gsx:ipm> <gsx:items>60</gsx:items> <gsx:name>Elizabeth Bennet</gsx:name> </entry>""" UPDATED_ROW = """<entry gd:etag='"S0wCTlpIIip7ImA0X0QI"' xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <id>http://spreadsheets.google.com/feeds/list/k/w/private/full/rowId</id> <updated>2006-11-17T18:23:45.173Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#list"/> <title type="text">Bingley</title> <content type="text">Hours: 10, Items: 2, IPM: 0.0033</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/list/k/w/private/full/r/v"/> <gsx:name>Bingley</gsx:name> <gsx:hours>20</gsx:hours> <gsx:items>4</gsx:items> <gsx:ipm>0.0033</gsx:ipm> </entry>""" CELLS_FEED = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gs="http://schemas.google.com/spreadsheets/2006" xmlns:gd="http://schemas.google.com/g/2005" gd:etag='W/"D0cERnk-eip7ImA9WBBXGEg."'> <id> http://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full </id> <updated>2006-11-17T18:27:32.543Z</updated> <title type="text">Sheet1</title> <link rel="alternate" type="text/html" href="http://spreadsheets.google.com/ccc?key=key"/> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/private/full"/> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" <link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/private/full/batch"/> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/private/full"/> <author> <name>Fitzwilliam Darcy</name> <email>fitz@gmail.com</email> </author> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>36</openSearch:itemsPerPage> <gs:rowCount>100</gs:rowCount> <gs:colCount>20</gs:colCount> <entry gd:etag='"ImA9D1APFyp7"'> <id> http://spreadsheets.google.com/feeds/cells/k/w/private/full/R1C1 </id> <updated>2006-11-17T18:27:32.543Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell"/> <title type="text">A1</title> <content type="text">Name</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/pr/full/R1C1"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/./cells/k/w/pr/full/R1C1/bgvjf"/> <gs:cell row="1" col="1" inputValue="Name">Name</gs:cell> </entry> <entry gd:etag='"YD0PS1YXByp7Ig.."'> <id> http://spreadsheets.google.com/feeds/cells/k/w/private/full/R1C2 </id> <updated>2006-11-17T18:27:32.543Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell"/> <title type="text">B1</title> <content type="text">Hours</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/pr/full/R1C2"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/./cells/k/w/pr/full/R1C2/1pn567"/> <gs:cell row="1" col="2" inputValue="Hours">Hours</gs:cell> </entry> <entry gd:etag='"ImB5CBYSRCp7"'> <id> http://spreadsheets.google.com/feeds/cells/k/w/private/full/R9C4 </id> <updated>2006-11-17T18:27:32.543Z</updated> <category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell"/> <title type="text">D9</title> <content type="text">5</content> <link rel="self" type="application/atom+xml" href="http://spreadsheets.google.com/feeds/cells/k/w/pr/full/R9C4"/> <link rel="edit" type="application/atom+xml" href="http://spreadsheets.google.com/./cells/k/w/pr/full/R9C4/srevc"/> <gs:cell row="9" col="4" inputValue="=FLOOR(R[0]C[-1]/(R[0]C[-2]*60),.0001)" numericValue="5.0">5</gs:cell> </entry> </feed>""" BATCH_CELLS = """<feed xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gs="http://schemas.google.com/spreadsheets/2006"> <id> http://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full </id> <entry> <batch:id">A1</batch:id"> <batch:operation type="update"/> <id> http://spreadsheets.google.com/feeds/cells/k/w/private/full/cellId </id> <link rel="edit" type="application/atom+xml" href="http://spreadsheets/google.com/./cells/k/w/pr/full/R2C4/v"/> <gs:cell row="2" col="4" inputValue="newData"/> </entry> <entry> <batch:id">A2</batch:id"> <batch:operation type="update"/> <title type="text">A2</title> <id> http://spreadsheets.google.com/feeds/cells/k/w/private/full/cellId </id> <link rel="edit" type="application/atom+xml" href="http://spreadsheets/google.com/feeds/cells/k/w/pr/full/R2C5/v"/> <gs:cell row="2" col="5" inputValue="moreInfo"/> </entry> </feed>""" class SpreadsheetEntryTest(unittest.TestCase): def setUp(self): self.spreadsheet = atom.core.parse( SPREADSHEET, gdata.spreadsheets.data.Spreadsheet) def test_check_parsing(self): self.assertEqual(self.spreadsheet.etag, '"BxAUSQUJRCp7ImBq"') self.assertEqual(self.spreadsheet.id.text, 'http://spreadsheets.google.com/feeds/spreadsheets' '/private/full/key') self.assertEqual(self.spreadsheet.updated.text, '2006-11-17T18:24:18.231Z') self.assertEqual(self.spreadsheet.find_worksheets_feed(), 'http://spreadsheets.google.com/feeds/worksheets' '/key/private/full') self.assertEqual(self.spreadsheet.find_self_link(), 'http://spreadsheets.google.com/feeds/spreadsheets' '/private/full/key') class ListEntryTest(unittest.TestCase): def test_get_and_set_column_value(self): row = atom.core.parse(NEW_ROW, gdata.spreadsheets.data.ListEntry) row.set_value('hours', '3') row.set_value('name', 'Lizzy') self.assertEqual(row.get_value('hours'), '3') self.assertEqual(row.get_value('ipm'), '1') self.assertEqual(row.get_value('items'), '60') self.assertEqual(row.get_value('name'), 'Lizzy') self.assertEqual(row.get_value('x'), None) row.set_value('x', 'Test') self.assertEqual(row.get_value('x'), 'Test') row_xml = str(row) self.assert_(row_xml.find(':x') > -1) self.assert_(row_xml.find('>Test</') > -1) self.assert_(row_xml.find(':hours') > -1) self.assert_(row_xml.find('>3</') > -1) self.assert_(row_xml.find(':ipm') > -1) self.assert_(row_xml.find('>1</') > -1) self.assert_(row_xml.find(':items') > -1) self.assert_(row_xml.find('>60</') > -1) self.assert_(row_xml.find(':name') > -1) self.assert_(row_xml.find('>Lizzy</') > -1) self.assertEqual(row_xml.find(':zzz'), -1) self.assertEqual(row_xml.find('>foo</'), -1) def test_check_parsing(self): row = atom.core.parse(NEW_ROW, gdata.spreadsheets.data.ListEntry) self.assertEqual(row.get_value('hours'), '1') self.assertEqual(row.get_value('ipm'), '1') self.assertEqual(row.get_value('items'), '60') self.assertEqual(row.get_value('name'), 'Elizabeth Bennet') self.assertEqual(row.get_value('none'), None) row = atom.core.parse(UPDATED_ROW, gdata.spreadsheets.data.ListEntry) self.assertEqual(row.get_value('hours'), '20') self.assertEqual(row.get_value('ipm'), '0.0033') self.assertEqual(row.get_value('items'), '4') self.assertEqual(row.get_value('name'), 'Bingley') self.assertEqual(row.get_value('x'), None) self.assertEqual( row.id.text, 'http://spreadsheets.google.com/feeds/list' '/k/w/private/full/rowId') self.assertEqual(row.updated.text, '2006-11-17T18:23:45.173Z') self.assertEqual(row.content.text, 'Hours: 10, Items: 2, IPM: 0.0033') class RecordEntryTest(unittest.TestCase): def setUp(self): self.records = atom.core.parse( RECORDS_FEED, gdata.spreadsheets.data.RecordsFeed) def test_get_by_index(self): self.assertEqual(self.records.entry[0].field[0].index, 'B') self.assertEqual(self.records.entry[0].field[0].name, 'Birthday') self.assertEqual(self.records.entry[0].field[0].text, '2/10/1785') self.assertEqual(self.records.entry[0].value_for_index('B'), '2/10/1785') self.assertRaises(gdata.spreadsheets.data.FieldMissing, self.records.entry[0].ValueForIndex, 'E') self.assertEqual(self.records.entry[1].value_for_index('D'), 'Yes') def test_get_by_name(self): self.assertEqual(self.records.entry[0].ValueForName('Birthday'), '2/10/1785') self.assertRaises(gdata.spreadsheets.data.FieldMissing, self.records.entry[0].value_for_name, 'Foo') self.assertEqual(self.records.entry[1].value_for_name('Age'), '22') class DataClassSanityTest(unittest.TestCase): def test_basic_element_structure(self): conf.check_data_classes(self, [ gdata.spreadsheets.data.Cell, gdata.spreadsheets.data.ColCount, gdata.spreadsheets.data.Field, gdata.spreadsheets.data.Column, gdata.spreadsheets.data.Data, gdata.spreadsheets.data.Header, gdata.spreadsheets.data.RowCount, gdata.spreadsheets.data.Worksheet, gdata.spreadsheets.data.Spreadsheet, gdata.spreadsheets.data.SpreadsheetsFeed, gdata.spreadsheets.data.WorksheetEntry, gdata.spreadsheets.data.WorksheetsFeed, gdata.spreadsheets.data.Table, gdata.spreadsheets.data.TablesFeed, gdata.spreadsheets.data.Record, gdata.spreadsheets.data.RecordsFeed, gdata.spreadsheets.data.ListRow, gdata.spreadsheets.data.ListEntry, gdata.spreadsheets.data.ListsFeed, gdata.spreadsheets.data.CellEntry, gdata.spreadsheets.data.CellsFeed]) def suite(): return conf.build_suite([SpreadsheetEntryTest, DataClassSanityTest, ListEntryTest, RecordEntryTest]) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import gdata.spreadsheets.client import gdata.gauth import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data import gdata.test_config as conf conf.options.register_option(conf.SPREADSHEET_ID_OPTION) class SpreadsheetsClientTest(unittest.TestCase): def setUp(self): self.client = None if conf.options.get_value('runlive') == 'true': self.client = gdata.spreadsheets.client.SpreadsheetsClient() conf.configure_client(self.client, 'SpreadsheetsClientTest', 'wise') def tearDown(self): conf.close_client(self.client) def test_create_update_delete_worksheet(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete_worksheet') spreadsheet_id = conf.options.get_value('spreadsheetid') original_worksheets = self.client.get_worksheets(spreadsheet_id) self.assert_(isinstance(original_worksheets, gdata.spreadsheets.data.WorksheetsFeed)) worksheet_count = int(original_worksheets.total_results.text) # Add a new worksheet to the spreadsheet. created = self.client.add_worksheet( spreadsheet_id, 'a test worksheet', 4, 8) self.assert_(isinstance(created, gdata.spreadsheets.data.WorksheetEntry)) self.assertEqual(created.title.text, 'a test worksheet') self.assertEqual(created.row_count.text, '4') self.assertEqual(created.col_count.text, '8') # There should now be one more worksheet in this spreadsheet. updated_worksheets = self.client.get_worksheets(spreadsheet_id) new_worksheet_count = int(updated_worksheets.total_results.text) self.assertEqual(worksheet_count + 1, new_worksheet_count) # Delete our test worksheet. self.client.delete(created) # We should be back to the original number of worksheets. updated_worksheets = self.client.get_worksheets(spreadsheet_id) new_worksheet_count = int(updated_worksheets.total_results.text) self.assertEqual(worksheet_count, new_worksheet_count) def test_create_update_delete_table_and_records(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache( self.client, 'test_create_update_delete_table_and_records') spreadsheet_id = conf.options.get_value('spreadsheetid') tables = self.client.get_tables(spreadsheet_id) test_worksheet = self.client.add_worksheet( spreadsheet_id, 'worksheet x', rows=30, cols=3) self.assert_(isinstance(tables, gdata.spreadsheets.data.TablesFeed)) initial_count = tables.total_results.text created_table = self.client.add_table( spreadsheet_id, 'Test Table', 'This table is for testing', 'worksheet x', header_row=5, num_rows=10, start_row=8, insertion_mode=None, column_headers={'B': 'Food', 'C': 'Drink', 'A': 'Price'}) # Re-get the list of tables and make sure there are more now. updated_tables = self.client.get_tables(spreadsheet_id) self.assertEqual(int(initial_count) + 1, int(updated_tables.total_results.text)) # Get the records in our new table to make sure it has the correct # number of records. table_num = int(created_table.get_table_id()) starting_records = self.client.get_records(spreadsheet_id, table_num) self.assertEqual(starting_records.total_results.text, '10') self.assert_(starting_records.entry[0].field[0].text is None) self.assert_(starting_records.entry[0].field[1].text is None) self.assert_(starting_records.entry[1].field[0].text is None) self.assert_(starting_records.entry[1].field[1].text is None) record1 = self.client.add_record( spreadsheet_id, table_num, {'Food': 'Cheese', 'Drink': 'Soda', 'Price': '2.99'}, 'icky') self.client.add_record(spreadsheet_id, table_num, {'Food': 'Eggs', 'Drink': 'Milk'}) self.client.add_record(spreadsheet_id, table_num, {'Food': 'Spinach', 'Drink': 'Water'}) updated_records = self.client.get_records(spreadsheet_id, table_num) self.assertEqual(updated_records.entry[10].value_for_name('Price'), '2.99') self.assertEqual(updated_records.entry[10].value_for_index('A'), '2.99') self.assertEqual(updated_records.entry[10].value_for_name('Drink'), 'Soda') self.assert_(updated_records.entry[11].value_for_name('Price') is None) self.assertEqual(updated_records.entry[11].value_for_name('Drink'), 'Milk') self.assertEqual(updated_records.entry[12].value_for_name('Drink'), 'Water') self.assert_(updated_records.entry[1].value_for_index('A') is None) self.assert_(updated_records.entry[2].value_for_index('B') is None) self.assert_(updated_records.entry[3].value_for_index('C') is None) # Cleanup the table. self.client.delete(created_table) # Delete the test worksheet in which the table was placed. self.client.delete(test_worksheet) # Make sure we are back to the original count. updated_tables = self.client.get_tables(spreadsheet_id) self.assertEqual(int(initial_count), int(updated_tables.total_results.text)) def suite(): return conf.build_suite([SpreadsheetsClientTest]) if __name__ == '__main__': unittest.TextTestRunner().run(suite())
Python