rbtools.testing¶
Common support for writing unit tests for RBTools.
- class rbtools.testing.CommandTestsMixin(*args, **kwargs)¶
Bases:
SpyAgency
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.
New in version 3.1.
- command_cls = 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=[], server_url='https://reviews.example.com/', initialize=False, **kwargs)¶
Create an argument parser with the given extra fields.
- Parameters:
args (
list
ofunicode
, optional) –A list of command line arguments to be passed to the parser.
The command line will receive each item in the list.
repository_info (
rbtools.clients.base.repository.RepositoryInfo
) –The repository information to set for the command.
If being set,
tool
must also be set.tool (
rbtools.clients.base.BaseSCMClient
) –The SCM client to set for the command.
If being set,
repository_info
must also be set.scan (
bool
, optional) – Whether to allow for repository scanning. IfFalse
, andrepository_info
andtool
aren’t provided, then no repositories will be matched.server_url (
unicode
, optional) – The URL to use as the Review Board URL.stdout (
io.BytesIO
, optional) – A stream used to capture standard output.stderr (
io.BytesIO
, optional) – A stream used to capture standard error.stdin (
io.BytesIO
, optional) – A stream used to provide standard input.setup_transport_func (
callable
, optional) –A callback to call in order to set up transport URLs.
This must take a
transport
argument.initialize (
bool
, optional) – Whether to initialize the command before returning.
- Returns:
The command instance.
- Return type:
- run_command(args=[], server_url='https://reviews.example.com/', **kwargs)¶
Run a command class and return results.
- Parameters:
args (
list
ofunicode
, optional) –A list of command line arguments to be passed to the parser.
The command line will receive each item in the list.
repository_info (
rbtools.clients.base.repository.RepositoryInfo
) –The repository information to set for the command.
If being set,
tool
must also be set.tool (
rbtools.clients.base.BaseSCMClient
) –The SCM client to set for the command.
If being set,
repository_info
must also be set.scan (
bool
, optional) – Whether to allow for repository scanning. IfFalse
, andrepository_info
andtool
aren’t provided, then no repositories will be matched.server_url (
unicode
, optional) – The URL to use as the Review Board URL.stdin (
io.BytesIO
, optional) – A stream used to provide standard input.setup_transport_func (
callable
, optional) –A callback to call in order to set up transport URLs.
This must take a
transport
argument.
- Returns:
A dictionary of results, containing:
- Keys:
command (
rbtools.commands.Command
) – The command instance.exit_code (
int
) – The exit code.stderr (
bytes
) – The standard error output.stdout (
bytes
) – The standard output.
- Return type:
- 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+')¶
- default_text_editor = '/Users/chipx86/buildroots/rbtools-5.0/bin/python3.10 /private/var/folders/34/6wkbp94x5g79sbk8kfrscpzw0000gn/T/beanbag-tools.wdcv04tv/rbtools/testing/scripts/editor.py'¶
- maxDiff = 10000¶
- 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()¶
Hook method for setting up class fixture before running tests in the class.
- classmethod tearDownClass()¶
Hook method for deconstructing the class fixture after running all tests in the class.
- setUp()¶
Hook method for setting up the test fixture before exercising it.
- tearDown()¶
Hook method for deconstructing the test fixture after testing it.
- shortDescription()¶
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()¶
Return the user’s current home directory.
New in version 3.0.
- Returns:
The current home directory.
- Return type:
- set_user_home(path)¶
Set the user’s current home directory.
This will be unset when the unit test has finished.
New in version 3.0.
- Parameters:
path (
unicode
) – The new home directory.
- chdir_tmp()¶
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:
- precreate_tempfiles(count)¶
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.- Raises:
AssertionError – The test suite class did not mix in
kgb.SpyAgency
.
- precreate_tempdirs(count)¶
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.- Raises:
AssertionError – The test suite class did not mix in
kgb.SpyAgency
.
- assertDiffEqual(diff, expected_diff)¶
Assert that two diffs are equal.
- Parameters:
- Raises:
AssertionError – The diffs aren’t equal or of the right type.
- assertRaisesMessage(expected_exception, expected_message)¶
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()¶
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)¶
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, use_temp_dir=False)¶
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:
config (
dict
) –A dictionary of key-value pairs to write into the
.reviewboardrc
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, password, *args, **kwargs)¶
Log in to the server.
This will simply set the
logged_in
andlogin_credentials
login state.
- 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