sqlobject.tests.dbtest module¶
The framework for making database tests.
- class sqlobject.tests.dbtest.Dummy(**kw)[source]¶
Bases:
objectUsed for creating fake objects; a really poor ‘mock object’.
- sqlobject.tests.dbtest.inserts(cls, data, schema=None)[source]¶
Creates a bunch of rows.
You can use it like:
inserts(Person, [{'fname': 'blah', 'lname': 'doe'}, ...])
Or:
inserts(Person, [('blah', 'doe')], schema= ['fname', 'lname'])
If you give a single string for the schema then it’ll split that string to get the list of column names.
- sqlobject.tests.dbtest.raises(expected_exception: type[E] | tuple[type[E], ...], *, match: str | Pattern[str] | None = ..., check: Callable[[E], bool] = ...) RaisesExc[E][source]¶
- sqlobject.tests.dbtest.raises(*, match: str | Pattern[str], check: Callable[[BaseException], bool] = ...) RaisesExc[BaseException]
- sqlobject.tests.dbtest.raises(*, check: Callable[[BaseException], bool]) RaisesExc[BaseException]
- sqlobject.tests.dbtest.raises(expected_exception: type[E] | tuple[type[E], ...], func: Callable[..., Any], *args: Any, **kwargs: Any) ExceptionInfo[E]
Assert that a code block/function call raises an exception type, or one of its subclasses.
- Parameters:
expected_exception –
The expected exception type, or a tuple if one of multiple possible exception types are expected. Note that subclasses of the passed exceptions will also match.
This is not a required parameter, you may opt to only use
matchand/orcheckfor verifying the raised exception.match (str | re.Pattern[str] | None) –
If specified, a string containing a regular expression, or a regular expression object, that is tested against the string representation of the exception and its PEP 678 __notes__ using
re.search().To match a literal string that may contain special characters, the pattern can first be escaped with
re.escape().(This is only used when
pytest.raisesis used as a context manager, and passed through to the function otherwise. When usingpytest.raisesas a function, you can use:pytest.raises(Exc, func, match="passed on").match("my pattern").)check (Callable[[BaseException], bool]) –
Added in version 8.4.
If specified, a callable that will be called with the exception as a parameter after checking the type and the match regex if specified. If it returns
Trueit will be considered a match, if not it will be considered a failed match.
Use
pytest.raisesas a context manager, which will capture the exception of the given type, or any of its subclasses:>>> import pytest >>> with pytest.raises(ZeroDivisionError): ... 1/0
If the code block does not raise the expected exception (
ZeroDivisionErrorin the example above), or no exception at all, the check will fail instead.You can also use the keyword argument
matchto assert that the exception matches a text or regex:>>> with pytest.raises(ValueError, match='must be 0 or None'): ... raise ValueError("value must be 0 or None") >>> with pytest.raises(ValueError, match=r'must be \d+$'): ... raise ValueError("value must be 42")
The
matchargument searches the formatted exception string, which includes any PEP-678__notes__:>>> with pytest.raises(ValueError, match=r"had a note added"): ... e = ValueError("value must be 42") ... e.add_note("had a note added") ... raise e
The
checkargument, if provided, must return True when passed the raised exception for the match to be successful, otherwise anAssertionErroris raised.>>> import errno >>> with pytest.raises(OSError, check=lambda e: e.errno == errno.EACCES): ... raise OSError(errno.EACCES, "no permission to view")
The context manager produces an
ExceptionInfoobject which can be used to inspect the details of the captured exception:>>> with pytest.raises(ValueError) as exc_info: ... raise ValueError("value must be 42") >>> assert exc_info.type is ValueError >>> assert exc_info.value.args[0] == "value must be 42"
Warning
Given that
pytest.raisesmatches subclasses, be wary of using it to matchExceptionlike this:# Careful, this will catch ANY exception raised. with pytest.raises(Exception): some_function()
Because
Exceptionis the base class of almost all exceptions, it is easy for this to hide real bugs, where the user wrote this expecting a specific exception, but some other exception is being raised due to a bug introduced during a refactoring.Avoid using
pytest.raisesto catchExceptionunless certain that you really want to catch any exception raised.Note
When using
pytest.raisesas a context manager, it’s worthwhile to note that normal context manager rules apply and that the exception raised must be the final line in the scope of the context manager. Lines of code after that, within the scope of the context manager will not be executed. For example:>>> value = 15 >>> with pytest.raises(ValueError) as exc_info: ... if value > 10: ... raise ValueError("value must be <= 10") ... assert exc_info.type is ValueError # This will not execute.
Instead, the following approach must be taken (note the difference in scope):
>>> with pytest.raises(ValueError) as exc_info: ... if value > 10: ... raise ValueError("value must be <= 10") ... >>> assert exc_info.type is ValueError
Expecting exception groups
When expecting exceptions wrapped in
BaseExceptionGrouporExceptionGroup, you should instead usepytest.RaisesGroup.Using with
pytest.mark.parametrizeWhen using pytest.mark.parametrize ref it is possible to parametrize tests such that some runs raise an exception and others do not.
See parametrizing_conditional_raising for an example.
See also
assertraises for more examples and detailed discussion.
Legacy form
It is possible to specify a callable by passing a to-be-called lambda:
>>> raises(ZeroDivisionError, lambda: 1/0) <ExceptionInfo ...>
or you can specify an arbitrary callable with arguments:
>>> def f(x): return 1/x ... >>> raises(ZeroDivisionError, f, 0) <ExceptionInfo ...> >>> raises(ZeroDivisionError, f, x=0) <ExceptionInfo ...>
The form above is fully supported but discouraged for new code because the context manager form is regarded as more readable and less error-prone.
Note
Similar to caught exception objects in Python, explicitly clearing local references to returned
ExceptionInfoobjects can help the Python interpreter speed up its garbage collection.Clearing those references breaks a reference cycle (
ExceptionInfo–> caught exception –> frame stack raising the exception –> current frame stack –> local variables –>ExceptionInfo) which makes Python keep all objects referenced from that cycle (including all local variables in the current frame) alive until the next cyclic garbage collection run. More detailed information can be found in the official Python documentation for the try statement.
- sqlobject.tests.dbtest.setupClass(soClasses, force=False)[source]¶
Makes sure the classes have a corresponding and correct table. This won’t recreate the table if it already exists. It will check that the table is properly defined (in case you change your table definition).
You can provide a single class or a list of classes; if a list then classes will be created in the order you provide, and destroyed in the opposite order. So if class A depends on class B, then do setupClass([B, A]) and B won’t be destroyed or cleared until after A is destroyed or cleared.
If force is true, then the database will be recreated no matter what.