desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Pop the I{top} frame. @return: The popped frame. @rtype: L{Frame} @raise StopIteration: when stack is empty.'
def pop(self):
if len(self.stack): return self.stack.pop() else: raise StopIteration()
'Get the I{top} frame. @return: The top frame. @rtype: L{Frame} @raise StopIteration: when stack is empty.'
def top(self):
if len(self.stack): return self.stack[(-1)] else: raise StopIteration()
'Get the next item. @return: A tuple: the next (child, ancestry). @rtype: (L{SchemaObject}, [L{SchemaObject},..]) @raise StopIteration: A the end.'
def next(self):
frame = self.top() while True: result = frame.next() if (result is None): self.pop() return self.next() if isinstance(result, Content): ancestry = [f.sx for f in self.stack] return (result, ancestry) self.push(result) return...
'@param schema: The containing schema. @type schema: L{schema.Schema}'
def __init__(self, schema, name):
root = Element(name) SchemaObject.__init__(self, schema, root) self.name = name self.nillable = True
'@param matcher: An object used as criteria for match. @type matcher: I{any}.match(n) @param limit: Limit the number of matches. 0=unlimited. @type limit: int'
def __init__(self, matcher, limit=0):
self.matcher = matcher self.limit = limit
'Traverse the tree looking for matches. @param node: A node to match on. @type node: L{SchemaObject} @param list: A list to fill. @type list: list'
def find(self, node, list):
if self.matcher.match(node): list.append(node) self.limit -= 1 if (self.limit == 0): return for c in node.rawchildren: self.find(c, list) return self
''
def __init__(self):
self.unsorted = [] self.index = {} self.stack = [] self.pushed = set() self.sorted = None
'Add items to be sorted. @param items: One or more items to be added. @type items: I{item} @return: self @rtype: L{DepList}'
def add(self, *items):
for item in items: self.unsorted.append(item) key = item[0] self.index[key] = item return self
'Sort the list based on dependancies. @return: The sorted items. @rtype: list'
def sort(self):
self.sorted = list() self.pushed = set() for item in self.unsorted: popped = [] self.push(item) while len(self.stack): try: top = self.top() ref = top[1].next() refd = self.index.get(ref) if (refd is None): ...
'Get the item at the top of the stack. @return: The top item. @rtype: (item, iter)'
def top(self):
return self.stack[(-1)]
'Push and item onto the sorting stack. @param item: An item to push. @type item: I{item} @return: The number of items pushed. @rtype: int'
def push(self, item):
if (item in self.pushed): return frame = (item, iter(item[1])) self.stack.append(frame) self.pushed.add(item)
'Pop the top item off the stack and append it to the sorted list. @return: The popped item. @rtype: I{item}'
def pop(self):
try: frame = self.stack.pop() return frame[0] except: pass
'@param ref: The schema reference being queried. @type ref: qref'
def __init__(self, ref=None):
Object.__init__(self) self.id = objid(self) self.ref = ref self.history = [] self.resolved = False if (not isqref(self.ref)): raise Exception(('%s, must be qref' % tostr(self.ref)))
'Execute this query using the specified schema. @param schema: The schema associated with the query. The schema is used by the query to search for items. @type schema: L{schema.Schema} @return: The item matching the search criteria. @rtype: L{sxbase.SchemaObject}'
def execute(self, schema):
raise Exception, 'not-implemented by subclass'
'Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean'
def filter(self, result):
if (result is None): return True reject = (result in self.history) if reject: log.debug('result %s, rejected by\n%s', Repr(result), self) return reject
'Query result post processing. @param result: A query result. @type result: L{sxbase.SchemaObject}'
def result(self, result):
if (result is None): log.debug('%s, not-found', self.ref) return if self.resolved: result = result.resolve() log.debug('%s, found as: %s', self.ref, Repr(result)) self.history.append(result) return result
'Map (override) tag => I{class} mapping. @param tag: An xsd tag name. @type tag: str @param fn: A function or class. @type fn: fn|class.'
@classmethod def maptag(cls, tag, fn):
cls.tags[tag] = fn
'Create an object based on the root tag name. @param schema: A schema object. @type schema: L{schema.Schema} @param name: The name. @type name: str @return: The created object. @rtype: L{XBuiltin}'
@classmethod def create(cls, schema, name):
fn = cls.tags.get(name) if (fn is not None): return fn(schema, name) else: return XBuiltin(schema, name)
'@param wsdl: A wsdl object. @type wsdl: L{suds.wsdl.Definitions}'
def __init__(self, wsdl):
self.wsdl = wsdl self.children = [] self.namespaces = {}
'Add a schema node to the collection. Schema(s) within the same target namespace are consolidated. @param schema: A schema object. @type schema: (L{Schema})'
def add(self, schema):
key = schema.tns[1] existing = self.namespaces.get(key) if (existing is None): self.children.append(schema) self.namespaces[key] = schema else: existing.root.children += schema.root.children existing.root.nsprefixes.update(schema.root.nsprefixes)
'Load the schema objects for the root nodes. - de-references schemas - merge schemas @param options: An options dictionary. @type options: L{options.Options} @return: The merged schema. @rtype: L{Schema}'
def load(self, options):
if options.autoblend: self.autoblend() for child in self.children: child.build() for child in self.children: child.open_imports(options) for child in self.children: child.dereference() log.debug('loaded:\n%s', self) merged = self.merge() log.debug('MERGED:\n%s...
'Ensure that all schemas within the collection import each other which has a blending effect. @return: self @rtype: L{SchemaCollection}'
def autoblend(self):
namespaces = self.namespaces.keys() for s in self.children: for ns in namespaces: tns = s.root.get('targetNamespace') if (tns == ns): continue for imp in s.root.getChildren('import'): if (imp.get('namespace') == ns): ...
'Find a schema by namespace. Only the URI portion of the namespace is compared to each schema\'s I{targetNamespace} @param ns: A namespace. @type ns: (prefix,URI) @return: The schema matching the namesapce, else None. @rtype: L{Schema}'
def locate(self, ns):
return self.namespaces.get(ns[1])
'Merge the contained schemas into one. @return: The merged schema. @rtype: L{Schema}'
def merge(self):
if len(self): schema = self.children[0] for s in self.children[1:]: schema.merge(s) return schema else: return None
'@param root: The xml root. @type root: L{sax.element.Element} @param baseurl: The base url used for importing. @type baseurl: basestring @param options: An options dictionary. @type options: L{options.Options} @param container: An optional container. @type container: L{SchemaCollection}'
def __init__(self, root, baseurl, options, container=None):
self.root = root self.id = objid(self) self.tns = self.mktns() self.baseurl = baseurl self.container = container self.children = [] self.all = [] self.types = {} self.imports = [] self.elements = {} self.attributes = {} self.groups = {} self.agrps = {} if (options...
'Make the schema\'s target namespace. @return: The namespace representation of the schema\'s targetNamespace value. @rtype: (prefix, uri)'
def mktns(self):
tns = [None, self.root.get('targetNamespace')] if (tns[1] is not None): tns[0] = self.root.findPrefix(tns[1]) return tuple(tns)
'Build the schema (object graph) using the root node using the factory. - Build the graph. - Collate the children.'
def build(self):
self.children = BasicFactory.build(self.root, self) collated = BasicFactory.collate(self.children) self.children = collated[0] self.attributes = collated[2] self.imports = collated[1] self.elements = collated[3] self.types = collated[4] self.groups = collated[5] self.agrps = collated...
'Merge the contents from the schema. Only objects not already contained in this schema\'s collections are merged. This is to provide for bidirectional import which produce cyclic includes. @returns: self @rtype: L{Schema}'
def merge(self, schema):
for item in schema.attributes.items(): if (item[0] in self.attributes): continue self.all.append(item[1]) self.attributes[item[0]] = item[1] for item in schema.elements.items(): if (item[0] in self.elements): continue self.all.append(item[1]) ...
'Instruct all contained L{sxbasic.Import} children to import the schema\'s which they reference. The contents of the imported schema are I{merged} in. @param options: An options dictionary. @type options: L{options.Options}'
def open_imports(self, options):
for imp in self.imports: imported = imp.open(options) if (imported is None): continue imported.open_imports(options) log.debug('imported:\n%s', imported) self.merge(imported)
'Instruct all children to perform dereferencing.'
def dereference(self):
all = [] indexes = {} for child in self.children: child.content(all) deplist = DepList() for x in all: x.qualify() (midx, deps) = x.dependencies() item = (x, tuple(deps)) deplist.add(item) indexes[x] = midx for (x, deps) in deplist.sort(): ...
'Find a schema by namespace. Only the URI portion of the namespace is compared to each schema\'s I{targetNamespace}. The request is passed to the container. @param ns: A namespace. @type ns: (prefix,URI) @return: The schema matching the namesapce, else None. @rtype: L{Schema}'
def locate(self, ns):
if (self.container is not None): return self.container.locate(ns) else: return None
'Get whether the specified reference is B{not} an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if B{not} a builtin, else False. @rtype: bool'
def custom(self, ref, context=None):
if (ref is None): return True else: return (not self.builtin(ref, context))
'Get whether the specified reference is an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if builtin, else False. @rtype: bool'
def builtin(self, ref, context=None):
w3 = 'http://www.w3.org' try: if isqref(ref): ns = ref[1] return ((ref[0] in Factory.tags) and ns.startswith(w3)) if (context is None): context = self.root prefix = splitPrefix(ref)[0] prefixes = context.findPrefixes(w3, 'startswith') r...
'Create and return an new schema object using the specified I{root} and I{url}. @param root: A schema root node. @type root: L{sax.element.Element} @param baseurl: A base URL. @type baseurl: str @param options: An options dictionary. @type options: L{options.Options} @return: The newly created schema object. @rtype: L{...
def instance(self, root, baseurl, options):
return Schema(root, baseurl, options)
'Examine and repair the schema (if necessary). @param root: A schema root element. @type root: L{Element}'
def examine(self, root):
pass
'Add a doctor to the practice @param doctor: A doctor to add. @type doctor: L{Doctor}'
def add(self, doctor):
self.doctors.append(doctor)
'@param tns: A list of target namespaces. @type tns: [str,...]'
def __init__(self, *tns):
self.tns = [] self.add(*tns)
'Add I{targetNamesapces} to be added. @param tns: A list of target namespaces. @type tns: [str,...]'
def add(self, *tns):
self.tns += tns
'Match by I{targetNamespace} excluding those that are equal to the specified namespace to prevent adding an import to itself. @param root: A schema root. @type root: L{Element}'
def match(self, root, ns):
tns = root.get('targetNamespace') if len(self.tns): matched = (tns in self.tns) else: matched = 1 itself = (ns == tns) return (matched and (not itself))
'@param ns: An import namespace. @type ns: str @param location: An optional I{schemaLocation}. @type location: str'
def __init__(self, ns, location=None):
self.ns = ns self.location = location self.filter = TnsFilter()
'Set the filter. @param filter: A filter to set. @type filter: L{TnsFilter}'
def setfilter(self, filter):
self.filter = filter
'Apply the import (rule) to the specified schema. If the schema does not already contain an import for the I{namespace} specified here, it is added. @param root: A schema root. @type root: L{Element}'
def apply(self, root):
if (not self.filter.match(root, self.ns)): return if self.exists(root): return node = Element('import', ns=self.xsdns) node.set('namespace', self.ns) if (self.location is not None): node.set('schemaLocation', self.location) log.debug('inserting: %s', node) root.ins...
'Add an <xs:import/> to the specified schema root. @param root: A schema root. @type root: L{Element}'
def add(self, root):
node = Element('import', ns=self.xsdns) node.set('namespace', self.ns) if (self.location is not None): node.set('schemaLocation', self.location) log.debug('%s inserted', node) root.insert(node)
'Check to see if the <xs:import/> already exists in the specified schema root by matching I{namesapce}. @param root: A schema root. @type root: L{Element}'
def exists(self, root):
for node in root.children: if (node.name != 'import'): continue ns = node.get('namespace') if (self.ns == ns): return 1 return 0
''
def __init__(self, *imports):
self.imports = [] self.add(*imports)
'Add a namesapce to be checked. @param imports: A list of L{Import} objects. @type imports: [L{Import},..]'
def add(self, *imports):
self.imports += imports
'Get the I{type} qualified reference to the referenced xsd type. This method takes into account simple types defined through restriction with are detected by determining that self is simple (len=0) and by finding a restriction child. @return: The I{type} qualified reference. @rtype: qref'
def qref(self):
qref = self.type if ((qref is None) and (len(self) == 0)): ls = [] m = RestrictionMatcher() finder = NodeFinder(m, 1) finder.find(self, ls) if len(ls): return ls[0].ref return qref
'Set the type as any when implicit. An implicit <xs:any/> is when an element has not body and no type defined. @return: self @rtype: L{Element}'
def implany(self):
if ((self.type is None) and (self.ref is None) and self.root.isempty()): self.type = self.anytype() return self
'create an xsd:anyType reference'
def anytype(self):
(p, u) = Namespace.xsdns mp = self.root.findPrefix(u) if (mp is None): mp = p self.root.addPrefix(p, u) return ':'.join((mp, 'anyType'))
'Bind a namespace to a schema location (URI). This is used for imports that don\'t specify a schemaLocation. @param ns: A namespace-uri. @type ns: str @param location: The (optional) schema location for the namespace. (default=ns). @type location: str'
@classmethod def bind(cls, ns, location=None):
if (location is None): location = ns cls.locations[ns] = location
'Open and import the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema}'
def open(self, options):
if self.opened: return self.opened = True log.debug('%s, importing ns="%s", location="%s"', self.id, self.ns[1], self.location) result = self.locate() if (result is None): if (self.location is None): log.debug('imported schema (%s) not-found', self.ns[1]...
'find the schema locally'
def locate(self):
if (self.ns[1] == self.schema.tns[1]): return None else: return self.schema.locate(self.ns)
'download the schema'
def download(self, options):
url = self.location try: if ('://' not in url): url = urljoin(self.schema.baseurl, url) reader = DocumentReader(options) d = reader.open(url) root = d.root() root.set('url', url) return self.schema.instance(root, url, options) except TransportError...
'Open and include the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema}'
def open(self, options):
if self.opened: return self.opened = True log.debug('%s, including location="%s"', self.id, self.location) result = self.download(options) log.debug('included:\n%s', result) return result
'download the schema'
def download(self, options):
url = self.location try: if ('://' not in url): url = urljoin(self.schema.baseurl, url) reader = DocumentReader(options) d = reader.open(url) root = d.root() root.set('url', url) self.__applytns(root) return self.schema.instance(root, url, opti...
'make sure included schema has same tns.'
def __applytns(self, root):
TNS = 'targetNamespace' tns = root.get(TNS) if (tns is None): tns = self.schema.tns[1] root.set(TNS, tns) elif (self.schema.tns[1] != tns): raise Exception, ('%s mismatch' % TNS)
'Gets the <xs:attribute default=""/> attribute value. @return: The default value for the attribute @rtype: str'
def get_default(self):
return self.root.get('default', default='')
'Map (override) tag => I{class} mapping. @param tag: An xsd tag name. @type tag: str @param fn: A function or class. @type fn: fn|class.'
@classmethod def maptag(cls, tag, fn):
cls.tags[tag] = fn
'Create an object based on the root tag name. @param root: An XML root element. @type root: L{Element} @param schema: A schema object. @type schema: L{schema.Schema} @return: The created object. @rtype: L{SchemaObject}'
@classmethod def create(cls, root, schema):
fn = cls.tags.get(root.name) if (fn is not None): return fn(schema, root) else: return None
'Build an xsobject representation. @param root: An schema XML root. @type root: L{sax.element.Element} @param filter: A tag filter. @type filter: [str,...] @return: A schema object graph. @rtype: L{sxbase.SchemaObject}'
@classmethod def build(cls, root, schema, filter=('*',)):
children = [] for node in root.getChildren(ns=Namespace.xsdns): if (('*' in filter) or (node.name in filter)): child = cls.create(node, schema) if (child is None): continue children.append(child) c = cls.build(node, schema, child.childtags(...
'@param options: An options object. @type options: I{Options}'
def __init__(self, options):
self.options = options self.plugins = PluginContainer(options.plugins)
'Mangle the name by hashing the I{name} and appending I{x}. @return: the mangled name.'
def mangle(self, name, x):
h = abs(hash(name)) return ('%s-%s' % (h, x))
'Open an XML document at the specified I{url}. First, the document attempted to be retrieved from the I{object cache}. If not found, it is downloaded and parsed using the SAX parser. The result is added to the cache for the next open(). @param url: A document url. @type url: str. @return: The specified XML document. ...
def open(self, url):
cache = self.cache() id = self.mangle(url, 'document') d = cache.get(id) if (d is None): d = self.download(url) cache.put(id, d) self.plugins.document.parsed(url=url, document=d.root()) return d
'Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like'
def download(self, url):
store = DocumentStore() fp = store.open(url) if (fp is None): fp = self.options.transport.open(Request(url)) content = fp.read() fp.close() ctx = self.plugins.document.loaded(url=url, document=content) content = ctx.document sax = Parser() return sax.parse(string=content)
'Get the cache. @return: The I{options} when I{cachingpolicy} = B{0}. @rtype: L{Cache}'
def cache(self):
if (self.options.cachingpolicy == 0): return self.options.cache else: return NoCache()
'@param options: An options object. @type options: I{Options} @param fn: A factory function (constructor) used to create the object not found in the cache. @type fn: I{Constructor}'
def __init__(self, options, fn):
Reader.__init__(self, options) self.fn = fn
'Open a WSDL at the specified I{url}. First, the WSDL attempted to be retrieved from the I{object cache}. After unpickled from the cache, the I{options} attribute is restored. If not found, it is downloaded and instantiated using the I{fn} constructor and added to the cache for the next open(). @param url: A WSDL url....
def open(self, url):
cache = self.cache() id = self.mangle(url, 'wsdl') d = cache.get(id) if (d is None): d = self.fn(url, self.options) cache.put(id, d) else: d.options = self.options for imp in d.imports: imp.imported.options = self.options return d
'Get the cache. @return: The I{options} when I{cachingpolicy} = B{1}. @rtype: L{Cache}'
def cache(self):
if (self.options.cachingpolicy == 1): return self.options.cache else: return NoCache()
'Get a object from the cache by ID. @param id: The object ID. @type id: str @return: The object, else None @rtype: any'
def get(self, id):
raise Exception('not-implemented')
'Get a object from the cache by ID. @param id: The object ID. @type id: str @return: The object, else None @rtype: any'
def getf(self, id):
raise Exception('not-implemented')
'Put a object into the cache. @param id: The object ID. @type id: str @param object: The object to add. @type object: any'
def put(self, id, object):
raise Exception('not-implemented')
'Write a fp into the cache. @param id: The object ID. @type id: str @param fp: File pointer. @type fp: file-like object.'
def putf(self, id, fp):
raise Exception('not-implemented')
'Purge a object from the cache by id. @param id: A object ID. @type id: str'
def purge(self, id):
raise Exception('not-implemented')
'Clear all objects from the cache.'
def clear(self):
raise Exception('not-implemented')
'@param location: The directory for the cached files. @type location: str @param duration: The cached file duration which defines how long the file will be cached. A duration=0 means forever. The duration may be: (months|weeks|days|hours|minutes|seconds). @type duration: {unit:value}'
def __init__(self, location=None, **duration):
if (location is None): location = os.path.join(tmp(), 'suds') self.location = location self.duration = (None, 0) self.setduration(**duration) self.checkversion()
'Get the file name suffix @return: The suffix @rtype: str'
def fnsuffix(self):
return 'gcf'
'Set the caching duration which defines how long the file will be cached. @param duration: The cached file duration which defines how long the file will be cached. A duration=0 means forever. The duration may be: (months|weeks|days|hours|minutes|seconds). @type duration: {unit:value}'
def setduration(self, **duration):
if (len(duration) == 1): arg = duration.items()[0] if (not (arg[0] in self.units)): raise Exception(('must be: %s' % str(self.units))) self.duration = arg return self
'Set the location (directory) for the cached files. @param location: The directory for the cached files. @type location: str'
def setlocation(self, location):
self.location = location
'Make the I{location} directory if it doesn\'t already exits.'
def mktmp(self):
try: if (not os.path.isdir(self.location)): os.makedirs(self.location) except: log.debug(self.location, exc_info=1) return self
'Validate that the file has not expired based on the I{duration}. @param fn: The file name. @type fn: str'
def validate(self, fn):
if (self.duration[1] < 1): return created = dt.fromtimestamp(os.path.getctime(fn)) d = {self.duration[0]: self.duration[1]} expired = (created + timedelta(**d)) if (expired < dt.now()): log.debug('%s expired, deleted', fn) os.remove(fn)
'Open the cache file making sure the directory is created.'
def open(self, fn, *args):
self.mktmp() return open(fn, *args)
'Ensure JWT login view using JSON POST works.'
def test_jwt_login_custom_response_json(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username) ...
'Ensure JWT login view using JSON POST works.'
def test_jwt_login_json(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, format='json') decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username)
'Ensure JWT login view using JSON POST fails if bad credentials are used.'
def test_jwt_login_json_bad_creds(self):
client = APIClient(enforce_csrf_checks=True) self.data['password'] = 'wrong' response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, 400)
'Ensure JWT login view using JSON POST fails if missing fields.'
def test_jwt_login_json_missing_fields(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', {'username': self.username}, format='json') self.assertEqual(response.status_code, 400)
'Ensure JWT login view using form POST works.'
def test_jwt_login_form(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(decoded_payload['username'], self.username)
'Ensure JWT login view works even if expired token is provided'
def test_jwt_login_with_expired_token(self):
payload = utils.jwt_payload_handler(self.user) payload['exp'] = 1 token = utils.jwt_encode_handler(payload) auth = 'JWT {0}'.format(token) client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, HTTP_AUTHORIZATION=auth, format='json') decoded_payload...
'Test to reproduce issue #33'
def test_jwt_login_using_zero(self):
client = APIClient(enforce_csrf_checks=True) data = {'username': '0', 'password': '0'} response = client.post('/auth-token/', data, format='json') self.assertEqual(response.status_code, 400)
'Ensure JWT login view using JSON POST works.'
def test_jwt_login_json(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(decoded_payload['email'], self.email)
'Ensure JWT login view using JSON POST fails if bad credentials are used.'
def test_jwt_login_json_bad_creds(self):
client = APIClient(enforce_csrf_checks=True) self.data['password'] = 'wrong' response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, 400)
'Ensure JWT login view using JSON POST works.'
def test_jwt_login_json(self):
client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) decoded_payload = utils.jwt_decode_handler(response.data['token']) self.assertEqual(decoded_payload['user_id'], str(self.user.id))
'Ensure JWT login view using JSON POST fails if bad credentials are used.'
def test_jwt_login_json_bad_creds(self):
client = APIClient(enforce_csrf_checks=True) self.data['password'] = 'wrong' response = client.post('/auth-token/', self.data, format='json') self.assertEqual(response.status_code, 400)
'Test that a valid, non-expired token will return a 200 response and itself when passed to the validation endpoint.'
def test_verify_jwt(self):
client = APIClient(enforce_csrf_checks=True) orig_token = self.get_token() response = client.post('/auth-token-verify/', {'token': orig_token}, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['token'], orig_token)
'Test that an expired token will fail with the correct error.'
def test_verify_jwt_fails_with_expired_token(self):
client = APIClient(enforce_csrf_checks=True) token = self.create_token(self.user, exp=(datetime.utcnow() - timedelta(seconds=5)), orig_iat=(datetime.utcnow() - timedelta(hours=1))) response = client.post('/auth-token-verify/', {'token': token}, format='json') self.assertEqual(response.status_code, statu...
'Test that an invalid token will fail with the correct error.'
def test_verify_jwt_fails_with_bad_token(self):
client = APIClient(enforce_csrf_checks=True) token = 'i am not a correctly formed token' response = client.post('/auth-token-verify/', {'token': token}, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertRegexpMatches(response.data['non_fi...
'Test that an invalid token will fail with a user that does not exist.'
def test_verify_jwt_fails_with_missing_user(self):
client = APIClient(enforce_csrf_checks=True) user = User.objects.create_user(email='jsmith@example.com', username='jsmith', password='password') token = self.create_token(user) user.delete() response = client.post('/auth-token-verify/', {'token': token}, format='json') self.assertEqual(response....
'Test that a token can be signed with asymmetrics keys'
def test_verify_jwt_with_pub_pvt_key(self):
client = APIClient(enforce_csrf_checks=True) orig_token = self.get_token() response = client.post('/auth-token-verify/', {'token': orig_token}, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['token'], orig_token)
'Test that an expired token will fail with the correct error.'
def test_verify_jwt_fails_with_expired_token(self):
client = APIClient(enforce_csrf_checks=True) token = self.create_token(self.user, exp=(datetime.utcnow() - timedelta(seconds=5)), orig_iat=(datetime.utcnow() - timedelta(hours=1))) response = client.post('/auth-token-verify/', {'token': token}, format='json') self.assertEqual(response.status_code, statu...
'Test that an invalid token will fail with the correct error.'
def test_verify_jwt_fails_with_bad_token(self):
client = APIClient(enforce_csrf_checks=True) token = 'i am not a correctly formed token' response = client.post('/auth-token-verify/', {'token': token}, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertRegexpMatches(response.data['non_fi...
'Test that an mismatched private key token will fail with the correct error.'
def test_verify_jwt_fails_with_bad_pvt_key(self):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) api_settings.JWT_PRIVATE_KEY = private_key client = APIClient(enforce_csrf_checks=True) orig_token = self.get_token() response = client.post('/auth-token-verify/', {'token': orig_token}, format='j...