5. Other Packages

PyTan relies on a number of python packages to function properly. All dependencies are bundled with PyTan in order to make it easier for the user to start using PyTan right away.

5.1. requests Package

PyTan uses requests for all HTTP requests in order to get automatic keep alive support, session tracking, and a host of other things. requests is an open source package maintained at: https://github.com/kennethreitz/requests

5.1.1. Requests HTTP library

Requests is an HTTP library, written in Python, for human beings. Basic GET usage:

>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True

... or POST:

>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

The other HTTP methods are supported - see requests.api. Full documentation is at <http://python-requests.org>.

copyright:
  1. 2015 by Kenneth Reitz.
license:

Apache 2.0, see LICENSE for more details.

5.2. threaded_http Package

PyTan uses threaded_http to create a fake HTTP server on localhost for the invalid server functional tests (see: pytan.test_pytan_invalid_server_tests). threaded_http is developed and maintained by Tanium.

Simple HTTP server for testing purposes

class threaded_http.CustomHTTPHandler(request, client_address, server)[source]

Bases: BaseHTTPServer.BaseHTTPRequestHandler

ENABLE_LOGGING = True
do_GET()[source]
do_POST()[source]
log_message(format, *args)[source]
class threaded_http.ThreadedHTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)[source]

Bases: SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer

Handle requests in a separate thread.

threaded_http.threaded_http(host='localhost', port=4443, verbosity=2)[source]

establishes an HTTP server on host:port in a thread

5.3. xmltodict Package

PyTan uses xmltodict for pretty printing XML documents (see: pytan.utils.xml_pretty()). xmltodict is an open source package maintained at: https://github.com/martinblech/xmltodict

Makes working with XML feel like you are working with JSON

xmltodict.parse(xml_input, encoding=None, expat=<module 'xml.parsers.expat' from '/Library/Python/2.7/site-packages/_xmlplus/parsers/expat.pyc'>, process_namespaces=False, namespace_separator=':', **kwargs)[source]

Parse the given XML input and convert it into a dictionary.

xml_input can either be a string or a file-like object.

If xml_attribs is True, element attributes are put in the dictionary among regular child elements, using @ as a prefix to avoid collisions. If set to False, they are just ignored.

Simple example:

>>> import xmltodict
>>> doc = xmltodict.parse("""
... <a prop="x">
...   <b>1</b>
...   <b>2</b>
... </a>
... """)
>>> doc['a']['@prop']
u'x'
>>> doc['a']['b']
[u'1', u'2']

If item_depth is 0, the function returns a dictionary for the root element (default behavior). Otherwise, it calls item_callback every time an item at the specified depth is found and returns None in the end (streaming mode).

The callback function receives two parameters: the path from the document root to the item (name-attribs pairs), and the item (dict). If the callback’s return value is false-ish, parsing will be stopped with the ParsingInterrupted exception.

Streaming example:

>>> def handle(path, item):
...     print 'path:%s item:%s' % (path, item)
...     return True
...
>>> xmltodict.parse("""
... <a prop="x">
...   <b>1</b>
...   <b>2</b>
... </a>""", item_depth=2, item_callback=handle)
path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1
path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2

The optional argument postprocessor is a function that takes path, key and value as positional arguments and returns a new (key, value) pair where both key and value may have changed. Usage example:

>>> def postprocessor(path, key, value):
...     try:
...         return key + ':int', int(value)
...     except (ValueError, TypeError):
...         return key, value
>>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>',
...                 postprocessor=postprocessor)
OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))])

You can pass an alternate version of expat (such as defusedexpat) by using the expat parameter. E.g:

>>> import defusedexpat
>>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat)
OrderedDict([(u'a', u'hello')])
xmltodict.unparse(input_dict, output=None, encoding='utf-8', full_document=True, **kwargs)[source]

Emit an XML document for the given input_dict (reverse of parse).

The resulting XML document is returned as a string, but if output (a file-like object) is specified, it is written there instead.

Dictionary keys prefixed with attr_prefix (default=`’@’) are interpreted as XML node attributes, whereas keys equal to `cdata_key (default=`’#text’`) are treated as character data.

The pretty parameter (default=`False`) enables pretty-printing. In this mode, lines are terminated with ‘n’ and indented with ‘t’, but this can be customized with the newl and indent parameters.

5.4. ddt Package

PyTan uses ddt for creating automatically generating test cases from JSON files (see: pytan.test_pytan_valid_server_tests). ddt is an open source package maintained at: https://github.com/txels/ddt

ddt.data(*values)[source]

Method decorator to add to your test methods.

Should be added to methods of instances of unittest.TestCase.

ddt.ddt(cls)[source]

Class decorator for subclasses of unittest.TestCase.

Apply this decorator to the test case class, and then decorate test methods with @data.

For each method decorated with @data, this will effectively create as many methods as data items are passed as parameters to @data.

The names of the test methods follow the pattern original_test_name_{ordinal}_{data}. ordinal is the position of the data argument, starting with 1.

For data we use a string representation of the data value converted into a valid python identifier. If data.__name__ exists, we use that instead.

For each method decorated with @file_data('test_data.json'), the decorator will try to load the test_data.json file located relative to the python file containing the method that is decorated. It will, for each test_name key create as many methods in the list of values from the data key.

ddt.file_data(value)[source]

Method decorator to add to your test methods.

Should be added to methods of instances of unittest.TestCase.

value should be a path relative to the directory of the file containing the decorated unittest.TestCase. The file should contain JSON encoded data, that can either be a list or a dict.

In case of a list, each value in the list will correspond to one test case, and the value will be concatenated to the test method name.

In case of a dict, keys will be used as suffixes to the name of the test case, and values will be fed as test data.

ddt.is_hash_randomized()[source]
ddt.mk_test_name(name, value, index=0)[source]

Generate a new name for a test case.

It will take the original test name and append an ordinal index and a string representation of the value, and convert the result into a valid python identifier by replacing extraneous characters with _.

If hash randomization is enabled (a feature available since 2.7.3/3.2.3 and enabled by default since 3.3) and a “non-trivial” value is passed this will omit the name argument by default. Set PYTHONHASHSEED to a fixed value before running tests in these cases to get the names back consistently or use the __name__ attribute on data values.

A “trivial” value is a plain scalar, or a tuple or list consisting only of trivial values.

ddt.unpack(func)[source]

Method decorator to add unpack feature.

5.5. pyreadline Package

PyTan uses pyreadline for providing tab completion within pytan_shell.py/.bat on Windows (see: pytan.binsupport.HistoryConsole). pyreadline is stored in winlb/ instead of lib/ since it should only be imported on Windows. pyreadline is an open source package maintained at: https://pypi.python.org/pypi/pyreadline/2.0