tests.utils =========== .. py:module:: tests.utils Attributes ---------- .. autoapisummary:: tests.utils.TEST_INI_FILE tests.utils.TEST_CFG_FILE tests.utils.CURR_DIR tests.utils.LOGGER tests.utils.TestAppOrUrlType tests.utils.AnyTestItemType tests.utils._TestVersion tests.utils.LatestVersion tests.utils.AnyTestVersion Classes ------- .. autoapisummary:: tests.utils.TestAppContainer tests.utils.TestConfig tests.utils.TestVersion tests.utils.MockMagpieHandler tests.utils.MockAnyHandlerBase tests.utils.MockAnyHandler Functions --------- .. autoapisummary:: tests.utils.clear_handlers_instances tests.utils.config_setup_from_ini tests.utils.get_test_app tests.utils.get_app_or_url tests.utils.get_hostname tests.utils.get_headers tests.utils.get_response_content_types_list tests.utils.get_json_body tests.utils.json_msg tests.utils.mock_get_settings tests.utils.mock_request tests.utils.test_request tests.utils.visual_repr tests.utils.format_test_val_ref tests.utils.all_equal tests.utils.check_all_equal tests.utils.check_val_equal tests.utils.check_val_not_equal tests.utils.check_val_is_in tests.utils.check_val_not_in tests.utils.check_val_type tests.utils.check_raises tests.utils.check_no_raise tests.utils.check_response_basic_info tests.utils.check_error_param_structure tests.utils.check_path_permissions tests.utils.check_mock_has_calls Module Contents --------------- .. py:data:: TEST_INI_FILE .. py:data:: TEST_CFG_FILE .. py:data:: CURR_DIR .. py:data:: LOGGER .. py:class:: TestAppContainer Bases: :py:obj:`object` .. py:attribute:: test_app :type: Optional[webtest.app.TestApp] :value: None .. py:attribute:: app :type: Optional[webtest.app.TestApp] :value: None .. py:attribute:: url :type: Optional[str] :value: None .. py:data:: TestAppOrUrlType .. py:data:: AnyTestItemType .. py:type:: _TestVersion :canonical: 'TestVersion' .. py:data:: LatestVersion .. py:data:: AnyTestVersion .. py:class:: TestConfig Bases: :py:obj:`object` .. py:attribute:: grp :type: str .. py:attribute:: usr :type: str .. py:attribute:: pwd :type: str .. py:attribute:: url :type: str .. py:method:: load_config() -> None .. py:class:: TestVersion(vstring: AnyTestVersion) Bases: :py:obj:`packaging.version.Version` Special version supporting ``latest`` keyword to ignore safeguard check of :func:`warn_version` during development. .. seealso:: Environment variable ``COWBIRD_TEST_VERSION`` should be set with the desired version or ``latest`` to evaluate even new features above the last tagged version. Initialize a Version object. :param version: The string representation of a version which will be parsed and normalized before use. :raises InvalidVersion: If the ``version`` does not conform to PEP 440 in any way then this exception will be raised. .. py:attribute:: __test__ :value: False .. py:method:: _cmp(other: Any) -> int .. py:method:: __lt__(other: Any) -> bool .. py:method:: __le__(other: Any) -> bool .. py:method:: __gt__(other: Any) -> bool .. py:method:: __ge__(other: Any) -> bool .. py:method:: __eq__(other: Any) -> bool .. py:method:: __ne__(other: Any) -> bool .. py:property:: version :type: Union[Tuple[Union[int, str], Ellipsis], str] .. py:class:: MockMagpieHandler(settings, name, **kwargs) Bases: :py:obj:`cowbird.handlers.handler.Handler` Helper class that provides a standard way to create an ABC using inheritance. :param settings: Cowbird settings for convenience :param name: Handler name :param kwargs: The base class handle, but doesn't require the following variables: :param url: Location of the web service represented by the cowbird handler :param workspace_dir: Workspace directory :param priority: Relative priority between handlers while handling events. Lower value has higher priority, default value is last. .. py:attribute:: required_params :value: [] .. py:attribute:: event_users :value: [] .. py:attribute:: event_perms :value: [] .. py:attribute:: outbound_perms :value: [] .. py:method:: json() .. py:method:: get_user_list() .. py:method:: get_geoserver_workspace_res_id(user_name) .. py:method:: user_created(user_name) .. py:method:: user_deleted(user_name) .. py:method:: permission_created(permission) .. py:method:: permission_deleted(permission) .. py:method:: create_permission(permission) .. py:method:: delete_permission(permission) .. py:method:: delete_resource(res_id) .. py:method:: resync() .. py:method:: get_service_types() -> List[str] :staticmethod: Returns the list of service types available on Magpie. .. py:class:: MockAnyHandlerBase(settings: cowbird.typedefs.SettingsType, name: str, **kwargs: Any) Bases: :py:obj:`cowbird.handlers.handler.Handler` Helper class that provides a standard way to create an ABC using inheritance. :param settings: Cowbird settings for convenience :param name: Handler name :param kwargs: The base class handle, but doesn't require the following variables: :param url: Location of the web service represented by the cowbird handler :param workspace_dir: Workspace directory :param priority: Relative priority between handlers while handling events. Lower value has higher priority, default value is last. .. py:attribute:: ResourceId :value: 1000 .. py:method:: user_created(user_name) .. py:method:: user_deleted(user_name) .. py:method:: permission_created(permission) .. py:method:: permission_deleted(permission) .. py:method:: resync() .. py:class:: MockAnyHandler(settings: cowbird.typedefs.SettingsType, name: str, **kwargs: Any) Bases: :py:obj:`MockAnyHandlerBase` Helper class that provides a standard way to create an ABC using inheritance. :param settings: Cowbird settings for convenience :param name: Handler name :param kwargs: The base class handle, but doesn't require the following variables: :param url: Location of the web service represented by the cowbird handler :param workspace_dir: Workspace directory :param priority: Relative priority between handlers while handling events. Lower value has higher priority, default value is last. .. py:attribute:: required_params :value: [] .. py:function:: clear_handlers_instances() .. py:function:: config_setup_from_ini(config_ini_file_path) .. py:function:: get_test_app(settings: Optional[cowbird.typedefs.SettingsType] = None) -> webtest.app.TestApp Instantiate a local test application. .. py:function:: get_app_or_url(test_item: AnyTestItemType) -> TestAppOrUrlType Obtains the referenced test application, local application or remote URL from `Test Case` implementation. .. py:function:: get_hostname(test_item: AnyTestItemType) -> str Obtains stored hostname in the class implementation. .. py:function:: get_headers(app_or_url: TestAppOrUrlType, header_dict: cowbird.typedefs.AnyHeadersType) -> cowbird.typedefs.HeadersType Obtains stored headers in the class implementation. .. py:function:: get_response_content_types_list(response: cowbird.typedefs.AnyResponseType) -> List[str] Obtains the specified response Content-Type header(s) without additional formatting parameters. .. py:function:: get_json_body(response: cowbird.typedefs.AnyResponseType) -> cowbird.typedefs.JSON Obtains the JSON payload of the response regardless of its class implementation. .. py:function:: json_msg(json_body: cowbird.typedefs.JSON, msg: Optional[str] = null) -> str Generates a message string with formatted JSON body for display with easier readability. .. py:function:: mock_get_settings(test) Decorator to mock :func:`cowbird.utils.get_settings` to allow retrieval of settings from :class:`DummyRequest`. .. warning:: Only apply on test methods (not on class TestCase) to ensure that :mod:`pytest` can collect them correctly. .. py:function:: mock_request(request_path_query: str = '', method: str = 'GET', params: Optional[Dict[str, str]] = None, body: Union[str, cowbird.typedefs.JSON] = '', content_type: Optional[str] = None, headers: Optional[cowbird.typedefs.AnyHeadersType] = None, cookies: Optional[cowbird.typedefs.AnyCookiesType] = None, settings: cowbird.typedefs.SettingsType = None) -> pyramid.request.Request Generates a fake request with provided arguments. Can be employed by functions that expect a request object as input to retrieve details such as body content, the request path, or internal settings, but that no actual request needs to be accomplished. .. py:function:: test_request(test_item: AnyTestItemType, method: str, path: str, data: Optional[Union[cowbird.typedefs.JSON, str]] = None, json: Optional[Union[cowbird.typedefs.JSON, str]] = None, body: Optional[Union[cowbird.typedefs.JSON, str]] = None, params: Optional[Dict[str, str]] = None, timeout: int = 10, retries: int = 3, allow_redirects: bool = True, content_type: Optional[str] = None, headers: Optional[cowbird.typedefs.AnyHeadersType] = None, cookies: Optional[cowbird.typedefs.AnyCookiesType] = None, **kwargs: Any) -> cowbird.typedefs.AnyResponseType Calls the request using either a :class:`webtest.TestApp` instance or :class:`requests.Request` from a string URL. Keyword arguments :paramref:`json`, :paramref:`data` and :paramref:`body` are all looked for to obtain the data. Header ``Content-Type`` is set with respect to explicit :paramref:`json` or via provided :paramref:`headers` when available. Explicit :paramref:`content_type` can also be provided to override all of these. Request cookies are set according to :paramref:`cookies`, or can be interpreted from ``Set-Cookie`` header. .. warning:: When using :class:`TestApp`, some internal cookies can be stored from previous requests to retain the active user. Make sure to provide new set of cookies (or logout user explicitly) if different session must be used, otherwise they will be picked up automatically. For 'empty' cookies, provide an empty dictionary. :param test_item: one of `BaseTestCase`, `webtest.TestApp` or remote server URL to call with `requests` :param method: request method (GET, POST, PATCH, PUT, DELETE) :param path: test path starting at base path that will be appended to the application's endpoint. :param params: query parameters added to the request path. :param json: explicit JSON body content to use as request body. :param data: body content string to use as request body, can be JSON if matching ``Content-Type`` is identified. :param body: alias to :paramref:`data`. :param content_type: Enforce specific content-type of provided data body. Otherwise, attempt to retrieve it from request headers. Inferred JSON content-type when :paramref:`json` is employed, unless overridden explicitly. :param headers: Set of headers to send the request. Header ``Content-Type`` is looked for if not overridden. :param cookies: Cookies to provide to the request. :param timeout: passed down to :mod:`requests` when using URL, otherwise ignored (unsupported). :param retries: number of retry attempts in case the requested failed due to timeout (only when using URL). :param allow_redirects: Passed down to :mod:`requests` when using URL, handled manually for same behaviour when using :class:`TestApp`. :param kwargs: any additional keywords that will be forwarded to the request call. :returns: response of the request .. py:function:: visual_repr(item: Any) -> str .. py:function:: format_test_val_ref(val, ref, pre='Fail', msg=None) .. py:function:: all_equal(iter_val, iter_ref, any_order=False) .. py:function:: check_all_equal(iter_val: Collection[Any], iter_ref: Union[Collection[Any], cowbird.utils.NullType], msg: Optional[str] = None, any_order: bool = False) -> None :param iter_val: tested values. :param iter_ref: reference values. :param msg: override message to display if failing test. :param any_order: allow equal values to be provided in any order, otherwise order must match as well as values. :raises AssertionError: If all values in :paramref:`iter_val` are not equal to values within :paramref:`iter_ref`. If :paramref:`any_order` is ``False``, also raises if equal items are not in the same order. .. py:function:: check_val_equal(val: Any, ref: Union[Any, cowbird.utils.NullType], msg: Optional[str] = None) -> None :raises AssertionError: if :paramref:`val` is not equal to :paramref:`ref`. .. py:function:: check_val_not_equal(val: Any, ref: Union[Any, cowbird.utils.NullType], msg: Optional[str] = None) -> None :raises AssertionError: if :paramref:`val` is equal to :paramref:`ref`. .. py:function:: check_val_is_in(val: Any, ref: Union[Any, cowbird.utils.NullType], msg: Optional[str] = None) -> None :raises AssertionError: if :paramref:`val` is not in to :paramref:`ref`. .. py:function:: check_val_not_in(val: Any, ref: Union[Any, cowbird.utils.NullType], msg: Optional[str] = None) -> None :raises AssertionError: if :paramref:`val` is in to :paramref:`ref`. .. py:function:: check_val_type(val: Any, ref: Union[Type[Any], cowbird.utils.NullType, Iterable[Type[Any]]], msg: Optional[str] = None) -> None :raises AssertionError: if :paramref:`val` is not an instanced of :paramref:`ref`. .. py:function:: check_raises(func: Callable[[], Any], exception_type: Type[Exception], msg: Optional[str] = None) -> Exception Calls the callable and verifies that the specific exception was raised. :raise AssertionError: on failing exception check or missing raised exception. :returns: raised exception of expected type if it was raised. .. py:function:: check_no_raise(func: Callable[[], Any], msg: Optional[str] = None) -> Any Calls the callable and verifies that no exception was raised. :raise AssertionError: on any raised exception. .. py:function:: check_response_basic_info(response: cowbird.typedefs.AnyResponseType, expected_code: int = 200, expected_type: str = CONTENT_TYPE_JSON, expected_method: str = 'GET', extra_message: Optional[str] = None) -> Union[cowbird.typedefs.JSON, str] Validates basic `Cowbird` API response metadata. For UI pages, employ :func:`check_ui_response_basic_info` instead. If the expected content-type is JSON, further validations are accomplished with specific metadata fields that are always expected in the response body. Otherwise, minimal validation of basic fields that can be validated regardless of content-type is done. :param response: response to validate. :param expected_code: status code to validate from the response. :param expected_type: Content-Type to validate from the response. :param expected_method: method 'GET', 'POST', etc. to validate from the response if an error. :param extra_message: additional message to append to every specific test message if provided. :returns: json body of the response for convenience. .. py:function:: check_error_param_structure(body: cowbird.typedefs.JSON, param_value: Optional[Any] = null, param_name: Optional[str] = null, param_compare: Optional[Any] = null, param_name_exists: bool = False, param_compare_exists: bool = False) -> None Validates error response ``param`` information based on different Cowbird version formats. :param body: JSON body of the response to validate. :param param_value: Expected 'value' of param the parameter. Contained field value not verified if ``null``, only presence of the field. :param param_name: Expected 'name' of param. Ignored for older Cowbird version that did not provide this information. Contained field value not verified if ``null`` and ``param_name_exists`` is ``True`` (only its presence). If provided, automatically implies ``param_name_exists=True``. Skipped otherwise. :param param_compare: Expected 'compare'/'param_compare' value (filed name according to version) Contained field value not verified if ``null`` and ``param_compare_exists`` is ``True`` (only its presence). If provided, automatically implies ``param_compare_exists=True``. Skipped otherwise. :param param_name_exists: verify that 'name' is in the body, not validating its value. :param param_compare_exists: verify that 'compare'/'param_compare' is in the body, not validating its value. :raises AssertionError: on any failing condition .. py:function:: check_path_permissions(path: Union[str, os.PathLike], permissions: int, check_others_only: bool = False) -> None Checks if the path has the right permissions, by verifying the last digits of the octal permissions. .. py:function:: check_mock_has_calls(mocked_fct, calls)