id stringlengths 16 145 | text stringlengths 1 179k | title stringclasses 1
value |
|---|---|---|
spring_io/bootfeaturesexternal1_106_0.txt | Using the ` @Value("${property}") ` annotation to inject configuration
properties can sometimes be cumbersome, especially if you are working with
multiple properties or your data is hierarchical in nature. Spring Boot
provides an alternative method of working with properties that lets strongly
typed beans govern and va... | |
spring_io/bootfeaturesexternal_40_0.txt | 1. ` file:./config/ `
2. ` file:./ `
3. ` classpath:/config/ `
4. ` classpath:/ ` | |
spring_io/bootfeaturesexternal_177_0.txt | ` person.first_name ` | |
spring_io/bootfeaturesexternal1_87_0.txt | server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production & eu-central
server:
address: 192.168.1.120 | |
spring_io/bootfeaturesexternal1_86_0.txt | You can specify multiple profile-specific YAML documents in a single file by
using a ` spring.profiles ` key to indicate when the document applies, as
shown in the following example: | |
spring_io/bootfeaturesexternal_20_0.txt | ## 24.1 Configuring random values | |
spring_io/bootfeaturesexternal1_149_0.txt | This style of configuration works particularly well with the `
SpringApplication ` external YAML configuration, as shown in the following
example: | |
spring_io/spring_io_5_2.txt | ack.rollingpolicy.max-file-size ` | The maximum size of log file before it is archived.
` logging.logback.rollingpolicy.total-size-cap ` | The maximum amount of size log archives can take before being deleted.
` logging.logback.rollingpolicy.max-history ` | The maximum number of archive log files to keep (defa... | |
spring_io/bootfeaturesexternal1_54_0.txt | If several profiles are specified, a last-wins strategy applies. For example,
profiles specified by the ` spring.profiles.active ` property are added after
those configured through the ` SpringApplication ` API and therefore take
precedence. | |
spring_io/bootfeaturesexternal_82_0.txt | ### 24.6.3 Multi-profile YAML documents | |
spring_io/spring_io_10_4.txt | import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(args = "--app.test=one")
class MyApplicationArgumentTests {
@Test
void applicationArgumentsPopulated(@Autowired ApplicationArguments args) {
... | |
spring_io/bootfeaturesexternal_117_0.txt | public void setRemoteAddress(InetAddress remoteAddress) { ... } | |
spring_io/bootfeaturesexternal1_7_0.txt | import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*; | |
spring_io/bootfeaturesexternal1_18_0.txt | $ java -jar myapp.jar --spring.application.json='{"name":"test"}' | |
spring_io/bootfeaturesexternal1_218_0.txt | ### 25.8.3 Merging Complex Types | |
spring_io/bootfeaturesexternal_32_0.txt | You can also [ use YAML ('.yml') files ](boot-features-external-
config.html#boot-features-external-config-yaml "24.6 Using YAML instead of
Properties") as an alternative to '.properties'. | |
spring_io/spring_io_8_2.txt | OException::class)
override fun serializeObject(value: MyObject, jgen: JsonGenerator, provider: SerializerProvider) {
jgen.writeStringField("name", value.name)
jgen.writeNumberField("age", value.age)
}
}
class Deserializer : JsonObjectDeserial... | |
spring_io/bootfeaturesexternal_184_0.txt | As this bean is requested very early during the application lifecycle, make
sure to limit the dependencies that your ` ConversionService ` is using.
Typically, any dependency that you require may not be fully initialized at
creation time. You may want to rename your custom ` ConversionService ` if
it’s not required for... | |
spring_io/bootfeaturesexternal1_289_0.txt | public static class Security { | |
spring_io/bootfeaturesexternal1_61_0.txt | You can also use this technique to create “short” variants of existing Spring
Boot properties. See the _[ Section 78.4, “Use ‘Short’ Command Line
Arguments” ](howto-properties-and-configuration.html#howto-use-short-command-
line-arguments "78.4 Use ‘Short’ Command Line Arguments") _ how-to for
details. | |
spring_io/bootfeaturesexternal_141_0.txt | When ` @ConfigurationProperties ` bean is registered that way, the bean will
have a conventional name: ` <prefix>-<fqn> ` , where ` <prefix> ` is the
environment key prefix specified in the ` @ConfigurationProperties `
annotation and ` <fqn> ` the fully qualified name of the bean. If the
annotation does not provide any... | |
spring_io/environmentvariables_4_0.txt | Follow | |
spring_io/bootfeaturesexternal_61_0.txt | ![\[Note\]](images/note.png) | Note
---|--- | |
spring_io/bootfeaturesexternal1_217_0.txt | For example, the configuration property ` my.acme[0].other ` would use an
environment variable named ` MY_ACME_0_OTHER ` . | |
spring_io/bootfeaturesexternal_49_0.txt | In addition to ` application.properties ` files, profile-specific properties
can also be defined using the naming convention `
application-{profile}.properties ` . The ` Environment ` has a set of default
profiles (by default ` [default] ` ) which are used if no active profiles are
set (i.e. if no profiles are explicit... | |
spring_io/bootfeaturesexternal_41_0.txt | When custom config locations are configured, they are used in addition to the
default locations. Custom locations are searched before the default locations.
For example, if custom locations ` classpath:/custom-config/,file:./custom-
config/ ` are configured, the search order becomes: | |
spring_io/bootfeaturesexternal1_259_0.txt | If you are upgrading from a previous version that is using ` Long ` to express
the duration, make sure to define the unit (using ` @DurationUnit ` ) if it
isn’t milliseconds alongside the switch to ` Duration ` . Doing so gives a
transparent upgrade path while supporting a much richer format. | |
spring_io/bootfeaturesexternal1_153_0.txt | To work with ` @ConfigurationProperties ` beans, you can inject them in the
same way as any other bean, as shown in the following example: | |
spring_io/bootfeaturesexternal_136_0.txt | ![\[Tip\]](images/tip.png) | Tip
---|--- | |
spring_io/bootfeaturesexternal1_39_0.txt | If ` spring.config.location ` contains directories (as opposed to files), they
should end in ` / ` (and, at runtime, be appended with the names generated
from ` spring.config.name ` before being loaded, including profile-specific
file names). Files specified in ` spring.config.location ` are used as-is,
with no support... | |
spring_io/bootfeaturesexternal1_69_0.txt | ### 25.7.1 Loading YAML | |
Python_development_tools/unittest_10_0.txt | ## Signal Handling ¶
New in version 3.2.
The ` -c/--catch ` command-line option to unittest, along with the `
catchbreak ` parameter to ` unittest.main() ` , provide more friendly
handling of control-C during a test run. With catch break behavior enabled
control-C will allow the currently running test to comp... | |
Python_development_tools/unittest_mock_2_7.txt | t_has_awaits(calls)
Traceback (most recent call last):
...
AssertionError: Awaits not found.
Expected: [call('foo'), call('bar')]
Actual: []
>>> asyncio.run(main('foo'))
>>> asyncio.run(main('bar'))
>>> mock.assert_has_awaits(calls)
assert_not_awaited ( ) ¶
Assert that t... | |
Python_development_tools/typing_7_0.txt | #### Aliases to built-in types ¶
_ class _ typing. Dict ( _ dict, MutableMapping[KT, VT] _ ) ¶
Deprecated alias to [ ` dict ` ](stdtypes.html#dict "dict") .
Note that to annotate arguments, it is preferred to use an abstract collection
type such as ` Mapping ` rather than to use [ ` dict ` ](st... | |
Python_development_tools/unittest_mock_2_6.txt | ck
is ` AsyncMock ` or ` MagicMock ` ) or ` Mock ` (if the parent mock is
` Mock ` ). All asynchronous functions will be ` AsyncMock ` .
>>> class ExampleClass:
... def sync_foo():
... pass
... async def async_foo():
... pass
...
>>> a_mock = Async... | |
Python_development_tools/unittest_8_0.txt | ## Classes and functions ¶
This section describes in depth the API of ` unittest ` .
### Test cases ¶
_ class _ unittest. TestCase ( _ methodName = 'runTest' _ ) ¶
Instances of the ` TestCase ` class represent the logical test units in the
` unittest ` universe. This class is intended to b... | |
Python_development_tools/unittest_9_0.txt | ## Class and Module Fixtures ¶
Class and module level fixtures are implemented in ` TestSuite ` . When the
test suite encounters a test from a new class then ` tearDownClass() ` from
the previous class (if there is one) is called, followed by ` setUpClass() `
from the new class.
Similarly if a test is from a d... | |
Python_development_tools/typing_14_0.txt | #### Previous topic
[ Development Tools ](development.html "previous chapter")
| |
Python_development_tools/doctest_6_0.txt | ## Advanced API ¶
The basic API is a simple wrapper thatâs intended to make doctest easy to
use. It is fairly flexible, and should meet most usersâ needs; however, if
you require more fine-grained control over testing, or wish to extend
doctestâs capabilities, then you should use the advanced API.
The advanc... | |
Python_development_tools/doctest_4_1.txt | ld be used to
convert the file to unicode.
doctest. testmod ( _ m = None _ , _ name = None _ , _ globs = None
_ , _ verbose = None _ , _ report = True _ , _ optionflags = 0 _ , _
extraglobs = None _ , _ raise_on_error = False _ , _ exclude_empty =
False _ ) ¶
All arguments are opti... | |
Python_development_tools/unittest_mock_5_1.txt | ='two')
>>> kall = m.call_args
>>> kall.args
(1, 2, 3)
>>> kall.kwargs
{'arg': 'one', 'arg2': 'two'}
>>> kall.args is kall[0]
True
>>> kall.kwargs is kall[1]
True
>>> m = MagicMock()
>>> m.foo(4, 5, 6, arg='two', arg2='three')
<MagicMock name='mock.foo()' i... | |
Python_development_tools/unittest_mock_5_2.txt | >>> dir(Mock(spec=request))
['AbstractBasicAuthHandler',
'AbstractDigestAuthHandler',
'AbstractHTTPHandler',
'BaseHandler',
...
Many of the not-very-useful (private to ` Mock ` rather than the thing being
mocked) underscore and double underscore prefixed attributes have been
filtered f... | |
Python_development_tools/unittest_mock_0_0.txt | [  ](https://www.python.org/)
Theme Auto Light Dark
### [ Table of Contents ](../contents.html)
* ` unittest.mock ` â mock object library
* Quick Guide
* The Mock Class
* Calling
* Deleting Attributes
* Mock names and the name attribute
... | |
Python_development_tools/unittest_8_14.txt | the name of a single test or an iterable
of test names to run if no test names are specified via _argv_ . If not
specified or ` None ` and no test names are provided via _argv_ , all tests
found in _module_ are run.
The _argv_ argument can be a list of options passed to the program, with the
first element being the ... | |
Python_development_tools/typing_6_6.txt | nthesized ` __init__ ` method. If unspecified, ` init ` defaults to ` True ` .
` default ` | Provides the default value for the field.
` default_factory ` | Provides a runtime callback that returns the default value for the field. If neither ` default ` nor ` default_factory ` are specified, the field is... | |
Python_development_tools/unittest_4_1.txt | ages to placing the test code in a separate module, such as `
test_widget.py ` :
* The test module can be run standalone from the command line.
* The test code can more easily be separated from shipped code.
* There is less temptation to change test code to fit the code it tests without a good reason.
*... | |
Python_development_tools/typing_2_1.txt | , servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
...
... | |
Python_development_tools/unittest_0_0.txt | [  ](https://www.python.org/)
Theme Auto Light Dark
### [ Table of Contents ](../contents.html)
* ` unittest ` â Unit testing framework
* Basic example
* Command-Line Interface
* Command-line options
* Test Discovery
* Organizing test code
* R... | |
Python_development_tools/code_translation_1_0.txt | ## Using 2to3 ¶
2to3 will usually be installed with the Python interpreter as a script. It is
also located in the ` Tools/scripts ` directory of the Python root.
2to3âs basic arguments are a list of files or directories to transform. The
directories are recursively traversed for Python sources.
Here is a sampl... | |
Python_development_tools/doctest_2_0.txt | ## Simple Usage: Checking Examples in a Text File ¶
Another simple application of doctest is testing interactive examples in a
text file. This can be done with the ` testfile() ` function:
import doctest
doctest.testfile("example.txt")
That short script executes and verifies any interacti... | |
Python_development_tools/doctest_5_0.txt | ## Unittest API ¶
As your collection of doctestâed modules grows, youâll want a way to run
all their doctests systematically. ` doctest ` provides two functions that
can be used to create [ ` unittest ` ](unittest.html#module-unittest
"unittest: Unit testing framework for Python.") test suites from modules a... | |
Python_development_tools/doctest_5_2.txt | ntrols when and how tests get run. The framework author
typically wants to control ` doctest ` reporting options (perhaps, e.g.,
specified by command line options), but thereâs no way to pass options
through [ ` unittest ` ](unittest.html#module-unittest "unittest: Unit
testing framework for Python.") to ` doctes... | |
Python_development_tools/typing_0_0.txt | [  ](https://www.python.org/)
Theme Auto Light Dark
### [ Table of Contents ](../contents.html)
* ` typing ` â Support for type hints
* Specification for the Python Type System
* Type aliases
* NewType
* Annotating callable objects
* Generics
* ... | |
Python_development_tools/typing_6_4.txt | d by
[ ` open() ` ](functions.html#open "open") .
### Functions and decorators ¶
typing. cast ( _ typ _ , _ val _ ) ¶
Cast a value to a type.
This returns the value unchanged. To the type checker this signals that the
return value has the designated type, but at runtime we intentionally donât
che... | |
Python_development_tools/typing_6_3.txt | ](../howto/annotations.html#annotations-howto) for more
information on annotations best practices), ` __total__ ` , `
__required_keys__ ` , and ` __optional_keys__ ` .
__total__ ¶
` Point2D.__total__ ` gives the value of the ` total ` argument. Example:
>>> from typing import TypedDic... | |
Python_development_tools/typing_6_1.txt | esence of given
attributes, ignoring their type signatures.
Protocol classes can be generic, for example:
class GenProto[T](Protocol):
def meth(self) -> T:
...
In code that needs to be compatible with Python 3.11 or older, generic
Protocols can be written as follows:
... | |
Python_development_tools/typing_8_0.txt | #### Aliases to types in [ ` collections ` ](collections.html#module-
collections "collections: Container datatypes") ¶
_ class _ typing. DefaultDict ( _ collections.defaultdict,
MutableMapping[KT, VT] _ ) ¶
Deprecated alias to [ ` collections.defaultdict `
](collections.html#collections.defaultdict... | |
Python_development_tools/unittest_mock_3_0.txt | ## The patchers ¶
The patch decorators are used for patching objects only within the scope of
the function they decorate. They automatically handle the unpatching for you,
even if exceptions are raised. All of these functions can also be used in with
statements or as class decorators.
### patch ¶
Note
The key... | |
Python_development_tools/unittest_mock_3_3.txt | >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
... class TestSample(unittest.TestCase):
... def test_sample(self):
... self.assertEqual(os.environ['newkey'], 'newvalue')
If you want to use a different prefix for your test, you can inform the
patchers of the different prefix by sett... | |
Python_development_tools/unittest_mock_5_4.txt | True
>>> mock_request.Request
<MagicMock name='request.Request' spec='Request' id='...'>
You can see that ` request.Request ` has a spec. ` request.Request ` takes
two arguments in the constructor (one of which is _self_ ). Hereâs what
happens if we try to call it incorrectly:
>>> req... | |
Python_development_tools/typing_4_2.txt | stored in a `
__metadata__ ` attribute.
If a library or tool encounters an annotation ` Annotated[T, x] ` and has no
special logic for the metadata, it should ignore the metadata and simply treat
the annotation as ` T ` . As such, ` Annotated ` can be useful for code that
wants to use annotations for purposes out... | |
Python_development_tools/unittest_mock_4_2.txt | ce.
Different versions of Python are inconsistent about applying this rule. The
supported protocol methods should work with all supported versions of Python.
[ 3 ]
The function is basically hooked up to the class, but each ` Mock ` instance
is kept isolated from the others.
| |
Python_development_tools/unittest_0_1.txt | ython testing tools including functional testing
frameworks and mock object libraries.
[ Testing in Python Mailing List ](http://lists.idyll.org/listinfo/testing-in-
python)
A special-interest-group for discussion of testing, and testing tools, in
Python.
The script ` Tools/unittestgui/unittestgui.py ` in the... | |
Python_development_tools/unittest_mock_2_3.txt | s normal value (from the `
return_value ` ).
If you pass in an iterable, it is used to retrieve an iterator which must
yield a value on every call. This value can either be an exception instance to
be raised, or a value to be returned from the call to the mock ( ` DEFAULT `
handling is identical to the function ca... | |
Python_development_tools/code_translation_2_1.txt | s.html#exec
"exec") .
exitfunc ¶
Changes assignment of ` sys.exitfunc ` to use of the [ ` atexit `
](atexit.html#module-atexit "atexit: Register and execute cleanup functions.")
module.
filter ¶
Wraps [ ` filter() ` ](functions.html#filter "filter") usage in a [ ` list `
](stdtypes.html#list "li... | |
Python_development_tools/unittest_4_0.txt | ## Organizing test code ¶
The basic building blocks of unit testing are _test cases_ â single
scenarios that must be set up and checked for correctness. In ` unittest ` ,
test cases are represented by ` unittest.TestCase ` instances. To make your
own test cases you must write subclasses of ` TestCase ` or u... | |
Python_development_tools/unittest_mock_3_5.txt | e.module.Class is self.MockClass
...
As an added bonus you no longer need to keep a reference to the ` patcher `
object.
It is also possible to stop all patches which have been started by using `
patch.stopall() ` .
patch. stopall ( ) ¶
Stop all active patches. Only stops patches started with... | |
Python_development_tools/typing_6_0.txt | #### Other special directives ¶
These functions and classes should not be used directly as annotations. Their
intended purpose is to be building blocks for creating and declaring types.
_ class _ typing. NamedTuple ¶
Typed version of [ ` collections.namedtuple() `
](collections.html#collections.namedtu... | |
Python_development_tools/unittest_8_1.txt | block as a subtest.
_msg_ and _params_ are optional, arbitrary values which are displayed whenever
a subtest fails, allowing you to identify them clearly.
A test case can contain any number of subtest declarations, and they can be
arbitrarily nested.
See Distinguishing test iterations using subtests for more infor... | |
Python_development_tools/typing_4_4.txt |
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts] # Syntax error on Python <= 3.10!
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
` Unpack ` can also be used along with ` typing.TypedDict ` for typing `
**kwargs ` in a function signature:
from typin... | |
Python_development_tools/unittest_5_0.txt | ## Re-using old test code ¶
Some users will find that they have existing test code that they would like to
run from ` unittest ` , without converting every old test function to a `
TestCase ` subclass.
For this reason, ` unittest ` provides a ` FunctionTestCase ` class. This
subclass of ` TestCase ` can ... | |
Python_development_tools/unittest_1_0.txt | ## Basic example ¶
The ` unittest ` module provides a rich set of tools for constructing and
running tests. This section demonstrates that a small subset of the tools
suffice to meet the needs of most users.
Here is a short script to test three string methods:
import unittest
class TestSt... | |
Python_development_tools/doctest_7_1.txt | ntrol of
the Python debugger, [ ` pdb ` ](pdb.html#module-pdb "pdb: The Python
debugger for interactive interpreters.") .
A shallow copy of ` module.__dict__ ` is used for both local and global
execution context.
Optional argument _pm_ controls whether post-mortem debugging is used. If _pm_
has a true value, the sc... | |
Python_development_tools/unittest_8_12.txt | he ` expectedFailure() `
decorator.
stop ( ) ¶
This method can be called to signal that the set of tests being run should be
aborted by setting the ` shouldStop ` attribute to ` True ` . ` TestRunner
` objects should respect this flag and return without running any additional
tests.
For example, this ... | |
Python_development_tools/unittest_mock_2_9.txt | )
>>> parent = MagicMock()
>>> with patch('__main__.thing1', return_value=None) as child1:
... with patch('__main__.thing2', return_value=None) as child2:
... parent.attach_mock(child1, 'child1')
... parent.attach_mock(child2, 'child2')
... child1('one')
... ... | |
Python_development_tools/code_translation_0_0.txt | [  ](https://www.python.org/)
Theme Auto Light Dark
### [ Table of Contents ](../contents.html)
* 2to3 â Automated Python 2 to 3 code translation
* Using 2to3
* Fixers
* ` lib2to3 ` â 2to3âs library
#### Previous topic
[ ` unittest.mock ` â getting ... | |
Python_development_tools/doctest_8_1.txt | nts.html)
* ` doctest ` â Test interactive Python examples
* Simple Usage: Checking Examples in Docstrings
* Simple Usage: Checking Examples in a Text File
* How It Works
* Which Docstrings Are Examined?
* How are Docstring Examples Recognized?
* Whatâs the Execution Context?... | |
Python_development_tools/typing_1_0.txt | #### Previous topic
[ Development Tools ](development.html "previous chapter")
| |
Python_development_tools/unittest_8_5.txt | s of unhashable objects as well.
New in version 3.2.
The ` assertEqual() ` method dispatches the equality check for objects of
the same type to different type-specific methods. These methods are already
implemented for most of the built-in types, but itâs also possible to
register new methods using ` addTypeEqua... | |
Python_development_tools/unittest_6_1.txt | tead of raising this directly.
Skipped tests will not have ` setUp() ` or ` tearDown() ` run around them.
Skipped classes will not have ` setUpClass() ` or ` tearDownClass() ` run.
Skipped modules will not have ` setUpModule() ` or ` tearDownModule() ` run.
| |
Python_development_tools/doctest_7_0.txt | ## Debugging ¶
Doctest provides several mechanisms for debugging doctest examples:
* Several functions convert doctests to executable Python programs, which can be run under the Python debugger, [ ` pdb ` ](pdb.html#module-pdb "pdb: The Python debugger for interactive interpreters.") .
* The ` DebugRunner ... | |
Python_development_tools/typing_5_4.txt | rom typing import ParamSpec, get_origin
>>> P = ParamSpec("P")
>>> get_origin(P.args) is P
True
>>> get_origin(P.kwargs) is P
True
New in version 3.10.
_ class _ typing. TypeAliasType ( _ name _ , _ value _ , _ * _ , _
type_params = () _ ) ¶
The type of type aliases created... | |
Python_development_tools/unittest_mock_6_0.txt | ## Order of precedence of ` side_effect ` , ` return_value ` and _wraps_ ¶
The order of their precedence is:
1. ` side_effect `
2. ` return_value `
3. _wraps_
If all three are set, mock will return the value from ` side_effect ` ,
ignoring ` return_value ` and the wrapped object altogether. If any ... | |
Python_development_tools/code_translation_2_2.txt | rd operators.") module to other, but equivalent, function calls. When
needed, the appropriate ` import ` statements are added, e.g. ` import
collections.abc ` . The following mapping are made:
From | To
---|---
` operator.isCallable(obj) ` | ` callable(obj) `
` operator.sequenceIncludes(obj) ` | ` oper... | |
Python_development_tools/unittest_mock_3_1.txt | atch.TEST_PREFIX ` .
Patch can be used as a context manager, with the with statement. Here the
patching applies to the indented block after the with statement. If you use
âasâ then the patched object will be bound to the name after the âasâ;
very useful if ` patch() ` is creating a mock object for you.
` p... | |
Python_development_tools/doctest_3_2.txt | o, e.g., an example that expects ` ValueError: 42 is prime ` will pass whether [ ` ValueError ` ](exceptions.html#ValueError "ValueError") is actually raised or if the example merely prints that traceback text. In practice, ordinary output rarely begins with a traceback header line, so this doesnât create real p... | |
Python_development_tools/unittest_8_9.txt | ss that overrides `
TestSuite._removeTestAtIndex() ` to preserve test references.
Changed in version 3.2: In earlier versions the ` TestSuite ` accessed
tests directly rather than through iteration, so overriding ` __iter__() `
wasnât sufficient for providing tests.
Changed in version 3.4: In earlier versions... | |
Python_development_tools/unittest_8_3.txt | warnings_ .
If only the _warning_ and possibly the _msg_ arguments are given, return a
context manager so that the code under test can be written inline rather than
as a function:
with self.assertWarns(SomeWarning):
do_something()
When used as a context manager, ` assertWarns() ` accepts... | |
Python_development_tools/unittest_mock_2_0.txt | ## The Mock Class ¶
` Mock ` is a flexible mock object intended to replace the use of stubs and
test doubles throughout your code. Mocks are callable and create attributes as
new mocks when you access them [ 1 ] . Accessing the same attribute will
always return the same mock. Mocks record how you use them, all... | |
Python_development_tools/doctest_3_5.txt | her is to do
>>> d = sorted(foo())
>>> d
['eggs', 'spam']
There are others, but you get the idea.
Another bad idea is to print things that embed an object address, like
>>> id(1.0) # certain to fail some of the time
7948648
>>> class C: pass
>>> C() # the def... | |
Python_development_tools/unittest_8_7.txt | kwargs _ ) ¶
Add a function to be called after ` tearDownClass() ` to cleanup resources
used during the test class. Functions will be called in reverse order to the
order they are added ( LIFO ). They are called with any arguments and
keyword arguments passed into ` addClassCleanup() ` when they are a... | |
Python_development_tools/code_translation_2_0.txt | ## Fixers ¶
Each step of transforming code is encapsulated in a fixer. The command ` 2to3
-l ` lists them. As documented above , each can be turned on and off
individually. They are described here in more detail.
apply ¶
Removes usage of ` apply() ` . For example ` apply(function, *args,
**kwargs) `... | |
Python_development_tools/unittest_mock_4_1.txt | Mock ` variants: ` MagicMock ` and `
NonCallableMagicMock ` .
_ class _ unittest.mock. MagicMock ( _ * args _ , _ ** kw _ ) ¶
` MagicMock ` is a subclass of ` Mock ` with default implementations of
most of the [ magic methods ](../glossary.html#term-magic-method) . You can
use ` MagicMock ` ... | |
Python_development_tools/typing_5_2.txt | rameterization with a single type. A type
variable tuple, in contrast, allows parameterization with an _arbitrary_
number of types by acting like an _arbitrary_ number of type variables wrapped
in a tuple. For example:
# T is bound to int, Ts is bound to ()
# Return value is (1,), which has type tupl... | |
Python_development_tools/typing_6_5.txt | transform ( _ * _ , _ eq_default = True _ , _
order_default = False _ , _ kw_only_default = False _ , _ frozen_default
= False _ , _ field_specifiers = () _ , _ ** kwargs _ ) ¶
Decorator to mark an object as providing [ ` dataclass `
](dataclasses.html#dataclasses.dataclass "dataclasses.dat... | |
Python_development_tools/unittest_2_0.txt | ## Command-Line Interface ¶
The unittest module can be used from the command line to run tests from
modules, classes or even individual test methods:
python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method
... | |
Python_development_tools/doctest_8_0.txt | ## Soapbox ¶
As mentioned in the introduction, ` doctest ` has grown to have three
primary uses:
1. Checking examples in docstrings.
2. Regression testing.
3. Executable documentation / literate testing.
These uses have different requirements, and it is important to distinguish
them. In particular, f... | |
Python_development_tools/unittest_mock_6_1.txt | ...
StopIteration
### [ Table of Contents ](../contents.html)
* ` unittest.mock ` â mock object library
* Quick Guide
* The Mock Class
* Calling
* Deleting Attributes
* Mock names and the name attribute
* Attaching Mocks as Attributes
* The patchers
* p... | |
Python_development_tools/typing_4_0.txt | #### Special forms ¶
These can be used as types in annotations. They all support subscription using
` [] ` , but each has a unique syntax.
typing. Union ¶
Union type; ` Union[X, Y] ` is equivalent to ` X | Y ` and means either X or Y.
To define a union, use e.g. ` Union[int, str] ` or the short... | |
Python_development_tools/typing_6_7.txt | # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
There is no runtime checking of these properties. See [ **PEP 591**
](https://peps.python.org/pep-0591/) for more details.
New in version 3.8.
Change... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.