flexmock 0.12.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ """Flexmock test runner integrations."""
2
+
3
+ # pylint: disable=import-outside-toplevel, import-error
4
+ import sys
5
+ import unittest
6
+ from contextlib import suppress
7
+ from functools import wraps
8
+ from typing import Any, Type
9
+
10
+ from flexmock._api import flexmock_teardown
11
+
12
+
13
+ def _patch_test_result(klass: Type[Any]) -> None:
14
+ """Patches flexmock into any class that inherits unittest.TestResult.
15
+
16
+ This seems to work well for majority of test runners. In the case of nose
17
+ it's not even necessary as it doesn't override unittest.TestResults's
18
+ addSuccess and addFailure methods so simply patching unittest works
19
+ out of the box for nose.
20
+
21
+ For those that do inherit from unittest.TestResult and override its
22
+ stopTest and addSuccess methods, patching is pretty straightforward
23
+ (numerous examples below).
24
+
25
+ The reason we don't simply patch unittest's parent TestResult class
26
+ is stopTest and addSuccess in the child classes tend to add messages
27
+ into the output that we want to override in case flexmock generates
28
+ its own failures.
29
+
30
+ Args:
31
+ klass: the class whose stopTest method needs to be decorated.
32
+ """
33
+ # pylint: disable=invalid-name
34
+ _patch_stop_test(klass)
35
+ _patch_add_success(klass)
36
+
37
+
38
+ def _patch_stop_test(klass: Type[unittest.TextTestResult]) -> None:
39
+ """Patch TextTestResult class stopTest method and add call to flexmock
40
+ teardown.
41
+
42
+ If the test failed already before flexmock teardown, nothing is done.
43
+ However if the test was successful before flexmock teardown and flexmock
44
+ assertions fail, flexmock updates the test result to failed by calling
45
+ addFailure method.
46
+
47
+ Args:
48
+ klass: the class whose stopTest method needs to be decorated.
49
+ """
50
+ saved_add_success = klass.addSuccess
51
+ saved_stop_test = klass.stopTest
52
+
53
+ @wraps(saved_stop_test)
54
+ def decorated(self: unittest.TextTestResult, test: unittest.TestCase) -> None:
55
+ if saved_stop_test.__code__ is not decorated.__code__: # type: ignore [attr-defined]
56
+ # if parent class was for some reason patched, avoid calling
57
+ # flexmock_teardown() twice and delegate up the class hierarchy
58
+ # this doesn't help if there is a gap and only the parent's
59
+ # parent class was patched, but should cover most screw-ups
60
+ try:
61
+ flexmock_teardown()
62
+ saved_add_success(self, test)
63
+ except Exception:
64
+ if hasattr(self, "_pre_flexmock_success"):
65
+ self.addFailure(test, sys.exc_info())
66
+ if hasattr(self, "_pre_flexmock_success"):
67
+ del self._pre_flexmock_success
68
+ return saved_stop_test(self, test)
69
+
70
+ if klass.stopTest is not decorated:
71
+ klass.stopTest = decorated # type: ignore
72
+
73
+
74
+ def _patch_add_success(klass: Type[unittest.TextTestResult]) -> None:
75
+ """Patch the addSuccess method of the TextTestResult class.
76
+
77
+ TextTestResult addSuccess method is replaced and the original addSuccess
78
+ method is called after flexmock teardown patched stopTest method.
79
+
80
+ An attribute is set in the replaced addSuccess method to indicate if the
81
+ test was successful before flexmock teardown was called.
82
+
83
+ Args:
84
+ klass: the class whose addSuccess method needs to be decorated.
85
+ """
86
+
87
+ @wraps(klass.addSuccess)
88
+ def decorated(self: unittest.TextTestResult, _test: unittest.TestCase, **_kwargs: Any) -> None:
89
+ self._pre_flexmock_success = True # type: ignore
90
+
91
+ if klass.addSuccess is not decorated:
92
+ klass.addSuccess = decorated # type: ignore
93
+
94
+
95
+ # Hook flexmock into doctest.
96
+
97
+ with suppress(ImportError):
98
+ from doctest import DocTestRunner, TestResults
99
+
100
+ saved_doctest = DocTestRunner.run
101
+
102
+ @wraps(saved_doctest)
103
+ def run(
104
+ *args: Any,
105
+ **kwargs: Any,
106
+ ) -> TestResults:
107
+ """Call the teardown at the end of the tests.
108
+
109
+ Args:
110
+ args: the arguments passed to the runner
111
+ kwargs: the keyword arguments passed to the runner
112
+
113
+ Returns:
114
+ The test results
115
+
116
+ """
117
+ try:
118
+ return saved_doctest(*args, **kwargs)
119
+ finally:
120
+ flexmock_teardown()
121
+
122
+ DocTestRunner.run = run # type: ignore
123
+
124
+
125
+ # Hook flexmock into unittest.
126
+ # only valid TestResult class for unittest is TextTestResult
127
+ _patch_test_result(unittest.TextTestResult)
128
+
129
+
130
+ # Hook into Teamcity unittests.
131
+ # This allows flexmock to be used within PyCharm.
132
+ with suppress(ImportError):
133
+ from teamcity.unittestpy import TeamcityTestResult
134
+
135
+ _patch_test_result(TeamcityTestResult)
136
+
137
+
138
+ # Hook into teststools.
139
+ # testtools is a set of extensions to the Python standard library's unit testing framework:
140
+ # https://github.com/testing-cabal/testtools
141
+
142
+ with suppress(ImportError):
143
+ from testtools import testresult
144
+
145
+ _patch_test_result(testresult.TestResult)
146
+
147
+
148
+ # Hook into Zope testrunner.
149
+ # Zope is an open-source web application server:
150
+ # https://github.com/zopefoundation/Zope
151
+
152
+ with suppress(ImportError):
153
+ from zope import testrunner # pylint: disable=no-name-in-module
154
+
155
+ try:
156
+ _patch_test_result(testrunner.runner.TestResult)
157
+ except AttributeError:
158
+ # testrunner.runner is only available when tests are executed with zope.testrunner
159
+ pass
160
+
161
+
162
+ # Hook into subunit.
163
+ # Subunit is a test reporting and controlling protocol.
164
+ # https://github.com/testing-cabal/subunit
165
+
166
+ with suppress(ImportError):
167
+ import subunit
168
+
169
+ _patch_test_result(subunit.TestProtocolClient)
170
+ with suppress(AttributeError):
171
+ _patch_test_result(subunit.test_results.TestResultDecorator)
172
+
173
+
174
+ # Hook into twisted.
175
+ # Twisted is an event-based framework for internet applications:
176
+ # https://github.com/twisted/twisted
177
+
178
+ with suppress(ImportError):
179
+ from twisted.trial import reporter
180
+
181
+ _patch_test_result(reporter.MinimalReporter)
182
+ _patch_test_result(reporter.TextReporter)
183
+ _patch_test_result(reporter.VerboseTextReporter)
184
+ _patch_test_result(reporter.TreeReporter)
@@ -0,0 +1,36 @@
1
+ """Hook flexmock into Pytest.
2
+ Pytest is a Python test framework:
3
+ https://github.com/pytest-dev/pytest
4
+ """
5
+
6
+ from typing import Generator, Optional
7
+
8
+ import pytest
9
+ from _pytest.runner import CallInfo, ExceptionInfo, Item, TestReport
10
+
11
+ from flexmock._api import flexmock_teardown
12
+
13
+
14
+ @pytest.hookimpl(hookwrapper=True)
15
+ def pytest_runtest_makereport(
16
+ item: Item, # pylint: disable=unused-argument
17
+ call: CallInfo[None],
18
+ ) -> Generator[None, None, None]:
19
+ """Called to verify and tear down the mocks set up by flexmock.
20
+
21
+ Args:
22
+ item: Test item for which the hook is being called.
23
+ call: Information about the current call phase.
24
+
25
+ Yields:
26
+ Control back to the pytest runner.
27
+ """
28
+ if call.when == "call":
29
+ try:
30
+ flexmock_teardown()
31
+ except BaseException: # pylint: disable=broad-except
32
+ call.excinfo = call.excinfo or ExceptionInfo.from_current()
33
+ elif call.when == "teardown":
34
+ flexmock_teardown()
35
+
36
+ _test_report: Optional[TestReport] = yield
flexmock/exceptions.py ADDED
@@ -0,0 +1,33 @@
1
+ """Flexmock exceptions."""
2
+
3
+
4
+ class FlexmockError(Exception):
5
+ """FlexmockError"""
6
+
7
+
8
+ class MockBuiltinError(Exception):
9
+ """MockBuiltinError"""
10
+
11
+
12
+ class MethodSignatureError(FlexmockError):
13
+ """MethodSignatureError"""
14
+
15
+
16
+ class ExceptionClassError(FlexmockError):
17
+ """ExceptionClassError"""
18
+
19
+
20
+ class ExceptionMessageError(FlexmockError):
21
+ """ExceptionMessageError"""
22
+
23
+
24
+ class StateError(FlexmockError):
25
+ """StateError"""
26
+
27
+
28
+ class MethodCallError(FlexmockError):
29
+ """MethodCallError"""
30
+
31
+
32
+ class CallOrderError(FlexmockError):
33
+ """CallOrderError"""
flexmock/py.typed ADDED
File without changes
@@ -0,0 +1,26 @@
1
+ Copyright 2011-2015 Herman Sheremetyev, Slavek Kabrda.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+ 2. Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23
+
24
+ The views and conclusions contained in the software and documentation are those
25
+ of the authors and should not be interpreted as representing official policies,
26
+ either expressed or implied, of the FreeBSD Project.
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.1
2
+ Name: flexmock
3
+ Version: 0.12.2
4
+ Summary: flexmock is a testing library for Python that makes it easy to create mocks, stubs and fakes.
5
+ Home-page: https://github.com/flexmock/flexmock
6
+ License: BSD-2-Clause
7
+ Keywords: mock,testing,test,unittest,pytest
8
+ Author: Slavek Kabrda
9
+ Maintainer: Adarsh Krishnan
10
+ Maintainer-email: adarshk7@gmail.com
11
+ Requires-Python: >=3.8.0,<4.0.0
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: BSD License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3 :: Only
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Classifier: Topic :: Software Development :: Testing
25
+ Classifier: Topic :: Software Development :: Testing :: Mocking
26
+ Classifier: Topic :: Software Development :: Testing :: Unit
27
+ Classifier: Typing :: Typed
28
+ Project-URL: Changes, https://flexmock.readthedocs.io/en/latest/changelog/
29
+ Project-URL: Documentation, https://flexmock.readthedocs.io
30
+ Project-URL: Issue Tracker, https://github.com/flexmock/flexmock/issues
31
+ Project-URL: Repository, https://github.com/flexmock/flexmock
32
+ Project-URL: Source Code, https://github.com/flexmock/flexmock
33
+ Description-Content-Type: text/markdown
34
+
35
+ <p align="center">
36
+ <img alt="banner" src="https://user-images.githubusercontent.com/25169984/138661460-969caf9e-8e88-4609-87c4-1a0ab9624ee4.png">
37
+ </p>
38
+
39
+ <p align="center"><strong>flexmock</strong> <em>- Mock, stub, and spy library for Python.</em></p>
40
+
41
+ <p align="center">
42
+ <a href="https://pypi.org/project/flexmock/">
43
+ <img src="https://img.shields.io/pypi/v/flexmock" alt="pypi">
44
+ </a>
45
+ <a href="https://github.com/flexmock/flexmock/actions/workflows/ci.yml">
46
+ <img src="https://github.com/flexmock/flexmock/actions/workflows/ci.yml/badge.svg" alt="ci">
47
+ </a>
48
+ <a href="https://flexmock.readthedocs.io/">
49
+ <img src="https://img.shields.io/readthedocs/flexmock" alt="documentation">
50
+ </a>
51
+ <a href="https://codecov.io/gh/flexmock/flexmock">
52
+ <img src="https://codecov.io/gh/flexmock/flexmock/branch/master/graph/badge.svg?token=wRgtiGxhiL" alt="codecov">
53
+ </a>
54
+ <a href="./LICENSE">
55
+ <img src="https://img.shields.io/pypi/l/flexmock" alt="license">
56
+ </a>
57
+ </p>
58
+
59
+ ---
60
+
61
+ Flexmock is a testing library for Python that makes it easy to create mocks, stubs, and fakes.
62
+
63
+ ## Features
64
+
65
+ - **Mock**: Easily create mock objects and make assertions about which methods or attributes were used and arguments they were called with.
66
+ - **Spy**: Proxy calls to object's original methods or attributes and make assertions based on return values or call count.
67
+ - **Fake**: Generate a fake objects to be used in your tests with ease.
68
+ - **Stub**: Create stub objects which replace parts of existing objects and classes with just one call.
69
+ - **No external dependencies**: Flexmock is lightweight and only uses Python standard library. There are no external dependencies.
70
+ - **Simple and intuitive**: Declarations are structured to read more like English sentences than API calls, so they are easy to learn and use.
71
+ - **Fully type annotated**: External API is fully type annotated so it works great with static analysis tools and editor auto-completion.
72
+ - **Integrations with test runners**: Integrates seamlessly with all major test runners like unittest, doctest, and pytest.
73
+ - **Python 3.8+ and PyPy3**: Extensively tested to work with latest Python versions.
74
+
75
+ ## Installation
76
+
77
+ Install with pip:
78
+
79
+ ```
80
+ pip install flexmock
81
+ ```
82
+
83
+ ## Examples
84
+
85
+ Flexmock features smooth integration with pretty much every popular test runner, so no special setup is necessary. Simply importing flexmock into your test module is sufficient to get started with any of the following examples:
86
+
87
+ ```python
88
+ from flexmock import flexmock
89
+ ```
90
+
91
+ ### Mocks
92
+
93
+ Assertions take many flavors and flexmock has many different facilities to generate them:
94
+
95
+ ```python
96
+ # Simplest is ensuring that a certain method is called
97
+ flexmock(Train).should_receive("get_tickets").once()
98
+
99
+ # Of course, it is also possible to provide a default return value
100
+ flexmock(Train).should_receive("get_destination").and_return("Paris").once()
101
+
102
+ # Or check that a method is called with specific arguments
103
+ flexmock(Train).should_receive("set_destination").with_args("Seoul").at_least().twice()
104
+ ```
105
+
106
+ ### Spies
107
+
108
+ Instead of mocking, there are also times when you want to execute the actual method and simply find out how many times it was called. Flexmock uses `should_call` to generate this sort of assertions instead of `should_receive`:
109
+
110
+ ```python
111
+ # Verify that a method is called at most three times
112
+ flexmock(Train).should_call("get_tickets").at_most().times(3)
113
+
114
+ # Make sure that a method is never called with specific arguments
115
+ flexmock(Train).should_call("set_destination").with_args("Helsinki").never()
116
+
117
+ # More complex example with features like argument type and exception matching
118
+ flexmock(Train).should_call("crash").with_args(str, int).and_raise(AttributeError).once()
119
+ ```
120
+
121
+ See more examples in the documentation.
122
+
123
+ ## Documentation
124
+
125
+ User guide, examples, and a full API reference is available at: https://flexmock.readthedocs.io
126
+
127
+ ## Contributing
128
+
129
+ Contributions are absolutely welcome and encouraged! See [CONTRIBUTING.md](https://github.com/flexmock/flexmock/blob/master/CONTRIBUTING.md) to get started.
130
+
@@ -0,0 +1,11 @@
1
+ flexmock/__init__.py,sha256=s_lmZTsOuFGTcSRr1EZW3nhMyNTapalTiPzJQWYfgN8,228
2
+ flexmock/_api.py,sha256=J-FzuVg6alXJVN6AdbSIsn_EvzK10kynG79E9AO361Y,61049
3
+ flexmock/_integrations.py,sha256=RyRxBqtEv8akylGFVh_hn2Irh_lgtJuqaULnpcTcDtE,6007
4
+ flexmock/_pytest_plugin.py,sha256=Jc6H81iZR787DCIAwYPel5swWeANZ_zwn1vEiRM54Ek,1030
5
+ flexmock/exceptions.py,sha256=N4nOPY25yc-VUbOrx1pigzf0dXpfH7kHCpyaVR3bh_Y,563
6
+ flexmock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ flexmock-0.12.2.dist-info/LICENSE,sha256=JkR6IDOxBjK60IMwDVGo6dC6fx71CYXIgb4ovX-qgqY,1534
8
+ flexmock-0.12.2.dist-info/METADATA,sha256=5f9kPi9_0d4WFFnBi7QudpMPCFJQJcsT9q1NkzGA_5A,5615
9
+ flexmock-0.12.2.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
10
+ flexmock-0.12.2.dist-info/entry_points.txt,sha256=QPIoN9FjtXL4VToIFHSVh_8_6k_IhxnnGCGOO7JaW6E,45
11
+ flexmock-0.12.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [pytest11]
2
+ flexmock=flexmock._pytest_plugin
3
+