rbtools.testing¶
Common support for writing unit tests for RBTools.
- class rbtools.testing.CommandTestsMixin(*args, **kwargs)¶
Bases:
SpyAgency
,Generic
[_CommandT
]Mixin for unit tests for commands.
This provides utility commands for creating and running commands in a controlled environment, allowing API URLs to be created and output and exit codes to be captured.
Subclasses must provide the type of the class as a generic to the mixin, and set
command_cls
appropriately.Changed in version 5.0: Added generic support for the mixin, to type command classes and instances.
New in version 3.1.
- command_cls: Optional[type[_CommandT]] = None¶
The command class being tested.
This must be a subclass of
rbtools.commands.Command
.- Type:
- needs_temp_home = True¶
- DEFAULT_SERVER_URL = 'https://reviews.example.com/'¶
- create_command(*, args: Optional[list[str]] = None, server_url: str = 'https://reviews.example.com/', initialize: bool = False, **kwargs) _CommandT ¶
Create an argument parser with the given extra fields.
- Parameters:
args (
list
ofstr
, optional) –A list of command line arguments to be passed to the parser.
The command line will receive each item in the list.
server_url (
str
, optional) – The URL to use as the Review Board URL.initialize (
bool
, optional) – Whether to initialize the command before returning.**kwargs (
dict
) – Additional keyword arguments.
- Returns:
The command instance.
- Return type:
- run_command(args: Optional[list[str]] = None, server_url: str = 'https://reviews.example.com/', **kwargs) RunCommandResult[_CommandT] ¶
Run a command class and return results.
- Parameters:
- Returns:
A dictionary of results from the command execution. See
RunCommandResult
for details.- Return type:
- __orig_bases__ = (<class 'kgb.agency.SpyAgency'>, typing.Generic[~_CommandT])¶
- __parameters__ = (~_CommandT,)¶
- class rbtools.testing.TestCase(methodName='runTest')¶
Bases:
TestCase
The base class for RBTools test cases.
This provides helpful utility functions, environment management, and better docstrings to help craft unit tests for RBTools functionality. All RBTools unit tests should use this this class or a subclass of it as the base class.
- ws_re = re.compile('\\s+')¶
Regex for matching consecutive whitespace characters.
- maxDiff = None¶
- default_text_editor: str = '/Users/chipx86/buildroots/rbtools-5.0/bin/python3.12 /private/var/folders/34/6wkbp94x5g79sbk8kfrscpzw0000gn/T/beanbag-tools.wkno7ali/rbtools/testing/scripts/editor.py'¶
The default text editor to use for tests.
By default, this will use a fake editor that’s bundled with the test suite.
- TEST_SERVER_URL = 'https://reviews.example.com/'¶
A sample test URL for a Review Board server.
New in version 3.1.
- needs_temp_home: bool = False¶
Whether individual unit tests need a new temporary HOME directory.
If set, a directory will be created at test startup, and will be set as the home directory.
New in version 3.0.
- classmethod setUpClass() None ¶
Set up the test suite.
This will store some state that can be restored once all tests in the class have been run.
- classmethod tearDownClass() None ¶
Tear down the test suite.
This will restore the current directory to what was set prior to the test runs, and then call any parent tear-down logic.
- setUp() None ¶
Set up a single test.
This will store some initial state for tests and optionally create a new current HOME directory to run the tests within.
- tearDown() None ¶
Tear down a single test.
This will clean up any temporary files and directories, and restore the current directory and HOME direcotry.
- shortDescription() str ¶
Returns the description of the current test.
This changes the default behavior to replace all newlines with spaces, allowing a test description to span lines. It should still be kept short, though.
- Returns:
The descriptive text for the current unit test.
- Return type:
- get_user_home() str ¶
Return the user’s current home directory.
New in version 3.0.
- Returns:
The current home directory.
- Return type:
- set_user_home(path: str) None ¶
Set the user’s current home directory.
This will be unset when the unit test has finished.
New in version 3.0.
- Parameters:
path (
str
) – The new home directory.
- chdir_tmp() str ¶
Create a temporary directory and set it as the working directory.
The directory will be deleted after the test has finished.
New in version 3.0.
- Returns:
The path to the temp directory.
- Return type:
- env(env: dict[str, Optional[str]]) Iterator[None] ¶
Run code with custom environment variables temporarily set.
This will set environment variables to the provided values (or erase them from the environment if set to
None
) before executing the code in the context.Once executed, the old environment will be restored.
New in version 5.0.
- Parameters:
env (
dict
) – The environment variables to set/remove.- Context:
Code will execute with the new environment set.
- precreate_tempfiles(count: int) Sequence[str] ¶
Pre-create a specific number of temporary files.
This will call
make_tempfile()
the specified number of times, returning the list of generated temp file paths, and will then spy that function to return those temp files.Once each pre-created temp file is used up, any further calls to
make_tempfile()
will result in an error, failing the test.This is useful in unit tests that need to script a series of expected calls using
kgb
(such as throughkgb.ops.SpyOpMatchInOrder
) that need to know the names of temporary filenames up-front.Unit test suites that use this must mix in
kgb.SpyAgency
.New in version 3.0.
- Parameters:
count (
int
) – The number of temporary filenames to pre-create.- Returns:
The list of temporary file paths.
- Return type:
- Raises:
AssertionError – The test suite class did not mix in
kgb.SpyAgency
.
- precreate_tempdirs(count: int) Sequence[str] ¶
Pre-create a specific number of temporary directories.
This will call
make_tempdir()
the specified number of times, returning the list of generated temp paths, and will then spy that function to return those temp paths.Once each pre-created temp path is used up, any further calls to
make_tempdir()
will result in an error, failing the test.This is useful in unit tests that need to script a series of expected calls using
kgb
(such as throughkgb.ops.SpyOpMatchInOrder
) that need to know the names of temporary filenames up-front.Unit test suites that use this must mix in
kgb.SpyAgency
.New in version 3.0.
- Parameters:
count (
int
) – The number of temporary directories to pre-create.- Returns:
The list of temporary directory paths.
- Return type:
- Raises:
AssertionError – The test suite class did not mix in
kgb.SpyAgency
.
- assertDiffEqual(diff: bytes, expected_diff: bytes) None ¶
Assert that two diffs are equal.
- Parameters:
- Raises:
AssertionError – The diffs aren’t equal or of the right type.
- assertRaisesMessage(expected_exception: type[Exception], expected_message: str) _AssertRaisesContext[Exception] ¶
Assert that a call raises an exception with the given message.
- Parameters:
- Raises:
AssertionError – The assertion failure, if the exception and message isn’t raised.
- create_rbclient() RBClient ¶
Return a RBClient for testing.
This will set up a
URLMapTransport
. It’s recommended that the caller access it viaget_rbclient_transport()
.New in version 3.1.
- Parameters:
transport (
rbtools.api.transport.Transport
, optional) – An explicit transport instance to use- Returns:
The client for testing purposes.
- Return type:
- get_rbclient_transport(client: RBClient) Transport ¶
Return the transport associated with a RBClient.
This allows tests to avoid reaching into
RBClient
internals in order to get the transport.New in version 3.1.
- Parameters:
client (
rbtools.api.client.RBClient
) – The client instance.- Returns:
The client’s transport.
- Return type:
- write_reviewboardrc(config: Union[str, dict[str, object]] = {}, *, parent_dir: Optional[str] = None, filename: str = '.reviewboardrc') str ¶
Write a .reviewboardrc file to a directory.
This allows for control over where the file is written, what it’s named, and the serialization of the contents of the file.
New in version 5.0.
- Parameters:
config (
dict
orstr
) – A dictionary of settings to write, or a string payload for the entire file.parent_dir (
str
, optional) –The directory where the configuration file should go.
This will default to the current directory.
filename (
str
, optional) –The name of the configuration file.
This defaults to
.reviewboardrc
.
- Returns:
The resulting path to the configuration file.
- Return type:
- reviewboardrc(config: Union[str, dict[str, object]], use_temp_dir: bool = False) Iterator[None] ¶
Populate a temporary .reviewboardrc file.
This will create a
.reviewboardrc
file, either in the current directory or in a new temporary directory (ifuse_temp_dir
is set). The file will contain the provided configuration.New in version 3.0.
- Parameters:
A dictionary of key-value pairs to write into the
.reviewboardrc
file, or the string contents of the file.A best effort attempt will be made to write each configuration to the file.
use_temp_dir (
bool
, optional) – Whether a temporary directory should be created and set as the current directory. If set, the file will be written there, and the directory will be removed after the context manager finishes.
- Context:
The code being run will have a
.reviewboardrc
in the current directory.
- class rbtools.testing.URLMapTransport(url, username=None, password=None, cache_location=None, in_memory_cache=False, **kwargs)¶
Bases:
Transport
API transport for defining and querying URL maps of responses.
This transport allows unit tests to define the URLs they want to test against, mapping URLS and HTTP methods to groups of payloads and headers, and HTTP status codes.
By default, this provides a handful of pre-built URLs:
/api/
/api/info/
/api/repositories/
/api/review-requests/
Unit tests can define any additional resources they need through the following functions:
Any defined URLs can be modified by changing entries anywhere in the
urls
dictionary. These changes will not persist to other unit tests.API capabilities can also be changed be modifying
capabilities
.If unit tests need URLs that are not already defined on this transport, it may be worth contributing helper functions to this class, in order to ensure consistency (see the implementation of
add_repository_url()
for details).New in version 3.1.
- api_calls¶
A list of API calls that have been made. Each is a dictionary containing:
- cache_location¶
The cache location configured when constructing the transport or when calling
enable_cache()
.- Type:
- cache_in_memory¶
The cache-in-memory flag configured when constructing the transport or when calling
enable_cache()
.- Type:
- capabilities¶
The dictionary of capabilities to simulate being returned from the API. This can be modified as needed by unit tests.
- Type:
- list_item_payloads¶
A mapping of relative list URLs to lists of item payloads that should be returned when accessing that list resource.
Note that list resources must be registered through
add_list_url()
.- Type:
- logged_in¶
Whether the user is logged in.
This will be set to
True
if a username and password are provided during construction, or iflogin()
is called.- Type:
- login_credentials¶
A dictionary of login credentials.
This will be set to a dictionary with
username
andpassword
keys if a username and password are provided during construction, or iflogin()
is called. Otherwise it will beNone
.- Type:
- payload_factory¶
The payload factory used to construct resource object and response payloads. This can be used when calling
add_item_url()
oradd_list_url()
.- Type:
rbtools.testing.api.payloads.PayloadFactory
- urls¶
The mapping of URLs to response information. This is in the following form:
urls = { '/api/.../[?...]': { '<HTTP method>': { 'headers': { 'Content-Type': '...', ..., }, 'http_status': ..., 'payload': { 'stat': '...', ..., }, }, ... }, ... }
Anything in this tree can be freely modified by unit tests. Changes will not persist across tests.
- Type:
- __init__(url, username=None, password=None, cache_location=None, in_memory_cache=False, **kwargs)¶
Initialize the transport.
- Parameters:
url (
unicode
) – The URL to the root of the server. This must end with/
.username (
unicode
, optional) – An optional username to simulate logging in with. If set,password
is required.password (
unicode
, optional) – An optional password to simulate logging in with. This is ignored ifusername
is not set.cache_location (
unicode
, optional) – An optional cache location to set. This only affectscache_location
and will otherwise be ignored.in_memory_cache (
bool
, optional) – Whether to use an in-memory cache. This only affectscache_in_memory
and will otherwise be ignored.**kwargs (
dict
) – Additional keyword arguments passed to the transport. These will be stored intransport_kwargs
.
- add_url(url, mimetype, method='GET', http_status=200, headers={}, payload={}, link_expansion_types={}, extra_node_state={})¶
Add a URL mapping to a payload.
- Parameters:
url (
unicode
) – The URL for the resource. This can include or omit a query string, as needed (exact query strings have higher precedence than not having a query string).mimetype (
unicode
) – The mimetype for the response.method (
unicode
, optional) – The HTTP method that the payload will map to.http_status (
int
, optional, optional) – The HTTP status code of the response.headers (
dict
, optional, optional) – Any custom headers to provide in the response.payload (
dict
orbytes
, optional) – The payload data. This can be a dictionary of deserialized API results, or it can be a byte string of content.link_expansion_types (
dict
, optional) – A mapping of links torbtools.testing.api.payloads. LinkExpansionType
values to help determine how to expand links.extra_node_state (
dict
, optional) – Extra state to store along with the registered URL node.
- Responses:
dict: The results of the add operation, for further tracking or processing.
- Keys:
- method (unicode):
The registered HTTP method.
- url (unicode):
The normalized registered URL used to store the mapping.
- node (dict):
The registered dictionary that the URL and method maps to, for modification.
- add_item_url(url, payload, item_key=None, in_list_urls=[], link_expansion_types={}, **kwargs)¶
Add a URL for an item or singleton resource.
- Parameters:
url (
unicode
) – The URL for the resource. This can include or omit a query string, as needed (exact query strings have higher precedence than not having a query string).payload (
dict
) – The object payload to provide in the response payload.item_key (
unicode
, optional) – The item key used to map to the object’s payload in the response payload. IfNone
, the object payload will be merged into the response payload.in_list_urls (
list
ofunicode
) – Any URLs for list resources that should contain this item in list responses.link_expansion_types (
dict
, optional) – A mapping of links torbtools.testing.api.payloads. LinkExpansionType
values to help determine how to expand links.**kwargs (
dict
) – Additional keyword arguments for the registration. Seeadd_url()
for details.
- Responses:
dict: The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.
- add_list_url(url, list_key, item_mimetype, headers={}, **kwargs)¶
Add a URL for a list resource.
The payload will be computed dynamically as needed, listing items registered in
list_item_payloads
.- Parameters:
url (
unicode
) – The URL for the resource. This can include or omit a query string, as needed (exact query strings have higher precedence than not having a query string).list_key (
unicode
) – The key used to map to the list of item payloads in the response payload.item_mimetype (
unicode
) – The mimetype for items in the list.headers (
dict
, optional) – Any custom headers to provide in the response.**kwargs (
dict
) – Additional keyword arguments for the registration. Seeadd_url()
for details.
- Responses:
dict: The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.
- add_error_url(url, error_code, error_message, payload_extra=None, http_status=400, **kwargs)¶
Add a URL for an error response.
- Parameters:
url (
unicode
) – The URL that triggers the error. This can include or omit a query string, as needed (exact query strings have higher precedence than not having a query string).error_code (
int
) – The API error code.error_message (
unicode
) – The API error message.payload_extra (
dict
, optional) – Additional data to provide in the root of the error payload.http_status (
int
, optional) – The HTTP status code for the error.**kwargs (
dict
) – Additional keyword arguments for the registration. Seeadd_url()
for details.
- Responses:
dict: The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.
- add_repository_urls(repository_id=1, info_payload=None, **kwargs)¶
Add URLs for a repository.
This will add a URL for a repository item resource and register it in the corresponding list resource.
A repository info URL is also registered, returning either a specified repository-specific info payload or a suitable error.
- Parameters:
repository_id (
int
, optional) – The ID of the repository being added to the API.info_payload (
dict
, optional) – Any payload data for theinfo/
URL. IfNone
, then an error payload will be registered instead.**kwargs (
dict
) – Additional keyword arguments for the repository payload. Seerbtools.testing.api.payloads.PayloadFactory. make_repository_object_data()
for details.
- Returns:
A dictionary of
add_url()
results for the two URLs.- Return type:
- add_review_request_url(**kwargs)¶
Add URLs for a review request.
This will add a URL for a review request item resource and register it in the corresponding list resource.
- Parameters:
**kwargs (
dict
) – Keyword arguments for the review request payload. Seerbtools.testing.api.payloads.PayloadFactory. make_review_request_object_data()
for details.- Returns:
The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.- Return type:
- add_review_request_draft_url(**kwargs)¶
Add URLs for a review request draft.
This will add a URL for a review request draft resource.
- Parameters:
**kwargs (
dict
) – Keyword arguments for the review request draft payload. Seerbtools.testing.api.payloads.PayloadFactory. make_review_request_draft_object_data()
for details.- Returns:
The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.- Return type:
- add_session_url(**kwargs)¶
Add URLs for a user session.
- Parameters:
**kwargs (
dict
) – Keyword arguments for the session payload. Seerbtools.testing.api.payloads.PayloadFactory. make_session_object_data()
for details.- Returns:
The results of the add operation, for further tracking or processing. See the return type for
add_url()
for details.- Return type:
- add_user_url(**kwargs)¶
Add URLs for a user resource.
- get_root()¶
Perform a simulated HTTP GET on the root API.
- Returns:
The resulting root resource.
- Return type:
- get_path(path, *args, **kwargs)¶
Perform a simulated HTTP GET on the given relative path.
- Parameters:
- Returns:
The resulting resource or error.
- Return type:
rbtools.api.resource.Resource
orrbtools.api.errors.APIError
- get_url(url, *args, **kwargs)¶
Perform a simulated HTTP GET on the given absolute URL.
- Parameters:
- Returns:
The resulting resource or error.
- Return type:
rbtools.api.resource.Resource
orrbtools.api.errors.APIError
- login(username: Optional[str] = None, password: Optional[str] = None, api_token: Optional[str] = None, *args, **kwargs) None ¶
Log in to the server.
This will simply set the
logged_in
andlogin_credentials
login state.Changed in version 5.0: Added an optional
api_token
parameter and made theusername
andpassword
parameters optional to allow logging in with either a username and password or API token.
- logout()¶
Log out of the server.
This will simply clear the
logged_in
andlogin_credentials
login state.
- execute_request_method(method, *args, **kwargs)¶
Execute a method and process the resulting HttpRequest.
- Parameters:
- Returns:
The resulting resource or error.
- Return type:
rbtools.api.resource.Resource
orrbtools.api.errors.APIError
- enable_cache(cache_location=None, in_memory=False)¶
Enable the HTTP cache.
This will simply set the
cache_location
andcache_in_memory
attributes.
- handle_api_path(path, method)¶
Handle a request to an API path.
This will log the request attempt for debugging purposes, look up the appropriate response, and return it if found.
Any missing URL or method mappings will result in an assertion error.
- Parameters:
- Returns:
The resulting resource or error.
This may also return
None
for DELETE requests.- Return type:
rbtools.api.resource.Resource
orrbtools.api.errors.APIError