We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
target() cannot be called outside a hypothesis test
I have a test `assert_allclose_phase` which checks whether two arrays are almost equal modulo one. When running under `hypothesis`, this seems like a sensible place to put `target`, albeit with a(n optional?) `name` argument in case I want to call it twice in the same test. Unfortunately if I do so then I can't use the same function in non-`hypothesis` tests:

```
E           hypothesis.errors.InvalidArgument: Calling target() outside of a test is invalid.
```

My current workaround is to call `target` only if `name` is provided, but this clutters simple tests that wouldn't need a `name`.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `hypothesis-python/src/hypothesis/control.py`
Content:
```
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Most of this work is copyright (C) 2013-2021 David R. MacIver
5 # (david@drmaciver.com), but it contains contributions by others. See
6 # CONTRIBUTING.rst for a full list of people who may hold copyright, and
7 # consult the git log if you need to determine who owns an individual
8 # contribution.
9 #
10 # This Source Code Form is subject to the terms of the Mozilla Public License,
11 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
12 # obtain one at https://mozilla.org/MPL/2.0/.
13 #
14 # END HEADER
15 
16 import math
17 import traceback
18 from typing import NoReturn, Union
19 
20 from hypothesis import Verbosity, settings
21 from hypothesis.errors import CleanupFailed, InvalidArgument, UnsatisfiedAssumption
22 from hypothesis.internal.conjecture.data import ConjectureData
23 from hypothesis.internal.reflection import deprecated_posargs
24 from hypothesis.internal.validation import check_type
25 from hypothesis.reporting import report, verbose_report
26 from hypothesis.utils.dynamicvariables import DynamicVariable
27 
28 
29 def reject() -> NoReturn:
30     raise UnsatisfiedAssumption()
31 
32 
33 def assume(condition: object) -> bool:
34     """Calling ``assume`` is like an :ref:`assert <python:assert>` that marks
35     the example as bad, rather than failing the test.
36 
37     This allows you to specify properties that you *assume* will be
38     true, and let Hypothesis try to avoid similar examples in future.
39     """
40     if not condition:
41         raise UnsatisfiedAssumption()
42     return True
43 
44 
45 _current_build_context = DynamicVariable(None)
46 
47 
48 def current_build_context():
49     context = _current_build_context.value
50     if context is None:
51         raise InvalidArgument("No build context registered")
52     return context
53 
54 
55 class BuildContext:
56     def __init__(self, data, is_final=False, close_on_capture=True):
57         assert isinstance(data, ConjectureData)
58         self.data = data
59         self.tasks = []
60         self.is_final = is_final
61         self.close_on_capture = close_on_capture
62         self.close_on_del = False
63 
64     def __enter__(self):
65         self.assign_variable = _current_build_context.with_value(self)
66         self.assign_variable.__enter__()
67         return self
68 
69     def __exit__(self, exc_type, exc_value, tb):
70         self.assign_variable.__exit__(exc_type, exc_value, tb)
71         if self.close() and exc_type is None:
72             raise CleanupFailed()
73 
74     def close(self):
75         any_failed = False
76         for task in self.tasks:
77             try:
78                 task()
79             except BaseException:
80                 any_failed = True
81                 report(traceback.format_exc())
82         return any_failed
83 
84 
85 def cleanup(teardown):
86     """Register a function to be called when the current test has finished
87     executing. Any exceptions thrown in teardown will be printed but not
88     rethrown.
89 
90     Inside a test this isn't very interesting, because you can just use
91     a finally block, but note that you can use this inside map, flatmap,
92     etc. in order to e.g. insist that a value is closed at the end.
93     """
94     context = _current_build_context.value
95     if context is None:
96         raise InvalidArgument("Cannot register cleanup outside of build context")
97     context.tasks.append(teardown)
98 
99 
100 def should_note():
101     context = _current_build_context.value
102     if context is None:
103         raise InvalidArgument("Cannot make notes outside of a test")
104     return context.is_final or settings.default.verbosity >= Verbosity.verbose
105 
106 
107 def note(value: str) -> None:
108     """Report this value in the final execution."""
109     if should_note():
110         report(value)
111 
112 
113 def event(value: str) -> None:
114     """Record an event that occurred this test. Statistics on number of test
115     runs with each event will be reported at the end if you run Hypothesis in
116     statistics reporting mode.
117 
118     Events should be strings or convertible to them.
119     """
120     context = _current_build_context.value
121     if context is None:
122         raise InvalidArgument("Cannot make record events outside of a test")
123 
124     context.data.note_event(value)
125 
126 
127 @deprecated_posargs
128 def target(observation: Union[int, float], *, label: str = "") -> None:
129     """Calling this function with an ``int`` or ``float`` observation gives it feedback
130     with which to guide our search for inputs that will cause an error, in
131     addition to all the usual heuristics.  Observations must always be finite.
132 
133     Hypothesis will try to maximize the observed value over several examples;
134     almost any metric will work so long as it makes sense to increase it.
135     For example, ``-abs(error)`` is a metric that increases as ``error``
136     approaches zero.
137 
138     Example metrics:
139 
140     - Number of elements in a collection, or tasks in a queue
141     - Mean or maximum runtime of a task (or both, if you use ``label``)
142     - Compression ratio for data (perhaps per-algorithm or per-level)
143     - Number of steps taken by a state machine
144 
145     The optional ``label`` argument can be used to distinguish between
146     and therefore separately optimise distinct observations, such as the
147     mean and standard deviation of a dataset.  It is an error to call
148     ``target()`` with any label more than once per test case.
149 
150     .. note::
151         **The more examples you run, the better this technique works.**
152 
153         As a rule of thumb, the targeting effect is noticeable above
154         :obj:`max_examples=1000 <hypothesis.settings.max_examples>`,
155         and immediately obvious by around ten thousand examples
156         *per label* used by your test.
157 
158     .. note::
159         ``hypothesis.target`` is considered experimental, and may be radically
160         changed or even removed in a future version.  If you find it useful,
161         please let us know so we can share and build on that success!
162 
163     :ref:`statistics` include the best score seen for each label,
164     which can help avoid `the threshold problem
165     <https://hypothesis.works/articles/threshold-problem/>`__ when the minimal
166     example shrinks right down to the threshold of failure (:issue:`2180`).
167     """
168     check_type((int, float), observation, "observation")
169     if not math.isfinite(observation):
170         raise InvalidArgument("observation=%r must be a finite float." % observation)
171     check_type(str, label, "label")
172 
173     context = _current_build_context.value
174     if context is None:
175         raise InvalidArgument("Calling target() outside of a test is invalid.")
176     verbose_report("Saw target(observation=%r, label=%r)" % (observation, label))
177 
178     if label in context.data.target_observations:
179         raise InvalidArgument(
180             "Calling target(%r, label=%r) would overwrite target(%r, label=%r)"
181             % (observation, label, context.data.target_observations[label], label)
182         )
183     else:
184         context.data.target_observations[label] = observation
185
```

Path: `hypothesis-python/src/hypothesis/__init__.py`
Content:
```
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Most of this work is copyright (C) 2013-2021 David R. MacIver
5 # (david@drmaciver.com), but it contains contributions by others. See
6 # CONTRIBUTING.rst for a full list of people who may hold copyright, and
7 # consult the git log if you need to determine who owns an individual
8 # contribution.
9 #
10 # This Source Code Form is subject to the terms of the Mozilla Public License,
11 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
12 # obtain one at https://mozilla.org/MPL/2.0/.
13 #
14 # END HEADER
15 
16 """Hypothesis is a library for writing unit tests which are parametrized by
17 some source of data.
18 
19 It verifies your code against a wide range of input and minimizes any
20 failing examples it finds.
21 """
22 
23 import hypothesis._error_if_old  # noqa  # imported for side-effect of nice error
24 from hypothesis._settings import HealthCheck, Phase, Verbosity, settings
25 from hypothesis.control import assume, event, note, reject, target
26 from hypothesis.core import example, find, given, reproduce_failure, seed
27 from hypothesis.entry_points import run
28 from hypothesis.internal.entropy import register_random
29 from hypothesis.utils.conventions import infer
30 from hypothesis.version import __version__, __version_info__
31 
32 __all__ = [
33     "settings",
34     "Verbosity",
35     "HealthCheck",
36     "Phase",
37     "assume",
38     "reject",
39     "seed",
40     "given",
41     "reproduce_failure",
42     "find",
43     "example",
44     "note",
45     "event",
46     "infer",
47     "register_random",
48     "target",
49     "__version__",
50     "__version_info__",
51 ]
52 
53 run()
54 del run
55
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/hypothesis-python/src/hypothesis/__init__.py b/hypothesis-python/src/hypothesis/__init__.py
--- a/hypothesis-python/src/hypothesis/__init__.py
+++ b/hypothesis-python/src/hypothesis/__init__.py
@@ -22,7 +22,14 @@
 
 import hypothesis._error_if_old  # noqa  # imported for side-effect of nice error
 from hypothesis._settings import HealthCheck, Phase, Verbosity, settings
-from hypothesis.control import assume, event, note, reject, target
+from hypothesis.control import (
+    assume,
+    currently_in_test_context,
+    event,
+    note,
+    reject,
+    target,
+)
 from hypothesis.core import example, find, given, reproduce_failure, seed
 from hypothesis.entry_points import run
 from hypothesis.internal.entropy import register_random
@@ -30,21 +37,22 @@
 from hypothesis.version import __version__, __version_info__
 
 __all__ = [
-    "settings",
-    "Verbosity",
     "HealthCheck",
     "Phase",
+    "Verbosity",
     "assume",
-    "reject",
-    "seed",
-    "given",
-    "reproduce_failure",
-    "find",
-    "example",
-    "note",
+    "currently_in_test_context",
     "event",
+    "example",
+    "find",
+    "given",
     "infer",
+    "note",
     "register_random",
+    "reject",
+    "reproduce_failure",
+    "seed",
+    "settings",
     "target",
     "__version__",
     "__version_info__",
diff --git a/hypothesis-python/src/hypothesis/control.py b/hypothesis-python/src/hypothesis/control.py
--- a/hypothesis-python/src/hypothesis/control.py
+++ b/hypothesis-python/src/hypothesis/control.py
@@ -45,6 +45,18 @@
 _current_build_context = DynamicVariable(None)
 
 
+def currently_in_test_context() -> bool:
+    """Return ``True`` if the calling code is currently running inside an
+    :func:`@given <hypothesis.given>` or :doc:`stateful <stateful>` test,
+    ``False`` otherwise.
+
+    This is useful for third-party integrations and assertion helpers which
+    may be called from traditional or property-based tests, but can only use
+    :func:`~hypothesis.assume` or :func:`~hypothesis.target` in the latter case.
+    """
+    return _current_build_context.value is not None
+
+
 def current_build_context():
     context = _current_build_context.value
     if context is None:

{"golden_diff": "diff --git a/hypothesis-python/src/hypothesis/__init__.py b/hypothesis-python/src/hypothesis/__init__.py\n--- a/hypothesis-python/src/hypothesis/__init__.py\n+++ b/hypothesis-python/src/hypothesis/__init__.py\n@@ -22,7 +22,14 @@\n \n import hypothesis._error_if_old  # noqa  # imported for side-effect of nice error\n from hypothesis._settings import HealthCheck, Phase, Verbosity, settings\n-from hypothesis.control import assume, event, note, reject, target\n+from hypothesis.control import (\n+    assume,\n+    currently_in_test_context,\n+    event,\n+    note,\n+    reject,\n+    target,\n+)\n from hypothesis.core import example, find, given, reproduce_failure, seed\n from hypothesis.entry_points import run\n from hypothesis.internal.entropy import register_random\n@@ -30,21 +37,22 @@\n from hypothesis.version import __version__, __version_info__\n \n __all__ = [\n-    \"settings\",\n-    \"Verbosity\",\n     \"HealthCheck\",\n     \"Phase\",\n+    \"Verbosity\",\n     \"assume\",\n-    \"reject\",\n-    \"seed\",\n-    \"given\",\n-    \"reproduce_failure\",\n-    \"find\",\n-    \"example\",\n-    \"note\",\n+    \"currently_in_test_context\",\n     \"event\",\n+    \"example\",\n+    \"find\",\n+    \"given\",\n     \"infer\",\n+    \"note\",\n     \"register_random\",\n+    \"reject\",\n+    \"reproduce_failure\",\n+    \"seed\",\n+    \"settings\",\n     \"target\",\n     \"__version__\",\n     \"__version_info__\",\ndiff --git a/hypothesis-python/src/hypothesis/control.py b/hypothesis-python/src/hypothesis/control.py\n--- a/hypothesis-python/src/hypothesis/control.py\n+++ b/hypothesis-python/src/hypothesis/control.py\n@@ -45,6 +45,18 @@\n _current_build_context = DynamicVariable(None)\n \n \n+def currently_in_test_context() -> bool:\n+    \"\"\"Return ``True`` if the calling code is currently running inside an\n+    :func:`@given <hypothesis.given>` or :doc:`stateful <stateful>` test,\n+    ``False`` otherwise.\n+\n+    This is useful for third-party integrations and assertion helpers which\n+    may be called from traditional or property-based tests, but can only use\n+    :func:`~hypothesis.assume` or :func:`~hypothesis.target` in the latter case.\n+    \"\"\"\n+    return _current_build_context.value is not None\n+\n+\n def current_build_context():\n     context = _current_build_context.value\n     if context is None:\n", "issue": "target() cannot be called outside a hypothesis test\nI have a test `assert_allclose_phase` which checks whether two arrays are almost equal modulo one. When running under `hypothesis`, this seems like a sensible place to put `target`, albeit with a(n optional?) `name` argument in case I want to call it twice in the same test. Unfortunately if I do so then I can't use the same function in non-`hypothesis` tests:\r\n\r\n```\r\nE           hypothesis.errors.InvalidArgument: Calling target() outside of a test is invalid.\r\n```\r\n\r\nMy current workaround is to call `target` only if `name` is provided, but this clutters simple tests that wouldn't need a `name`.\n", "before_files": [{"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2021 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\nimport math\nimport traceback\nfrom typing import NoReturn, Union\n\nfrom hypothesis import Verbosity, settings\nfrom hypothesis.errors import CleanupFailed, InvalidArgument, UnsatisfiedAssumption\nfrom hypothesis.internal.conjecture.data import ConjectureData\nfrom hypothesis.internal.reflection import deprecated_posargs\nfrom hypothesis.internal.validation import check_type\nfrom hypothesis.reporting import report, verbose_report\nfrom hypothesis.utils.dynamicvariables import DynamicVariable\n\n\ndef reject() -> NoReturn:\n    raise UnsatisfiedAssumption()\n\n\ndef assume(condition: object) -> bool:\n    \"\"\"Calling ``assume`` is like an :ref:`assert <python:assert>` that marks\n    the example as bad, rather than failing the test.\n\n    This allows you to specify properties that you *assume* will be\n    true, and let Hypothesis try to avoid similar examples in future.\n    \"\"\"\n    if not condition:\n        raise UnsatisfiedAssumption()\n    return True\n\n\n_current_build_context = DynamicVariable(None)\n\n\ndef current_build_context():\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"No build context registered\")\n    return context\n\n\nclass BuildContext:\n    def __init__(self, data, is_final=False, close_on_capture=True):\n        assert isinstance(data, ConjectureData)\n        self.data = data\n        self.tasks = []\n        self.is_final = is_final\n        self.close_on_capture = close_on_capture\n        self.close_on_del = False\n\n    def __enter__(self):\n        self.assign_variable = _current_build_context.with_value(self)\n        self.assign_variable.__enter__()\n        return self\n\n    def __exit__(self, exc_type, exc_value, tb):\n        self.assign_variable.__exit__(exc_type, exc_value, tb)\n        if self.close() and exc_type is None:\n            raise CleanupFailed()\n\n    def close(self):\n        any_failed = False\n        for task in self.tasks:\n            try:\n                task()\n            except BaseException:\n                any_failed = True\n                report(traceback.format_exc())\n        return any_failed\n\n\ndef cleanup(teardown):\n    \"\"\"Register a function to be called when the current test has finished\n    executing. Any exceptions thrown in teardown will be printed but not\n    rethrown.\n\n    Inside a test this isn't very interesting, because you can just use\n    a finally block, but note that you can use this inside map, flatmap,\n    etc. in order to e.g. insist that a value is closed at the end.\n    \"\"\"\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot register cleanup outside of build context\")\n    context.tasks.append(teardown)\n\n\ndef should_note():\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot make notes outside of a test\")\n    return context.is_final or settings.default.verbosity >= Verbosity.verbose\n\n\ndef note(value: str) -> None:\n    \"\"\"Report this value in the final execution.\"\"\"\n    if should_note():\n        report(value)\n\n\ndef event(value: str) -> None:\n    \"\"\"Record an event that occurred this test. Statistics on number of test\n    runs with each event will be reported at the end if you run Hypothesis in\n    statistics reporting mode.\n\n    Events should be strings or convertible to them.\n    \"\"\"\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot make record events outside of a test\")\n\n    context.data.note_event(value)\n\n\n@deprecated_posargs\ndef target(observation: Union[int, float], *, label: str = \"\") -> None:\n    \"\"\"Calling this function with an ``int`` or ``float`` observation gives it feedback\n    with which to guide our search for inputs that will cause an error, in\n    addition to all the usual heuristics.  Observations must always be finite.\n\n    Hypothesis will try to maximize the observed value over several examples;\n    almost any metric will work so long as it makes sense to increase it.\n    For example, ``-abs(error)`` is a metric that increases as ``error``\n    approaches zero.\n\n    Example metrics:\n\n    - Number of elements in a collection, or tasks in a queue\n    - Mean or maximum runtime of a task (or both, if you use ``label``)\n    - Compression ratio for data (perhaps per-algorithm or per-level)\n    - Number of steps taken by a state machine\n\n    The optional ``label`` argument can be used to distinguish between\n    and therefore separately optimise distinct observations, such as the\n    mean and standard deviation of a dataset.  It is an error to call\n    ``target()`` with any label more than once per test case.\n\n    .. note::\n        **The more examples you run, the better this technique works.**\n\n        As a rule of thumb, the targeting effect is noticeable above\n        :obj:`max_examples=1000 <hypothesis.settings.max_examples>`,\n        and immediately obvious by around ten thousand examples\n        *per label* used by your test.\n\n    .. note::\n        ``hypothesis.target`` is considered experimental, and may be radically\n        changed or even removed in a future version.  If you find it useful,\n        please let us know so we can share and build on that success!\n\n    :ref:`statistics` include the best score seen for each label,\n    which can help avoid `the threshold problem\n    <https://hypothesis.works/articles/threshold-problem/>`__ when the minimal\n    example shrinks right down to the threshold of failure (:issue:`2180`).\n    \"\"\"\n    check_type((int, float), observation, \"observation\")\n    if not math.isfinite(observation):\n        raise InvalidArgument(\"observation=%r must be a finite float.\" % observation)\n    check_type(str, label, \"label\")\n\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Calling target() outside of a test is invalid.\")\n    verbose_report(\"Saw target(observation=%r, label=%r)\" % (observation, label))\n\n    if label in context.data.target_observations:\n        raise InvalidArgument(\n            \"Calling target(%r, label=%r) would overwrite target(%r, label=%r)\"\n            % (observation, label, context.data.target_observations[label], label)\n        )\n    else:\n        context.data.target_observations[label] = observation\n", "path": "hypothesis-python/src/hypothesis/control.py"}, {"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2021 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\n\"\"\"Hypothesis is a library for writing unit tests which are parametrized by\nsome source of data.\n\nIt verifies your code against a wide range of input and minimizes any\nfailing examples it finds.\n\"\"\"\n\nimport hypothesis._error_if_old  # noqa  # imported for side-effect of nice error\nfrom hypothesis._settings import HealthCheck, Phase, Verbosity, settings\nfrom hypothesis.control import assume, event, note, reject, target\nfrom hypothesis.core import example, find, given, reproduce_failure, seed\nfrom hypothesis.entry_points import run\nfrom hypothesis.internal.entropy import register_random\nfrom hypothesis.utils.conventions import infer\nfrom hypothesis.version import __version__, __version_info__\n\n__all__ = [\n    \"settings\",\n    \"Verbosity\",\n    \"HealthCheck\",\n    \"Phase\",\n    \"assume\",\n    \"reject\",\n    \"seed\",\n    \"given\",\n    \"reproduce_failure\",\n    \"find\",\n    \"example\",\n    \"note\",\n    \"event\",\n    \"infer\",\n    \"register_random\",\n    \"target\",\n    \"__version__\",\n    \"__version_info__\",\n]\n\nrun()\ndel run\n", "path": "hypothesis-python/src/hypothesis/__init__.py"}], "after_files": [{"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2021 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\nimport math\nimport traceback\nfrom typing import NoReturn, Union\n\nfrom hypothesis import Verbosity, settings\nfrom hypothesis.errors import CleanupFailed, InvalidArgument, UnsatisfiedAssumption\nfrom hypothesis.internal.conjecture.data import ConjectureData\nfrom hypothesis.internal.reflection import deprecated_posargs\nfrom hypothesis.internal.validation import check_type\nfrom hypothesis.reporting import report, verbose_report\nfrom hypothesis.utils.dynamicvariables import DynamicVariable\n\n\ndef reject() -> NoReturn:\n    raise UnsatisfiedAssumption()\n\n\ndef assume(condition: object) -> bool:\n    \"\"\"Calling ``assume`` is like an :ref:`assert <python:assert>` that marks\n    the example as bad, rather than failing the test.\n\n    This allows you to specify properties that you *assume* will be\n    true, and let Hypothesis try to avoid similar examples in future.\n    \"\"\"\n    if not condition:\n        raise UnsatisfiedAssumption()\n    return True\n\n\n_current_build_context = DynamicVariable(None)\n\n\ndef currently_in_test_context() -> bool:\n    \"\"\"Return ``True`` if the calling code is currently running inside an\n    :func:`@given <hypothesis.given>` or :doc:`stateful <stateful>` test,\n    ``False`` otherwise.\n\n    This is useful for third-party integrations and assertion helpers which\n    may be called from traditional or property-based tests, but can only use\n    :func:`~hypothesis.assume` or :func:`~hypothesis.target` in the latter case.\n    \"\"\"\n    return _current_build_context.value is not None\n\n\ndef current_build_context():\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"No build context registered\")\n    return context\n\n\nclass BuildContext:\n    def __init__(self, data, is_final=False, close_on_capture=True):\n        assert isinstance(data, ConjectureData)\n        self.data = data\n        self.tasks = []\n        self.is_final = is_final\n        self.close_on_capture = close_on_capture\n        self.close_on_del = False\n\n    def __enter__(self):\n        self.assign_variable = _current_build_context.with_value(self)\n        self.assign_variable.__enter__()\n        return self\n\n    def __exit__(self, exc_type, exc_value, tb):\n        self.assign_variable.__exit__(exc_type, exc_value, tb)\n        if self.close() and exc_type is None:\n            raise CleanupFailed()\n\n    def close(self):\n        any_failed = False\n        for task in self.tasks:\n            try:\n                task()\n            except BaseException:\n                any_failed = True\n                report(traceback.format_exc())\n        return any_failed\n\n\ndef cleanup(teardown):\n    \"\"\"Register a function to be called when the current test has finished\n    executing. Any exceptions thrown in teardown will be printed but not\n    rethrown.\n\n    Inside a test this isn't very interesting, because you can just use\n    a finally block, but note that you can use this inside map, flatmap,\n    etc. in order to e.g. insist that a value is closed at the end.\n    \"\"\"\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot register cleanup outside of build context\")\n    context.tasks.append(teardown)\n\n\ndef should_note():\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot make notes outside of a test\")\n    return context.is_final or settings.default.verbosity >= Verbosity.verbose\n\n\ndef note(value: str) -> None:\n    \"\"\"Report this value in the final execution.\"\"\"\n    if should_note():\n        report(value)\n\n\ndef event(value: str) -> None:\n    \"\"\"Record an event that occurred this test. Statistics on number of test\n    runs with each event will be reported at the end if you run Hypothesis in\n    statistics reporting mode.\n\n    Events should be strings or convertible to them.\n    \"\"\"\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Cannot make record events outside of a test\")\n\n    context.data.note_event(value)\n\n\n@deprecated_posargs\ndef target(observation: Union[int, float], *, label: str = \"\") -> None:\n    \"\"\"Calling this function with an ``int`` or ``float`` observation gives it feedback\n    with which to guide our search for inputs that will cause an error, in\n    addition to all the usual heuristics.  Observations must always be finite.\n\n    Hypothesis will try to maximize the observed value over several examples;\n    almost any metric will work so long as it makes sense to increase it.\n    For example, ``-abs(error)`` is a metric that increases as ``error``\n    approaches zero.\n\n    Example metrics:\n\n    - Number of elements in a collection, or tasks in a queue\n    - Mean or maximum runtime of a task (or both, if you use ``label``)\n    - Compression ratio for data (perhaps per-algorithm or per-level)\n    - Number of steps taken by a state machine\n\n    The optional ``label`` argument can be used to distinguish between\n    and therefore separately optimise distinct observations, such as the\n    mean and standard deviation of a dataset.  It is an error to call\n    ``target()`` with any label more than once per test case.\n\n    .. note::\n        **The more examples you run, the better this technique works.**\n\n        As a rule of thumb, the targeting effect is noticeable above\n        :obj:`max_examples=1000 <hypothesis.settings.max_examples>`,\n        and immediately obvious by around ten thousand examples\n        *per label* used by your test.\n\n    .. note::\n        ``hypothesis.target`` is considered experimental, and may be radically\n        changed or even removed in a future version.  If you find it useful,\n        please let us know so we can share and build on that success!\n\n    :ref:`statistics` include the best score seen for each label,\n    which can help avoid `the threshold problem\n    <https://hypothesis.works/articles/threshold-problem/>`__ when the minimal\n    example shrinks right down to the threshold of failure (:issue:`2180`).\n    \"\"\"\n    check_type((int, float), observation, \"observation\")\n    if not math.isfinite(observation):\n        raise InvalidArgument(\"observation=%r must be a finite float.\" % observation)\n    check_type(str, label, \"label\")\n\n    context = _current_build_context.value\n    if context is None:\n        raise InvalidArgument(\"Calling target() outside of a test is invalid.\")\n    verbose_report(\"Saw target(observation=%r, label=%r)\" % (observation, label))\n\n    if label in context.data.target_observations:\n        raise InvalidArgument(\n            \"Calling target(%r, label=%r) would overwrite target(%r, label=%r)\"\n            % (observation, label, context.data.target_observations[label], label)\n        )\n    else:\n        context.data.target_observations[label] = observation\n", "path": "hypothesis-python/src/hypothesis/control.py"}, {"content": "# This file is part of Hypothesis, which may be found at\n# https://github.com/HypothesisWorks/hypothesis/\n#\n# Most of this work is copyright (C) 2013-2021 David R. MacIver\n# (david@drmaciver.com), but it contains contributions by others. See\n# CONTRIBUTING.rst for a full list of people who may hold copyright, and\n# consult the git log if you need to determine who owns an individual\n# contribution.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public License,\n# v. 2.0. If a copy of the MPL was not distributed with this file, You can\n# obtain one at https://mozilla.org/MPL/2.0/.\n#\n# END HEADER\n\n\"\"\"Hypothesis is a library for writing unit tests which are parametrized by\nsome source of data.\n\nIt verifies your code against a wide range of input and minimizes any\nfailing examples it finds.\n\"\"\"\n\nimport hypothesis._error_if_old  # noqa  # imported for side-effect of nice error\nfrom hypothesis._settings import HealthCheck, Phase, Verbosity, settings\nfrom hypothesis.control import (\n    assume,\n    currently_in_test_context,\n    event,\n    note,\n    reject,\n    target,\n)\nfrom hypothesis.core import example, find, given, reproduce_failure, seed\nfrom hypothesis.entry_points import run\nfrom hypothesis.internal.entropy import register_random\nfrom hypothesis.utils.conventions import infer\nfrom hypothesis.version import __version__, __version_info__\n\n__all__ = [\n    \"HealthCheck\",\n    \"Phase\",\n    \"Verbosity\",\n    \"assume\",\n    \"currently_in_test_context\",\n    \"event\",\n    \"example\",\n    \"find\",\n    \"given\",\n    \"infer\",\n    \"note\",\n    \"register_random\",\n    \"reject\",\n    \"reproduce_failure\",\n    \"seed\",\n    \"settings\",\n    \"target\",\n    \"__version__\",\n    \"__version_info__\",\n]\n\nrun()\ndel run\n", "path": "hypothesis-python/src/hypothesis/__init__.py"}]}