ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2762

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

58. PYRAMID.SETTINGS

656

CHAPTER

FIFTYNINE

PYRAMID.TESTING

setUp(registry=None, request=None, hook_zca=True, autocommit=True, settings=None)

Set Pyramid registry and request thread locals for the duration of a single unit test.

Use this function in the setUp method of a unittest test case which directly or indirectly uses:

•any method of the pyramid.config.Configurator object returned by this function.

•the pyramid.threadlocal.get_current_registry() or pyramid.threadlocal.get_current_request() functions.

If you use the get_current_* functions (or call Pyramid code that uses these functions) without calling setUp, pyramid.threadlocal.get_current_registry() will return a global application registry, which may cause unit tests to not be isolated with respect to registrations they perform.

If the registry argument is None, a new empty application registry will be created (an instance of the pyramid.registry.Registry class). If the registry argument is not None, the value passed in should be an instance of the pyramid.registry.Registry class or a suitable testing analogue.

After setUp is finished, the registry returned by the pyramid.threadlocal.get_current_request() function will be the passed (or constructed) registry until pyramid.testing.tearDown() is called (or pyramid.testing.setUp() is called again) .

If

the hook_zca argument

is True,

setUp will attempt to per-

form

the

operation

zope.component.getSiteManager.sethook(

657


59. PYRAMID.TESTING

pyramid.threadlocal.get_current_registry), which will cause the Zope Component Architecture global API (e.g. zope.component.getSiteManager(), zope.component.getAdapter(), and so on) to use the registry constructed by setUp as the value it returns from zope.component.getSiteManager(). If the zope.component package cannot be imported, or if hook_zca is False, the hook will not be set.

If settings is not None, it must be a dictionary representing the values passed to a Configurator as its settings= argument.

This

function

returns an

instance of the pyramid.config.Configurator

class,

which

can be

used

for further configuration to set

up an environment suitable

for

a

unit or integration

test.

The registry attribute

attached to the Configurator

in-

stance

represents the

‘current’ application registry; the

same registry will be returned

by

pyramid.threadlocal.get_current_registry() during the execution of the test.

 

tearDown(unhook_zca=True)

Undo the effects pyramid.testing.setUp(). Use this function in the tearDown method of a unit test that uses pyramid.testing.setUp() in its setUp method.

If the unhook_zca argument is True (the default), call zope.component.getSiteManager.reset(). This undoes the action of pyramid.testing.setUp() called with the argument hook_zca=True. If zope.component cannot be imported, ignore the argument.

cleanUp(*arg, **kw)

pyramid.testing.cleanUp() is an alias for pyramid.testing.setUp().

class DummyResource(__name__=None, __parent__=None, __provides__=None, **kw)

A dummy Pyramid resource object.

clone(__name__=<object object at 0x57db0b0>, __parent__=<object object at

0x57db0b0>, **kw)

Create a clone of the resource object. If __name__ or __parent__ arguments are passed, use these values to override the existing __name__ or __parent__ of the resource. If any extra keyword args are passed in via the kw argument, use these keywords to add to or override existing resource keywords (attributes).

items()

Return the items set by __setitem__

keys()

Return the keys set by __setitem__

values()

Return the values set by __setitem__

658


class DummyRequest(params=None, environ=None, headers=None, path=’/’, cookies=None,

post=None, **kw)

A DummyRequest object (incompletely) imitates a request object.

The params, environ, headers, path, and cookies arguments correspond to their WebOb equivalents.

The post argument, if passed, populates the request’s POST attribute, but not params, in order to allow testing that the app accepts data for a given view only from POST requests. This argument also sets self.method to “POST”.

Extra keyword arguments are assigned as attributes of the request itself.

Note that DummyRequest does not have complete fidelity with a “real” request. For example, by default, the DummyRequest GET and POST attributes are of type dict, unlike a normal Request’s GET and POST, which are of type MultiDict. If your code uses the features of MultiDict, you should either use a”real” pyramid.request.Request or adapt your DummyRequest by replacing the attributes with MultiDict instances.

Other similar incompatibilities exist. If you need all the features of a Request, use the pyramid.request.Request class itself rather than this class while writing tests.

class DummyTemplateRenderer(string_response=’‘)

An instance of this class is returned from pyramid.config.Configurator.testing_add_renderer

It has a helper function (assert_) that makes it possible to make an assertion which compares data passed to the renderer by the view function against expected key/value pairs.

assert_(**kw)

Accept an arbitrary set of assertion key/value pairs. For each assertion key/value pair assert that the renderer (eg. pyramid.renderer.render_to_response()) received the key with a value that equals the asserted value. If the renderer did not receive the key at all, or the value received by the renderer doesn’t match the assertion value, raise an

AssertionError.

659

59. PYRAMID.TESTING

660


CHAPTER

SIXTY

PYRAMID.THREADLOCAL

get_current_request()

Return the currently active request or None if no request is currently active.

This function should be used extremely sparingly, usually only in unit testing code. it’s almost always usually a mistake to use get_current_request outside a testing context because its usage makes it possible to write code that can be neither easily tested nor scripted.

get_current_registry()

Return the currently active application registry or the global application registry if no request is currently active.

This function should be used extremely sparingly, usually only in unit testing code. it’s almost always usually a mistake to use get_current_registry outside a testing context because its usage makes it possible to write code that can be neither easily tested nor scripted.

661

60. PYRAMID.THREADLOCAL

662

CHAPTER

SIXTYONE

PYRAMID.TRAVERSAL

find_interface(resource, class_or_interface)

Return the first resource found in the lineage of resource which, a) if class_or_interface is a Python class object, is an instance of the class or any subclass of that class or b) if class_or_interface is a interface, provides the specified interface. Return None if no resource providing interface_or_class can be found in the lineage. The resource passed in must be location-aware.

find_resource(resource, path)

Given a resource object and a string or tuple representing a path (such as the return value of pyramid.traversal.resource_path() or pyramid.traversal.resource_path_tuple()), return a resource in this application’s resource tree at the specified path. The resource passed in must be location-aware. If the path cannot be resolved (if the respective node in the resource tree does not exist), a KeyError will be raised.

This function is the logical inverse of pyramid.traversal.resource_path() and pyramid.traversal.resource_path_tuple(); it can resolve any path string or tuple generated by either of those functions.

Rules for passing a string as the path argument: if the first character in the path string is the / character, the path is considered absolute and the resource tree traversal will start at the root resource. If the first character of the path string is not the / character, the path is considered relative and resource tree traversal will begin at the resource object supplied to the function as the resource argument. If an empty string is passed as path, the resource passed in will be returned. Resource path strings must be escaped in the following manner: each Unicode path segment must be encoded as UTF-8 and as each path segment must escaped via Python’s urllib.quote. For example,

663


61. PYRAMID.TRAVERSAL

/path/to%20the/La%20Pe%C3%B1a (absolute) or to%20the/La%20Pe%C3%B1a (relative). The pyramid.traversal.resource_path() function generates strings which follow these rules (albeit only absolute ones).

Rules for passing text (Unicode) as the path argument are the same as those for a string. In particular, the text may not have any nonascii characters in it.

Rules for passing a tuple as the path argument: if the first element in the path tuple is the empty string (for example (”, ’a’, ’b’, ’c’), the path is considered absolute and the resource tree traversal will start at the resource tree root object. If the first element in the path tuple is not the empty string (for example (’a’, ’b’, ’c’)), the path is considered relative and resource tree traversal will begin at the resource object supplied to the function as the resource argument. If an empty sequence is passed as path, the resource passed in itself will be returned. No URL-quoting or UTF-8-encoding of individual path segments within the tuple is required (each segment may be any string or unicode object representing a resource name). Resource path tuples generated by pyramid.traversal.resource_path_tuple() can always be resolved by find_resource.

latex-note.png

For backwards compatibility purposes, this function can also be imported as pyramid.traversal.find_model(), although doing so will emit a deprecation warning.

find_root(resource)

Find the root node in the resource tree to which resource belongs. Note that resource should be location-aware. Note that the root resource is available in the request object by accessing the request.root attribute.

resource_path(resource, *elements)

Return a string object representing the absolute physical path of the resource object based on its position in the resource tree, e.g /foo/bar. Any positional arguments passed in as elements will be appended as path segments to the end of the resource path. For instance, if the resource’s path is

/foo/bar and elements equals (’a’, ’b’), the returned string will be /foo/bar/a/b. The first character in the string will always be the / character (a leading / character in a path string represents that the path is absolute).

Resource path strings returned will be escaped in the following manner: each unicode path segment will be encoded as UTF-8 and each path segment will be escaped via Python’s urllib.quote. For example, /path/to%20the/La%20Pe%C3%B1a.

664

This function is a logical inverse of pyramid.traversal.find_resource: it can be used to generate path references that can later be resolved via that function.

The resource passed in must be location-aware.

latex-note.png

Each segment in the path string returned will use the __name__ attribute of the resource it represents within the resource tree. Each of these segments should be a unicode or string object (as per the contract of location-awareness). However, no conversion or safety checking of resource names is performed. For instance, if one of the resources in your tree has a __name__ which (by error) is a dictionary, the pyramid.traversal.resource_path() function will attempt to append it to a string and it will cause a pyramid.exceptions.URLDecodeError.

latex-note.png

The root resource must have a __name__ attribute with a value of either None or the empty string for paths to be generated properly. If the root resource has a nonnull __name__ attribute, its name will be prepended to the generated path rather than a single leading ‘/’ character.

latex-note.png

For backwards compatibility purposes, this function can also be imported as model_path, although doing so will cause a deprecation warning to be emitted.

resource_path_tuple(resource, *elements)

Return a tuple representing the absolute physical path of the resource object based on its position in a resource tree, e.g (”, ’foo’, ’bar’). Any positional arguments passed in as elements

665