From aea24baf83b1c4499501586f9256af8723373bfe Mon Sep 17 00:00:00 2001 From: Mark Mayo Date: Wed, 2 Nov 2022 16:53:57 +1300 Subject: [PATCH 1/2] pylint fixes Fixes to a bunch of pylint warnings/fixes --- HypothesisWorks.github.io/scratch/voting.py | 6 +- .../scripts/validate_branch_check.py | 2 +- hypothesis-python/setup.py | 4 +- .../src/_hypothesis_pytestplugin.py | 5 +- hypothesis-python/src/hypothesis/_settings.py | 39 ++- hypothesis-python/src/hypothesis/control.py | 3 +- hypothesis-python/src/hypothesis/core.py | 64 ++-- hypothesis-python/src/hypothesis/executors.py | 3 +- .../src/hypothesis/extra/_array_helpers.py | 4 +- .../src/hypothesis/extra/array_api.py | 62 ++-- hypothesis-python/src/hypothesis/extra/cli.py | 3 +- .../src/hypothesis/extra/django/_impl.py | 3 +- .../src/hypothesis/extra/ghostwriter.py | 4 +- .../src/hypothesis/extra/numpy.py | 5 +- .../src/hypothesis/extra/pandas/impl.py | 205 ++++++------- .../src/hypothesis/internal/cache.py | 7 +- .../src/hypothesis/internal/cathetus.py | 7 +- .../src/hypothesis/internal/compat.py | 64 ++-- .../internal/conjecture/choicetree.py | 5 +- .../hypothesis/internal/conjecture/data.py | 19 +- .../internal/conjecture/datatree.py | 55 ++-- .../internal/conjecture/dfa/__init__.py | 2 +- .../hypothesis/internal/conjecture/engine.py | 13 +- .../hypothesis/internal/conjecture/floats.py | 8 +- .../internal/conjecture/junkdrawer.py | 3 +- .../hypothesis/internal/conjecture/pareto.py | 11 +- .../internal/conjecture/shrinker.py | 3 +- .../internal/conjecture/shrinking/dfas.py | 2 +- .../internal/conjecture/shrinking/floats.py | 2 +- .../hypothesis/internal/conjecture/utils.py | 8 +- .../src/hypothesis/internal/escalation.py | 2 +- .../src/hypothesis/internal/filtering.py | 10 +- .../src/hypothesis/internal/floats.py | 17 +- .../src/hypothesis/internal/intervalsets.py | 2 +- .../src/hypothesis/internal/reflection.py | 9 +- .../src/hypothesis/internal/scrutineer.py | 2 +- .../src/hypothesis/internal/validation.py | 2 +- hypothesis-python/src/hypothesis/stateful.py | 3 +- .../src/hypothesis/statistics.py | 11 +- .../hypothesis/strategies/_internal/attrs.py | 4 +- .../strategies/_internal/collections.py | 3 +- .../hypothesis/strategies/_internal/core.py | 21 +- .../strategies/_internal/datetime.py | 30 +- .../strategies/_internal/functions.py | 9 +- .../strategies/_internal/numbers.py | 29 +- .../hypothesis/strategies/_internal/random.py | 10 +- .../hypothesis/strategies/_internal/regex.py | 288 +++++++++--------- .../hypothesis/strategies/_internal/shared.py | 3 +- .../strategies/_internal/strategies.py | 32 +- .../hypothesis/strategies/_internal/types.py | 7 +- .../src/hypothesis/utils/terminal.py | 2 +- .../src/hypothesis/vendor/pretty.py | 28 +- hypothesis-python/tests/array_api/conftest.py | 4 +- .../array_api/test_argument_validation.py | 4 +- .../tests/array_api/test_arrays.py | 10 +- .../tests/array_api/test_from_dtype.py | 5 +- .../tests/array_api/test_indices.py | 4 +- .../tests/array_api/test_pretty.py | 4 +- .../tests/array_api/test_scalar_dtypes.py | 6 +- hypothesis-python/tests/common/__init__.py | 4 +- hypothesis-python/tests/common/debug.py | 4 +- hypothesis-python/tests/common/strategies.py | 3 +- hypothesis-python/tests/conftest.py | 6 +- .../tests/conjecture/test_choice_tree.py | 2 +- .../tests/conjecture/test_dfa.py | 2 +- .../tests/conjecture/test_engine.py | 23 +- .../tests/conjecture/test_float_encoding.py | 2 +- .../tests/conjecture/test_junkdrawer.py | 2 +- .../tests/conjecture/test_optimiser.py | 4 +- .../tests/conjecture/test_shrinker.py | 4 +- .../conjecture/test_shrinking_interface.py | 4 +- .../tests/conjecture/test_test_data.py | 6 +- hypothesis-python/tests/cover/test_charmap.py | 2 +- .../tests/cover/test_complex_numbers.py | 5 +- .../tests/cover/test_composite.py | 5 +- hypothesis-python/tests/cover/test_control.py | 5 +- .../tests/cover/test_database_backend.py | 2 +- .../tests/cover/test_datetimes.py | 5 +- .../tests/cover/test_deadline.py | 8 +- .../tests/cover/test_debug_information.py | 4 +- .../tests/cover/test_deferred_strategies.py | 7 +- .../tests/cover/test_direct_strategies.py | 6 +- .../tests/cover/test_draw_example.py | 4 +- hypothesis-python/tests/cover/test_example.py | 4 +- .../tests/cover/test_explicit_examples.py | 4 +- .../tests/cover/test_feature_flags.py | 4 +- .../tests/cover/test_filter_rewriting.py | 4 +- hypothesis-python/tests/cover/test_find.py | 5 +- .../tests/cover/test_flakiness.py | 10 +- .../tests/cover/test_float_nastiness.py | 4 +- .../cover/test_given_error_conditions.py | 4 +- .../tests/cover/test_health_checks.py | 4 +- hypothesis-python/tests/cover/test_lookup.py | 11 +- .../tests/cover/test_lookup_py310.py | 3 +- .../tests/cover/test_lookup_py38.py | 13 +- .../tests/cover/test_lookup_py39.py | 4 +- hypothesis-python/tests/cover/test_map.py | 5 +- hypothesis-python/tests/cover/test_nothing.py | 4 +- .../tests/cover/test_numerics.py | 5 +- hypothesis-python/tests/cover/test_one_of.py | 5 +- .../tests/cover/test_permutations.py | 7 +- hypothesis-python/tests/cover/test_pretty.py | 11 +- .../cover/test_provisional_strategies.py | 4 +- hypothesis-python/tests/cover/test_randoms.py | 5 +- .../tests/cover/test_recursive.py | 8 +- hypothesis-python/tests/cover/test_regex.py | 6 +- .../tests/cover/test_reporting.py | 4 +- .../tests/cover/test_reproduce_failure.py | 4 +- .../tests/cover/test_sampled_from.py | 7 +- .../tests/cover/test_searchstrategy.py | 4 +- .../tests/cover/test_seed_printing.py | 4 +- .../tests/cover/test_settings.py | 5 +- .../tests/cover/test_simple_characters.py | 6 +- .../tests/cover/test_simple_collections.py | 6 +- .../tests/cover/test_simple_strings.py | 4 +- hypothesis-python/tests/cover/test_slices.py | 4 +- .../tests/cover/test_slippage.py | 17 +- .../tests/cover/test_stateful.py | 6 +- .../tests/cover/test_subnormal_floats.py | 6 +- .../tests/cover/test_testdecorators.py | 23 +- .../tests/cover/test_type_lookup.py | 6 +- .../cover/test_type_lookup_forward_ref.py | 4 +- .../tests/cover/test_unittest.py | 4 +- hypothesis-python/tests/cover/test_uuids.py | 5 +- .../tests/cover/test_validation.py | 4 +- .../tests/cover/test_verbosity.py | 6 +- .../tests/datetime/test_dateutil_timezones.py | 7 +- .../tests/datetime/test_pytz_timezones.py | 12 +- .../tests/datetime/test_zoneinfo_timezones.py | 5 +- hypothesis-python/tests/django/manage.py | 4 +- .../toystore/test_basic_configuration.py | 5 +- .../tests/django/toystore/test_given_forms.py | 8 +- .../django/toystore/test_given_models.py | 25 +- .../tests/ghostwriter/test_ghostwriter_cli.py | 4 +- .../ghostwriter/try-writing-for-installed.py | 2 +- hypothesis-python/tests/lark/test_grammar.py | 4 +- .../tests/nocover/test_argument_validation.py | 4 +- .../nocover/test_boundary_exploration.py | 5 +- .../tests/nocover/test_build_signature.py | 4 +- .../nocover/test_collective_minimization.py | 7 +- .../tests/nocover/test_conjecture_engine.py | 9 +- .../tests/nocover/test_database_usage.py | 5 +- .../tests/nocover/test_drypython_returns.py | 5 +- hypothesis-python/tests/nocover/test_find.py | 4 +- .../tests/nocover/test_flatmap.py | 4 +- .../tests/nocover/test_floating.py | 6 +- .../tests/nocover/test_integer_ranges.py | 4 +- .../tests/nocover/test_interesting_origin.py | 4 +- .../tests/nocover/test_large_examples.py | 3 +- .../tests/nocover/test_nesting.py | 4 +- .../tests/nocover/test_randomization.py | 4 +- .../tests/nocover/test_recursive.py | 25 +- hypothesis-python/tests/nocover/test_regex.py | 3 +- .../tests/nocover/test_reusable_values.py | 6 +- .../tests/nocover/test_sampled_from.py | 5 +- hypothesis-python/tests/nocover/test_sets.py | 4 +- .../tests/nocover/test_sharing.py | 4 +- .../tests/nocover/test_simple_numbers.py | 4 +- .../tests/nocover/test_skipping.py | 9 +- .../tests/nocover/test_stateful.py | 13 +- .../tests/nocover/test_strategy_state.py | 3 +- .../tests/nocover/test_subnormal_floats.py | 6 +- .../nocover/test_type_lookup_forward_ref.py | 4 +- hypothesis-python/tests/nocover/test_uuids.py | 3 +- .../tests/numpy/test_argument_validation.py | 5 +- .../tests/numpy/test_fill_values.py | 4 +- .../tests/numpy/test_floor_ceil.py | 4 +- .../tests/numpy/test_from_dtype.py | 8 +- .../tests/numpy/test_gen_data.py | 6 +- hypothesis-python/tests/numpy/test_gufunc.py | 4 +- .../tests/numpy/test_sampled_from.py | 4 +- .../tests/pandas/test_argument_validation.py | 6 +- .../tests/pandas/test_data_frame.py | 6 +- .../tests/pandas/test_indexes.py | 4 +- hypothesis-python/tests/pandas/test_series.py | 6 +- .../tests/pytest/test_capture.py | 3 +- .../tests/pytest/test_fixtures.py | 6 +- hypothesis-python/tests/pytest/test_runs.py | 5 +- .../tests/quality/test_deferred_strategies.py | 3 +- .../tests/quality/test_discovery_ability.py | 4 +- .../tests/quality/test_float_shrinking.py | 5 +- .../tests/quality/test_normalization.py | 7 +- .../tests/quality/test_poisoned_lists.py | 3 +- .../tests/quality/test_poisoned_trees.py | 18 +- .../tests/quality/test_shrink_quality.py | 13 +- .../tests/redis/test_redis_exampledatabase.py | 4 +- .../test_backported_types.py | 10 +- tooling/src/hypothesistooling/__main__.py | 2 +- 188 files changed, 917 insertions(+), 1024 deletions(-) diff --git a/HypothesisWorks.github.io/scratch/voting.py b/HypothesisWorks.github.io/scratch/voting.py index fbabb40382..f5e41d83cd 100644 --- a/HypothesisWorks.github.io/scratch/voting.py +++ b/HypothesisWorks.github.io/scratch/voting.py @@ -29,8 +29,7 @@ def plurality_winner(election): winners = [c for c, v in counts.items() if v == winning_score] if len(winners) > 1: return None - else: - return winners[0] + return winners[0] def irv_winner(election): @@ -46,8 +45,7 @@ def irv_winner(election): candidates = [c for c in candidates if scores[c] > losing_score] if not candidates: return None - else: - return candidates[0] + return candidates[0] def differing_without_ties(election): diff --git a/hypothesis-python/scripts/validate_branch_check.py b/hypothesis-python/scripts/validate_branch_check.py index e97e097f3f..48ec888f08 100644 --- a/hypothesis-python/scripts/validate_branch_check.py +++ b/hypothesis-python/scripts/validate_branch_check.py @@ -13,7 +13,7 @@ from collections import defaultdict if __name__ == "__main__": - with open("branch-check") as i: + with open("branch-check", encoding="utf-8") as i: data = [json.loads(l) for l in i] checks = defaultdict(set) diff --git a/hypothesis-python/setup.py b/hypothesis-python/setup.py index 0c8c95edb6..050f6be96d 100644 --- a/hypothesis-python/setup.py +++ b/hypothesis-python/setup.py @@ -45,7 +45,7 @@ def local_file(name): # Assignment to placate pyflakes. The actual version is from the exec that follows. __version__ = None -with open(local_file("src/hypothesis/version.py")) as o: +with open(local_file("src/hypothesis/version.py"), encoding="utf-8") as o: exec(o.read()) assert __version__ is not None @@ -133,7 +133,7 @@ def local_file(name): "pytest11": ["hypothesispytest = _hypothesis_pytestplugin"], "console_scripts": ["hypothesis = hypothesis.extra.cli:main"], }, - long_description=open(README).read(), + long_description=open(README, encoding="utf-8").read(), long_description_content_type="text/x-rst", keywords="python testing fuzzing property-based-testing", ) diff --git a/hypothesis-python/src/_hypothesis_pytestplugin.py b/hypothesis-python/src/_hypothesis_pytestplugin.py index afafd52ce4..569e7cdab0 100644 --- a/hypothesis-python/src/_hypothesis_pytestplugin.py +++ b/hypothesis-python/src/_hypothesis_pytestplugin.py @@ -285,11 +285,10 @@ def _stash_get(config, key, default): if hasattr(config, "stash"): # pytest 7 return config.stash.get(key, default) - elif hasattr(config, "_store"): + if hasattr(config, "_store"): # pytest 5.4 return config._store.get(key, default) - else: - return getattr(config, key, default) + return getattr(config, key, default) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): diff --git a/hypothesis-python/src/hypothesis/_settings.py b/hypothesis-python/src/hypothesis/_settings.py index 4743a666fd..e49dfb4bfa 100644 --- a/hypothesis-python/src/hypothesis/_settings.py +++ b/hypothesis-python/src/hypothesis/_settings.py @@ -52,19 +52,18 @@ def __init__(self, name, show_default): def __get__(self, obj, type=None): if obj is None: return self - else: - try: - result = obj.__dict__[self.name] - # This is a gross hack, but it preserves the old behaviour that - # you can change the storage directory and it will be reflected - # in the default database. - if self.name == "database" and result is not_set: - from hypothesis.database import ExampleDatabase - - result = ExampleDatabase(not_set) - return result - except KeyError: - raise AttributeError(self.name) from None + try: + result = obj.__dict__[self.name] + # This is a gross hack, but it preserves the old behaviour that + # you can change the storage directory and it will be reflected + # in the default database. + if self.name == "database" and result is not_set: + from hypothesis.database import ExampleDatabase + + result = ExampleDatabase(not_set) + return result + except KeyError: + raise AttributeError(self.name) from None def __set__(self, obj, value): obj.__dict__[self.name] = value @@ -109,7 +108,7 @@ def __setattr__(cls, name, value): "Cannot assign to the property settings.default - " "consider using settings.load_profile instead." ) - elif not (isinstance(value, settingsProperty) or name.startswith("_")): + if not (isinstance(value, settingsProperty) or name.startswith("_")): raise AttributeError( f"Cannot assign hypothesis.settings.{name}={value!r} - the settings " "class is immutable. You can change the global default " @@ -134,8 +133,7 @@ class settings(metaclass=settingsMeta): def __getattr__(self, name): if name in all_settings: return all_settings[name].default - else: - raise AttributeError(f"settings has no attribute {name}") + raise AttributeError(f"settings has no attribute {name}") def __init__( self, @@ -207,11 +205,10 @@ def __call__(self, test: T) -> T: setattr(test, attr_name, True) _test.TestCase.settings = self return test # type: ignore - else: - raise InvalidArgument( - "@settings(...) can only be used as a decorator on " - "functions, or on subclasses of RuleBasedStateMachine." - ) + raise InvalidArgument( + "@settings(...) can only be used as a decorator on " + "functions, or on subclasses of RuleBasedStateMachine." + ) if hasattr(_test, "_hypothesis_internal_settings_applied"): # Can't use _hypothesis_internal_use_settings as an indicator that # @settings was applied, because @given also assigns that attribute. diff --git a/hypothesis-python/src/hypothesis/control.py b/hypothesis-python/src/hypothesis/control.py index ebf2e53031..4c50cad520 100644 --- a/hypothesis-python/src/hypothesis/control.py +++ b/hypothesis-python/src/hypothesis/control.py @@ -181,7 +181,6 @@ def target(observation: Union[int, float], *, label: str = "") -> Union[int, flo f"Calling target({observation!r}, label={label!r}) would overwrite " f"target({context.data.target_observations[label]!r}, label={label!r})" ) - else: - context.data.target_observations[label] = observation + context.data.target_observations[label] = observation return observation diff --git a/hypothesis-python/src/hypothesis/core.py b/hypothesis-python/src/hypothesis/core.py index d6c784c99f..427708dd06 100644 --- a/hypothesis-python/src/hypothesis/core.py +++ b/hypothesis-python/src/hypothesis/core.py @@ -221,7 +221,7 @@ def decode_failure(blob): prefix = buffer[:1] if prefix == b"\0": return buffer[1:] - elif prefix == b"\1": + if prefix == b"\1": try: return zlib.decompress(buffer[1:]) except zlib.error as err: @@ -302,7 +302,7 @@ def is_invalid_test(test, original_sig, given_arguments, given_kwargs): extra_kwargs = [ k for k in given_kwargs if k not in {p.name for p in pos_params + kwonly_params} ] - if extra_kwargs and (params == [] or params[-1].kind is not params[-1].VAR_KEYWORD): + if extra_kwargs and (not params or params[-1].kind is not params[-1].VAR_KEYWORD): arg = extra_kwargs[0] return invalid( f"{test.__name__}() got an unexpected keyword argument {arg!r}, " @@ -462,17 +462,16 @@ def get_random_for_wrapped_test(test, wrapped_test): if wrapped_test._hypothesis_internal_use_seed is not None: return Random(wrapped_test._hypothesis_internal_use_seed) - elif settings.derandomize: + if settings.derandomize: return Random(int_from_bytes(function_digest(test))) - elif global_force_seed is not None: + if global_force_seed is not None: return Random(global_force_seed) - else: - global _hypothesis_global_random - if _hypothesis_global_random is None: - _hypothesis_global_random = Random() - seed = _hypothesis_global_random.getrandbits(128) - wrapped_test._hypothesis_internal_use_generated_seed = seed - return Random(seed) + global _hypothesis_global_random + if _hypothesis_global_random is None: + _hypothesis_global_random = Random() + seed = _hypothesis_global_random.getrandbits(128) + wrapped_test._hypothesis_internal_use_generated_seed = seed + return Random(seed) def process_arguments_to_given(wrapped_test, arguments, kwargs, given_kwargs, params): @@ -782,27 +781,26 @@ def _execute_once_for_engine(self, data): # block somewhere, suppressing our original StopTest. # We raise a new one here to resume normal operation. raise StopTest(data.testcounter) from e - else: - # The test failed by raising an exception, so we inform the - # engine that this test run was interesting. This is the normal - # path for test runs that fail. - - tb = get_trimmed_traceback() - info = data.extra_information - info.__expected_traceback = format_exception(e, tb) - info.__expected_exception = e - verbose_report(info.__expected_traceback) - - self.failed_normally = True - - interesting_origin = get_interesting_origin(e) - if trace: # pragma: no cover - # Trace collection is explicitly disabled under coverage. - self.explain_traces[interesting_origin].add(trace) - if interesting_origin[0] == DeadlineExceeded: - self.failed_due_to_deadline = True - self.explain_traces.clear() - data.mark_interesting(interesting_origin) + # The test failed by raising an exception, so we inform the + # engine that this test run was interesting. This is the normal + # path for test runs that fail. + + tb = get_trimmed_traceback() + info = data.extra_information + info.__expected_traceback = format_exception(e, tb) + info.__expected_exception = e + verbose_report(info.__expected_traceback) + + self.failed_normally = True + + interesting_origin = get_interesting_origin(e) + if trace: # pragma: no cover + # Trace collection is explicitly disabled under coverage. + self.explain_traces[interesting_origin].add(trace) + if interesting_origin[0] == DeadlineExceeded: + self.failed_due_to_deadline = True + self.explain_traces.clear() + data.mark_interesting(interesting_origin) def run_engine(self): """Run the test function many times, on database input and generated @@ -844,7 +842,7 @@ def run_engine(self): if not self.falsifying_examples: return - elif not (self.settings.report_multiple_bugs and pytest_shows_exceptiongroups): + if not (self.settings.report_multiple_bugs and pytest_shows_exceptiongroups): # Pretend that we only found one failure, by discarding the others. del self.falsifying_examples[:-1] diff --git a/hypothesis-python/src/hypothesis/executors.py b/hypothesis-python/src/hypothesis/executors.py index 67895467e4..d501a16f20 100644 --- a/hypothesis-python/src/hypothesis/executors.py +++ b/hypothesis-python/src/hypothesis/executors.py @@ -61,5 +61,4 @@ def new_style_executor(runner): old_school = executor(runner) if old_school is default_executor: return default_new_style_executor - else: - return lambda data, function: old_school(lambda: function(data)) + return lambda data, function: old_school(lambda: function(data)) diff --git a/hypothesis-python/src/hypothesis/extra/_array_helpers.py b/hypothesis-python/src/hypothesis/extra/_array_helpers.py index 5e6718eea8..84bcc238e4 100644 --- a/hypothesis-python/src/hypothesis/extra/_array_helpers.py +++ b/hypothesis-python/src/hypothesis/extra/_array_helpers.py @@ -241,7 +241,7 @@ def broadcastable_shapes( if s < min_side and s != 1: max_dims = n break - elif not (min_side <= 1 <= max_side or s <= max_side): + if not (min_side <= 1 <= max_side or s <= max_side): max_dims = n break @@ -471,7 +471,7 @@ def mutually_broadcastable_shapes( if s < min_side and s != 1: max_dims = n break - elif not (min_side <= 1 <= max_side or s <= max_side): + if not (min_side <= 1 <= max_side or s <= max_side): max_dims = n break diff --git a/hypothesis-python/src/hypothesis/extra/array_api.py b/hypothesis-python/src/hypothesis/extra/array_api.py index d9c0ceec62..437d4c46dc 100644 --- a/hypothesis-python/src/hypothesis/extra/array_api.py +++ b/hypothesis-python/src/hypothesis/extra/array_api.py @@ -227,7 +227,7 @@ def check_valid_minmax(prefix, val, info_obj): if builtin is bool: return st.booleans() - elif builtin is int: + if builtin is int: iinfo = xp.iinfo(dtype) if min_value is None: min_value = iinfo.min @@ -241,7 +241,7 @@ def check_valid_minmax(prefix, val, info_obj): check_valid_minmax("max", max_value, iinfo) check_valid_interval(min_value, max_value, "min_value", "max_value") return st.integers(min_value=min_value, max_value=max_value) - elif builtin is float: + if builtin is float: finfo = xp.finfo(dtype) kw = {} @@ -292,31 +292,30 @@ def check_valid_minmax(prefix, val, info_obj): kw["exclude_max"] = exclude_max return st.floats(width=finfo.bits, **kw) - else: - # A less-inelegant solution to support complex dtypes exists, but as - # this is currently a draft feature, we might as well wait for - # discussion of complex inspection to resolve first - a better method - # might become available soon enough. - # See https://github.com/data-apis/array-api/issues/433 - for attr in ["float32", "float64", "complex64"]: - if not hasattr(xp, attr): - raise NotImplementedError( - f"Array module {xp.__name__} has no dtype {attr}, which is " - "currently required for xps.from_dtype() to work with " - "any complex dtype." - ) - component_dtype = xp.float32 if dtype == xp.complex64 else xp.float64 - - floats = _from_dtype( - xp, - api_version, - component_dtype, - allow_nan=allow_nan, - allow_infinity=allow_infinity, - allow_subnormal=allow_subnormal, - ) + # A less-inelegant solution to support complex dtypes exists, but as + # this is currently a draft feature, we might as well wait for + # discussion of complex inspection to resolve first - a better method + # might become available soon enough. + # See https://github.com/data-apis/array-api/issues/433 + for attr in ["float32", "float64", "complex64"]: + if not hasattr(xp, attr): + raise NotImplementedError( + f"Array module {xp.__name__} has no dtype {attr}, which is " + "currently required for xps.from_dtype() to work with " + "any complex dtype." + ) + component_dtype = xp.float32 if dtype == xp.complex64 else xp.float64 + + floats = _from_dtype( + xp, + api_version, + component_dtype, + allow_nan=allow_nan, + allow_infinity=allow_infinity, + allow_subnormal=allow_subnormal, + ) - return st.builds(complex, floats, floats) # type: ignore[arg-type] + return st.builds(complex, floats, floats) # type: ignore[arg-type] class ArrayStrategy(st.SearchStrategy): @@ -448,8 +447,7 @@ def do_draw(self, data): if val in seen: elements.reject() continue - else: - seen.add(val) + seen.add(val) try: result[i] = val except Exception as e: @@ -554,7 +552,7 @@ def _arrays( xp, api_version, d, shape, elements=elements, fill=fill, unique=unique ) ) - elif isinstance(dtype, str): + if isinstance(dtype, str): dtype = dtype_from_name(xp, dtype) if isinstance(shape, st.SearchStrategy): @@ -563,7 +561,7 @@ def _arrays( xp, api_version, dtype, s, elements=elements, fill=fill, unique=unique ) ) - elif isinstance(shape, int): + if isinstance(shape, int): shape = (shape,) elif not isinstance(shape, tuple): raise InvalidArgument(f"shape={shape} is not a valid shape or strategy") @@ -606,7 +604,7 @@ def check_dtypes(xp: Any, dtypes: List[DataType], stubs: List[str]) -> None: f"Array module {xp.__name__} does not have the following " f"required dtypes in its namespace: {f_stubs}" ) - elif len(stubs) > 0: + if len(stubs) > 0: warn_on_missing_dtypes(xp, stubs) @@ -1023,7 +1021,7 @@ def floating_dtypes( class StrategiesNamespace(SimpleNamespace): def __init__(self, **kwargs): for attr in ["name", "api_version"]: - if attr not in kwargs.keys(): + if attr not in kwargs: raise ValueError(f"'{attr}' kwarg required") super().__init__(**kwargs) diff --git a/hypothesis-python/src/hypothesis/extra/cli.py b/hypothesis-python/src/hypothesis/extra/cli.py index ac530bce1e..9ce0f986b5 100644 --- a/hypothesis-python/src/hypothesis/extra/cli.py +++ b/hypothesis-python/src/hypothesis/extra/cli.py @@ -120,8 +120,7 @@ def describe_close_matches( matches = get_close_matches(objname, public_names) if matches: return f" Closest matches: {matches!r}" - else: - return "" + return "" if classname is None: try: diff --git a/hypothesis-python/src/hypothesis/extra/django/_impl.py b/hypothesis-python/src/hypothesis/extra/django/_impl.py index 397898cdd7..b53b9ff419 100644 --- a/hypothesis-python/src/hypothesis/extra/django/_impl.py +++ b/hypothesis-python/src/hypothesis/extra/django/_impl.py @@ -44,8 +44,7 @@ def __call__(self, result=None): testMethod = getattr(self, self._testMethodName) if getattr(testMethod, "is_hypothesis_test", False): return unittest.TestCase.__call__(self, result) - else: - return dt.SimpleTestCase.__call__(self, result) + return dt.SimpleTestCase.__call__(self, result) class TestCase(HypothesisTestCase, dt.TestCase): diff --git a/hypothesis-python/src/hypothesis/extra/ghostwriter.py b/hypothesis-python/src/hypothesis/extra/ghostwriter.py index 6b24549a44..ffd99795f4 100644 --- a/hypothesis-python/src/hypothesis/extra/ghostwriter.py +++ b/hypothesis-python/src/hypothesis/extra/ghostwriter.py @@ -230,7 +230,7 @@ def _type_from_doc_fragment(token: str) -> Optional[type]: if "numpy" in sys.modules: if re.fullmatch(r"[Aa]rray[-_ ]?like", token): return sys.modules["numpy"].ndarray - elif token == "dtype": + if token == "dtype": return sys.modules["numpy"].dtype # Natural-language syntax, e.g. "sequence of integers" coll_match = re.fullmatch(r"(\w+) of (\w+)", token) @@ -586,7 +586,7 @@ def _imports_for_strategy(strategy): if isinstance(strategy, LazyStrategy): if strategy.function is st.from_type: return _imports_for_object(strategy._LazyStrategy__args[0]) - elif _get_module(strategy.function).startswith("hypothesis.extra."): + if _get_module(strategy.function).startswith("hypothesis.extra."): return {(_get_module(strategy.function), strategy.function.__name__)} module = _get_module(strategy.function).replace("._array_helpers", ".numpy") return {(module, strategy.function.__name__)} diff --git a/hypothesis-python/src/hypothesis/extra/numpy.py b/hypothesis-python/src/hypothesis/extra/numpy.py index 06376ae42a..c1282696af 100644 --- a/hypothesis-python/src/hypothesis/extra/numpy.py +++ b/hypothesis-python/src/hypothesis/extra/numpy.py @@ -114,7 +114,7 @@ def compat_kw(*args, **kw): if kw[key] is not None: if key.startswith("min_") and kw[key] > kwargs[key]: raise InvalidArgument(msg % ("at least",)) - elif key.startswith("max_") and kw[key] < kwargs[key]: + if key.startswith("max_") and kw[key] < kwargs[key]: raise InvalidArgument(msg % ("at most",)) kw.update({k: v for k, v in kwargs.items() if k in args or k in kw}) return kw @@ -300,8 +300,7 @@ def do_draw(self, data): if result[i] in seen: elements.reject() continue - else: - seen.add(result[i]) + seen.add(result[i]) needs_fill[i] = False if needs_fill.any(): # We didn't fill all of the indices in the early loop, so we diff --git a/hypothesis-python/src/hypothesis/extra/pandas/impl.py b/hypothesis-python/src/hypothesis/extra/pandas/impl.py index 7158d490f3..4d796154b3 100644 --- a/hypothesis-python/src/hypothesis/extra/pandas/impl.py +++ b/hypothesis-python/src/hypothesis/extra/pandas/impl.py @@ -306,15 +306,14 @@ def result(draw): ) return pandas.Series(result_data, index=index, dtype=dtype, name=draw(name)) - else: - return pandas.Series( - (), - index=index, - dtype=dtype - if dtype is not None - else draw(dtype_for_elements_strategy(elements)), - name=draw(name), - ) + return pandas.Series( + (), + index=index, + dtype=dtype + if dtype is not None + else draw(dtype_for_elements_strategy(elements)), + name=draw(name), + ) return result() @@ -490,28 +489,25 @@ def data_frames( if columns is None: if rows is None: raise InvalidArgument("At least one of rows and columns must be provided") - else: - - @st.composite - def rows_only(draw): - index = draw(index_strategy) + @st.composite + def rows_only(draw): + index = draw(index_strategy) - @check_function - def row(): - result = draw(rows) - check_type(abc.Iterable, result, "draw(row)") - return result + @check_function + def row(): + result = draw(rows) + check_type(abc.Iterable, result, "draw(row)") + return result - if len(index) > 0: - return pandas.DataFrame([row() for _ in index], index=index) - else: - # If we haven't drawn any rows we need to draw one row and - # then discard it so that we get a consistent shape for the - # DataFrame. - base = pandas.DataFrame([row()]) - return base.drop(0) + if len(index) > 0: + return pandas.DataFrame([row() for _ in index], index=index) + # If we haven't drawn any rows we need to draw one row and + # then discard it so that we get a consistent shape for the + # DataFrame. + base = pandas.DataFrame([row()]) + return base.drop(0) - return rows_only() + return rows_only() assert columns is not None cols = try_convert(tuple, columns, "columns") @@ -629,91 +625,90 @@ def just_draw_columns(draw): return pandas.DataFrame(data, index=index) return just_draw_columns() - else: - @st.composite - def assign_rows(draw): - index = draw(index_strategy) + @st.composite + def assign_rows(draw): + index = draw(index_strategy) - result = pandas.DataFrame( - OrderedDict( - ( - c.name, - pandas.Series( - np.zeros(dtype=c.dtype, shape=len(index)), dtype=c.dtype - ), - ) - for c in rewritten_columns - ), - index=index, - ) + result = pandas.DataFrame( + OrderedDict( + ( + c.name, + pandas.Series( + np.zeros(dtype=c.dtype, shape=len(index)), dtype=c.dtype + ), + ) + for c in rewritten_columns + ), + index=index, + ) - fills = {} + fills = {} - any_unique = any(c.unique for c in rewritten_columns) + any_unique = any(c.unique for c in rewritten_columns) - if any_unique: - all_seen = [set() if c.unique else None for c in rewritten_columns] - while all_seen[-1] is None: - all_seen.pop() + if any_unique: + all_seen = [set() if c.unique else None for c in rewritten_columns] + while all_seen[-1] is None: + all_seen.pop() - for row_index in range(len(index)): - for _ in range(5): - original_row = draw(rows) - row = original_row - if isinstance(row, dict): - as_list = [None] * len(rewritten_columns) - for i, c in enumerate(rewritten_columns): + for row_index in range(len(index)): + for _ in range(5): + original_row = draw(rows) + row = original_row + if isinstance(row, dict): + as_list = [None] * len(rewritten_columns) + for i, c in enumerate(rewritten_columns): + try: + as_list[i] = row[c.name] + except KeyError: try: - as_list[i] = row[c.name] + as_list[i] = fills[i] except KeyError: - try: - as_list[i] = fills[i] - except KeyError: - if c.fill.is_empty: - raise InvalidArgument( - f"Empty fill strategy in {c!r} cannot " - f"complete row {original_row!r}" - ) from None - fills[i] = draw(c.fill) - as_list[i] = fills[i] - for k in row: - if k not in column_names: - raise InvalidArgument( - "Row %r contains column %r not in columns %r)" - % (row, k, [c.name for c in rewritten_columns]) - ) - row = as_list - if any_unique: - has_duplicate = False - for seen, value in zip(all_seen, row): - if seen is None: - continue - if value in seen: - has_duplicate = True - break - seen.add(value) - if has_duplicate: + if c.fill.is_empty: + raise InvalidArgument( + f"Empty fill strategy in {c!r} cannot " + f"complete row {original_row!r}" + ) from None + fills[i] = draw(c.fill) + as_list[i] = fills[i] + for k in row: + if k not in column_names: + raise InvalidArgument( + "Row %r contains column %r not in columns %r)" + % (row, k, [c.name for c in rewritten_columns]) + ) + row = as_list + if any_unique: + has_duplicate = False + for seen, value in zip(all_seen, row): + if seen is None: continue - row = list(try_convert(tuple, row, "draw(rows)")) - - if len(row) > len(rewritten_columns): + if value in seen: + has_duplicate = True + break + seen.add(value) + if has_duplicate: + continue + row = list(try_convert(tuple, row, "draw(rows)")) + + if len(row) > len(rewritten_columns): + raise InvalidArgument( + f"Row {original_row!r} contains too many entries. Has " + f"{len(row)} but expected at most {len(rewritten_columns)}" + ) + while len(row) < len(rewritten_columns): + c = rewritten_columns[len(row)] + if c.fill.is_empty: raise InvalidArgument( - f"Row {original_row!r} contains too many entries. Has " - f"{len(row)} but expected at most {len(rewritten_columns)}" + f"Empty fill strategy in {c!r} cannot " + f"complete row {original_row!r}" ) - while len(row) < len(rewritten_columns): - c = rewritten_columns[len(row)] - if c.fill.is_empty: - raise InvalidArgument( - f"Empty fill strategy in {c!r} cannot " - f"complete row {original_row!r}" - ) - row.append(draw(c.fill)) - result.iloc[row_index] = row - break - else: - reject() - return result - - return assign_rows() + row.append(draw(c.fill)) + result.iloc[row_index] = row + break + else: + reject() + return result + + return assign_rows() diff --git a/hypothesis-python/src/hypothesis/internal/cache.py b/hypothesis-python/src/hypothesis/internal/cache.py index 891b2111f5..6415755414 100644 --- a/hypothesis-python/src/hypothesis/internal/cache.py +++ b/hypothesis-python/src/hypothesis/internal/cache.py @@ -23,10 +23,9 @@ def sort_key(self): if self.pins == 0: # Unpinned entries are sorted by score. return (0, self.score) - else: - # Pinned entries sort after unpinned ones. Beyond that, we don't - # worry about their relative order. - return (1,) + # Pinned entries sort after unpinned ones. Beyond that, we don't + # worry about their relative order. + return (1,) class GenericCache: diff --git a/hypothesis-python/src/hypothesis/internal/cathetus.py b/hypothesis-python/src/hypothesis/internal/cathetus.py index 30e0d214f1..06053dc41f 100644 --- a/hypothesis-python/src/hypothesis/internal/cathetus.py +++ b/hypothesis-python/src/hypothesis/internal/cathetus.py @@ -35,10 +35,9 @@ def cathetus(h, a): if isinf(h): if isinf(a): return nan - else: - # Deliberately includes the case when isnan(a), because the - # C99 standard mandates that hypot(inf, nan) == inf - return inf + # Deliberately includes the case when isnan(a), because the + # C99 standard mandates that hypot(inf, nan) == inf + return inf h = fabs(h) a = fabs(a) diff --git a/hypothesis-python/src/hypothesis/internal/compat.py b/hypothesis-python/src/hypothesis/internal/compat.py index e7e3bf2a53..304252c22a 100644 --- a/hypothesis-python/src/hypothesis/internal/compat.py +++ b/hypothesis-python/src/hypothesis/internal/compat.py @@ -19,8 +19,8 @@ ExceptionGroup = ExceptionGroup # pragma: no cover except NameError: from exceptiongroup import ( - BaseExceptionGroup as BaseExceptionGroup, - ExceptionGroup as ExceptionGroup, + BaseExceptionGroup, + ExceptionGroup, ) if typing.TYPE_CHECKING: # pragma: no cover from typing_extensions import Concatenate as Concatenate, ParamSpec as ParamSpec @@ -137,31 +137,31 @@ def update_code_location(code, newfile, newlineno): # added to facilitate future-proof code. See BPO-37032 for details. return code.replace(co_filename=newfile, co_firstlineno=newlineno) - else: # pragma: no cover - # This field order is accurate for 3.5 - 3.7, but not 3.8 when a new field - # was added for positional-only arguments. However it also added a .replace() - # method that we use instead of field indices, so they're fine as-is. - CODE_FIELD_ORDER = [ - "co_argcount", - "co_kwonlyargcount", - "co_nlocals", - "co_stacksize", - "co_flags", - "co_code", - "co_consts", - "co_names", - "co_varnames", - "co_filename", - "co_name", - "co_firstlineno", - "co_lnotab", - "co_freevars", - "co_cellvars", - ] - unpacked = [getattr(code, name) for name in CODE_FIELD_ORDER] - unpacked[CODE_FIELD_ORDER.index("co_filename")] = newfile - unpacked[CODE_FIELD_ORDER.index("co_firstlineno")] = newlineno - return type(code)(*unpacked) + # pragma: no cover + # This field order is accurate for 3.5 - 3.7, but not 3.8 when a new field + # was added for positional-only arguments. However it also added a .replace() + # method that we use instead of field indices, so they're fine as-is. + CODE_FIELD_ORDER = [ + "co_argcount", + "co_kwonlyargcount", + "co_nlocals", + "co_stacksize", + "co_flags", + "co_code", + "co_consts", + "co_names", + "co_varnames", + "co_filename", + "co_name", + "co_firstlineno", + "co_lnotab", + "co_freevars", + "co_cellvars", + ] + unpacked = [getattr(code, name) for name in CODE_FIELD_ORDER] + unpacked[CODE_FIELD_ORDER.index("co_filename")] = newfile + unpacked[CODE_FIELD_ORDER.index("co_firstlineno")] = newlineno + return type(code)(*unpacked) # Under Python 2, math.floor and math.ceil returned floats, which cannot @@ -187,10 +187,10 @@ def ceil(x): def bad_django_TestCase(runner): if runner is None or "django.test" not in sys.modules: return False - else: # pragma: no cover - if not isinstance(runner, sys.modules["django.test"].TransactionTestCase): - return False + # pragma: no cover + if not isinstance(runner, sys.modules["django.test"].TransactionTestCase): + return False - from hypothesis.extra.django._impl import HypothesisTestCase + from hypothesis.extra.django._impl import HypothesisTestCase - return not isinstance(runner, HypothesisTestCase) + return not isinstance(runner, HypothesisTestCase) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/choicetree.py b/hypothesis-python/src/hypothesis/internal/conjecture/choicetree.py index 0f1932e8e2..bc85c26bec 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/choicetree.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/choicetree.py @@ -85,9 +85,8 @@ def choose( self.__choices.append(i) self.__node_trail.append(node.children[i]) return v - else: - node.children[i] = DeadNode - node.live_child_count -= 1 + node.children[i] = DeadNode + node.live_child_count -= 1 assert node.live_child_count == 0 raise DeadBranch() diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/data.py b/hypothesis-python/src/hypothesis/internal/conjecture/data.py index 6f40fc0a62..99c49a2e43 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/data.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/data.py @@ -584,8 +584,7 @@ def start(self, i: int) -> int: if i == 0: return 0 - else: - return self.end(i - 1) + return self.end(i - 1) def end(self, i: int) -> int: """Equivalent to self[i].end.""" @@ -621,8 +620,7 @@ def trivial(self, i: int) -> Any: return self.start(i) in self.owner.forced_indices or not any( self.owner.buffer[self.start(i) : self.end(i)] ) - else: - return self[i].trivial + return self[i].trivial def _check_index(self, i: int) -> int: n = len(self) @@ -939,13 +937,12 @@ def draw(self, strategy: "SearchStrategy[Ex]", label: Optional[int] = None) -> " try: if not at_top_level: return strategy.do_draw(self) - else: - assert start_time is not None - strategy.validate() - try: - return strategy.do_draw(self) - finally: - self.draw_times.append(time.perf_counter() - start_time) + assert start_time is not None + strategy.validate() + try: + return strategy.do_draw(self) + finally: + self.draw_times.append(time.perf_counter() - start_time) finally: self.stop_example() diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/datatree.py b/hypothesis-python/src/hypothesis/internal/conjecture/datatree.py index e61f33732a..faf6ec63b5 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/datatree.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/datatree.py @@ -224,35 +224,34 @@ def append_int(n_bits, value): # We've now found a value that is allowed to # vary, so what follows is not fixed. return bytes(novel_prefix) - else: - assert not isinstance(current_node.transition, (Conclusion, Killed)) - if current_node.transition is None: + assert not isinstance(current_node.transition, (Conclusion, Killed)) + if current_node.transition is None: + return bytes(novel_prefix) + branch = current_node.transition + assert isinstance(branch, Branch) + n_bits = branch.bit_length + + check_counter = 0 + while True: + k = random.getrandbits(n_bits) + try: + child = branch.children[k] + except KeyError: + append_int(n_bits, k) return bytes(novel_prefix) - branch = current_node.transition - assert isinstance(branch, Branch) - n_bits = branch.bit_length - - check_counter = 0 - while True: - k = random.getrandbits(n_bits) - try: - child = branch.children[k] - except KeyError: - append_int(n_bits, k) - return bytes(novel_prefix) - if not child.is_exhausted: - append_int(n_bits, k) - current_node = child - break - check_counter += 1 - # We don't expect this assertion to ever fire, but coverage - # wants the loop inside to run if you have branch checking - # on, hence the pragma. - assert ( # pragma: no cover - check_counter != 1000 - or len(branch.children) < (2**n_bits) - or any(not v.is_exhausted for v in branch.children.values()) - ) + if not child.is_exhausted: + append_int(n_bits, k) + current_node = child + break + check_counter += 1 + # We don't expect this assertion to ever fire, but coverage + # wants the loop inside to run if you have branch checking + # on, hence the pragma. + assert ( # pragma: no cover + check_counter != 1000 + or len(branch.children) < (2**n_bits) + or any(not v.is_exhausted for v in branch.children.values()) + ) def rewrite(self, buffer): """Use previously seen ConjectureData objects to return a tuple of diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/dfa/__init__.py b/hypothesis-python/src/hypothesis/internal/conjecture/dfa/__init__.py index 40b87f69b6..1df058753a 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/dfa/__init__.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/dfa/__init__.py @@ -177,7 +177,7 @@ def pop(): assert not self.is_dead(k) cache[k] = inf break - elif k not in cache and not self.is_dead(k): + if k not in cache and not self.is_dead(k): stack.append(k) stack_set.add(k) break diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/engine.py b/hypothesis-python/src/hypothesis/internal/conjecture/engine.py index 750e68edd4..f0de68011a 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/engine.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/engine.py @@ -583,7 +583,7 @@ def should_generate_more(self): return True # Users who disable shrinking probably want to exit as fast as possible. # If we've found a bug and won't report more than one, stop looking. - elif ( + if ( Phase.shrink not in self.settings.phases or not self.settings.report_multiple_bugs ): @@ -972,12 +972,11 @@ def clear_secondary_key(self): if sort_key(c) > cap: break - else: - self.cached_test_function(c) - # We unconditionally remove c from the secondary key as it - # is either now primary or worse than our primary example - # of this reason for interestingness. - self.settings.database.delete(self.secondary_key, c) + self.cached_test_function(c) + # We unconditionally remove c from the secondary key as it + # is either now primary or worse than our primary example + # of this reason for interestingness. + self.settings.database.delete(self.secondary_key, c) def shrink(self, example, predicate=None, allow_transition=None): s = self.new_shrinker(example, predicate, allow_transition) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/floats.py b/hypothesis-python/src/hypothesis/internal/conjecture/floats.py index 5608570130..2a4dff9459 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/floats.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/floats.py @@ -92,8 +92,7 @@ def exponent_key(e: int) -> float: unbiased = e - BIAS if unbiased < 0: return 10000 - unbiased - else: - return unbiased + return unbiased ENCODING_TABLE = array("H", sorted(range(MAX_EXPONENT + 1), key=exponent_key)) @@ -192,9 +191,8 @@ def lex_to_float(i: int) -> float: assert mantissa.bit_length() <= 52 return int_to_float((exponent << 52) | mantissa) - else: - integral_part = i & ((1 << 56) - 1) - return float(integral_part) + integral_part = i & ((1 << 56) - 1) + return float(integral_part) def float_to_lex(f: float) -> int: diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py b/hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py index dc3d0a0f9c..8678153c9a 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py @@ -223,8 +223,7 @@ def __getitem__(self, i: int) -> int: default = self.__values[i] if self.__mask is None: return default - else: - return self.__mask.get(i, default) + return self.__mask.get(i, default) def __setitem__(self, i: int, v: int) -> None: i = self.__check_index(i) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/pareto.py b/hypothesis-python/src/hypothesis/internal/conjecture/pareto.py index d82408f97e..17c7ad704c 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/pareto.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/pareto.py @@ -52,12 +52,11 @@ def dominance(left, right): result = dominance(left=right, right=left) if result == DominanceRelation.LEFT_DOMINATES: return DominanceRelation.RIGHT_DOMINATES - else: - # Because we have sort_key(left) < sort_key(right) the only options - # are that right is better than left or that the two are - # incomparable. - assert result == DominanceRelation.NO_DOMINANCE - return result + # Because we have sort_key(left) < sort_key(right) the only options + # are that right is better than left or that the two are + # incomparable. + assert result == DominanceRelation.NO_DOMINANCE + return result # Either left is better or there is no dominance relationship. assert sort_key(left.buffer) < sort_key(right.buffer) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py b/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py index 2ee5d5f4cb..5ce8ea2875 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py @@ -1301,8 +1301,7 @@ def run_block_program(self, i, description, original, repeats=1): value = int_from_bytes(attempt[u:v]) if value == 0: return False - else: - attempt[u:v] = int_to_bytes(value - 1, v - u) + attempt[u:v] = int_to_bytes(value - 1, v - u) elif d == "X": del attempt[u:v] else: diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/dfas.py b/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/dfas.py index 8fb42a33b7..e2e046af5c 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/dfas.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/dfas.py @@ -126,7 +126,7 @@ def learn_a_new_dfa(runner, u, v, predicate): allow_discards = worse.has_discards or better.has_discards def is_valid_core(s): - if not (len(u_core) <= len(s) <= len(v_core)): + if not len(u_core) <= len(s) <= len(v_core): return False buf = prefix + s + suffix result = runner.cached_test_function(buf) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/floats.py b/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/floats.py index ceab3f5f0f..7f958093d7 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/floats.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/shrinking/floats.py @@ -33,7 +33,7 @@ def make_immutable(self, f): def check_invariants(self, value): # We only handle positive floats because we encode the sign separately # anyway. - assert not (value < 0) + assert not value < 0 def left_is_better(self, left, right): lex1 = float_to_lex(left) diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/utils.py b/hypothesis-python/src/hypothesis/internal/conjecture/utils.py index 2a4d73eabc..f9ed756655 100644 --- a/hypothesis-python/src/hypothesis/internal/conjecture/utils.py +++ b/hypothesis-python/src/hypothesis/internal/conjecture/utils.py @@ -384,8 +384,7 @@ def sample(self, data: "ConjectureData") -> int: data.stop_example() if use_alternate: return alternate - else: - return base + return base INT_SIZES = (8, 16, 32, 64, 128) @@ -449,9 +448,8 @@ def more(self) -> bool: if should_continue: self.count += 1 return True - else: - self.data.stop_example() - return False + self.data.stop_example() + return False def reject(self): """Reject the last example (i.e. don't count it towards our budget of diff --git a/hypothesis-python/src/hypothesis/internal/escalation.py b/hypothesis-python/src/hypothesis/internal/escalation.py index 4eb1fd421b..59d504e137 100644 --- a/hypothesis-python/src/hypothesis/internal/escalation.py +++ b/hypothesis-python/src/hypothesis/internal/escalation.py @@ -1,4 +1,4 @@ -# This file is part of Hypothesis, which may be found at +v# This file is part of Hypothesis, which may be found at # https://github.com/HypothesisWorks/hypothesis/ # # Copyright the Hypothesis Authors. diff --git a/hypothesis-python/src/hypothesis/internal/filtering.py b/hypothesis-python/src/hypothesis/internal/filtering.py index 8f15ba9ecf..7b13e47852 100644 --- a/hypothesis-python/src/hypothesis/internal/filtering.py +++ b/hypothesis-python/src/hypothesis/internal/filtering.py @@ -90,19 +90,19 @@ def comp_to_kwargs(x: ast.AST, op: ast.AST, y: ast.AST, *, argname: str) -> dict if a is ARG: return {"max_value": b, "exclude_max": True} return {"min_value": a, "exclude_min": True} - elif isinstance(op, ast.LtE): + if isinstance(op, ast.LtE): if a is ARG: return {"max_value": b} return {"min_value": a} - elif isinstance(op, ast.Eq): + if isinstance(op, ast.Eq): if a is ARG: return {"min_value": b, "max_value": b} return {"min_value": a, "max_value": a} - elif isinstance(op, ast.GtE): + if isinstance(op, ast.GtE): if a is ARG: return {"min_value": b} return {"max_value": a} - elif isinstance(op, ast.Gt): + if isinstance(op, ast.Gt): if a is ARG: return {"min_value": b, "exclude_min": True} return {"max_value": a, "exclude_max": True} @@ -235,7 +235,7 @@ def get_numeric_predicate_bounds(predicate: Predicate) -> ConstructivePredicate: if isinstance(tree, ast.Lambda) and len(tree.args.args) == 1: return numeric_bounds_from_ast(tree.body, tree.args.args[0].arg, unchanged) - elif isinstance(tree, ast.FunctionDef) and len(tree.args.args) == 1: + if isinstance(tree, ast.FunctionDef) and len(tree.args.args) == 1: if len(tree.body) != 1 or not isinstance(tree.body[0], ast.Return): # If the body of the function is anything but `return `, # i.e. as simple as a lambda, we can't process it (yet). diff --git a/hypothesis-python/src/hypothesis/internal/floats.py b/hypothesis-python/src/hypothesis/internal/floats.py index d2cb2c94f8..399e0ac6d5 100644 --- a/hypothesis-python/src/hypothesis/internal/floats.py +++ b/hypothesis-python/src/hypothesis/internal/floats.py @@ -30,10 +30,9 @@ def float_of(x, width): assert width in (16, 32, 64) if width == 64: return float(x) - elif width == 32: + if width == 32: return reinterpret_bits(float(x), "!f", "!f") - else: - return reinterpret_bits(float(x), "!e", "!e") + return reinterpret_bits(float(x), "!e", "!e") def is_negative(x: SupportsFloat) -> bool: @@ -50,13 +49,11 @@ def count_between_floats(x, y, width=64): if is_negative(x): if is_negative(y): return float_to_int(x, width) - float_to_int(y, width) + 1 - else: - return count_between_floats(x, -0.0, width) + count_between_floats( - 0.0, y, width - ) - else: - assert not is_negative(y) - return float_to_int(y, width) - float_to_int(x, width) + 1 + return count_between_floats(x, -0.0, width) + count_between_floats( + 0.0, y, width + ) + assert not is_negative(y) + return float_to_int(y, width) - float_to_int(x, width) + 1 def float_to_int(value, width=64): diff --git a/hypothesis-python/src/hypothesis/internal/intervalsets.py b/hypothesis-python/src/hypothesis/internal/intervalsets.py index 5bdd731d2d..5d7c225bb6 100644 --- a/hypothesis-python/src/hypothesis/internal/intervalsets.py +++ b/hypothesis-python/src/hypothesis/internal/intervalsets.py @@ -56,7 +56,7 @@ def index(self, value): for offset, (u, v) in zip(self.offsets, self.intervals): if u == value: return offset - elif u > value: + if u > value: raise ValueError(f"{value} is not in list") if value <= v: return offset + (value - u) diff --git a/hypothesis-python/src/hypothesis/internal/reflection.py b/hypothesis-python/src/hypothesis/internal/reflection.py index 736d4ede9e..dba3775f1a 100644 --- a/hypothesis-python/src/hypothesis/internal/reflection.py +++ b/hypothesis-python/src/hypothesis/internal/reflection.py @@ -386,7 +386,7 @@ def get_pretty_function_description(f): name = f.__name__ if name == "": return extract_lambda_source(f) - elif isinstance(f, (types.MethodType, types.BuiltinMethodType)): + if isinstance(f, (types.MethodType, types.BuiltinMethodType)): self = f.__self__ # Some objects, like `builtins.abs` are of BuiltinMethodType but have # their module as __self__. This might include c-extensions generally? @@ -401,11 +401,10 @@ def get_pretty_function_description(f): def nicerepr(v): if inspect.isfunction(v): return get_pretty_function_description(v) - elif isinstance(v, type): + if isinstance(v, type): return v.__name__ - else: - # With TypeVar T, show List[T] instead of TypeError on List[~T] - return re.sub(r"(\[)~([A-Z][a-z]*\])", r"\g<1>\g<2>", pretty(v)) + # With TypeVar T, show List[T] instead of TypeError on List[~T] + return re.sub(r"(\[)~([A-Z][a-z]*\])", r"\g<1>\g<2>", pretty(v)) def repr_call(f, args, kwargs, reorder=True): diff --git a/hypothesis-python/src/hypothesis/internal/scrutineer.py b/hypothesis-python/src/hypothesis/internal/scrutineer.py index 3071111f6a..f2587d1d2a 100644 --- a/hypothesis-python/src/hypothesis/internal/scrutineer.py +++ b/hypothesis-python/src/hypothesis/internal/scrutineer.py @@ -38,7 +38,7 @@ def __init__(self): def trace(self, frame, event, arg): if event == "call": return self.trace - elif event == "line": + if event == "line": fname = frame.f_code.co_filename if should_trace_file(fname): current_location = (fname, frame.f_lineno) diff --git a/hypothesis-python/src/hypothesis/internal/validation.py b/hypothesis-python/src/hypothesis/internal/validation.py index da7dfbb937..9847ab183c 100644 --- a/hypothesis-python/src/hypothesis/internal/validation.py +++ b/hypothesis-python/src/hypothesis/internal/validation.py @@ -72,7 +72,7 @@ def check_valid_magnitude(value, name): check_valid_bound(value, name) if value is not None and value < 0: raise InvalidArgument(f"{name}={value!r} must not be negative.") - elif value is None and name == "min_magnitude": + if value is None and name == "min_magnitude": raise InvalidArgument("Use min_magnitude=0 or omit the argument entirely.") diff --git a/hypothesis-python/src/hypothesis/stateful.py b/hypothesis-python/src/hypothesis/stateful.py index c81b66a903..80c1f5191f 100644 --- a/hypothesis-python/src/hypothesis/stateful.py +++ b/hypothesis-python/src/hypothesis/stateful.py @@ -448,8 +448,7 @@ def do_draw(self, data): position = cu.integer_range(data, 0, len(bundle) - 1, center=len(bundle)) if self.consume: return bundle.pop(position) - else: - return bundle[position] + return bundle[position] class Bundle(SearchStrategy[Ex]): diff --git a/hypothesis-python/src/hypothesis/statistics.py b/hypothesis-python/src/hypothesis/statistics.py index 73377077cd..ace19d0eff 100644 --- a/hypothesis-python/src/hypothesis/statistics.py +++ b/hypothesis-python/src/hypothesis/statistics.py @@ -31,14 +31,13 @@ def describe_targets(best_targets): # See https://github.com/HypothesisWorks/hypothesis/issues/2180 if not best_targets: return [] - elif len(best_targets) == 1: + if len(best_targets) == 1: label, score = next(iter(best_targets.items())) return [f"Highest target score: {score:g} (label={label!r})"] - else: - lines = ["Highest target scores:"] - for label, score in sorted(best_targets.items(), key=lambda x: x[::-1]): - lines.append(f"{score:>16g} (label={label!r})") - return lines + lines = ["Highest target scores:"] + for label, score in sorted(best_targets.items(), key=lambda x: x[::-1]): + lines.append(f"{score:>16g} (label={label!r})") + return lines def describe_statistics(stats_dict): diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/attrs.py b/hypothesis-python/src/hypothesis/strategies/_internal/attrs.py index d4f56a1f3a..3428124597 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/attrs.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/attrs.py @@ -98,7 +98,7 @@ def types_to_strategy(attrib, types): if isinstance(typ, tuple): return st.one_of(*map(st.from_type, typ)) return st.from_type(typ) - elif types: + if types: # We have a list of tuples of types, and want to find a type # (or tuple of types) that is a subclass of all of of them. type_tuples = [k if isinstance(k, tuple) else (k,) for k in types] @@ -123,7 +123,7 @@ def types_to_strategy(attrib, types): converter = getattr(attrib, "converter", None) if isinstance(converter, type): return st.from_type(converter) - elif callable(converter): + if callable(converter): hints = get_type_hints(converter) if "return" in hints: return st.from_type(hints["return"]) diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/collections.py b/hypothesis-python/src/hypothesis/strategies/_internal/collections.py index 5476239ad7..be40f9f056 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/collections.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/collections.py @@ -167,8 +167,7 @@ def do_validate(self): def calc_is_empty(self, recur): if self.min_size == 0: return False - else: - return recur(self.element_strategy) + return recur(self.element_strategy) def do_draw(self, data): if self.element_strategy.is_empty: diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/core.py b/hypothesis-python/src/hypothesis/strategies/_internal/core.py index fd71cef608..1aba8166ea 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/core.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/core.py @@ -265,8 +265,7 @@ def lists( "cannot specify both unique and unique_by " "(you probably only want to set unique_by)" ) - else: - unique_by = identity + unique_by = identity if max_size == 0: return builds(list) @@ -460,7 +459,7 @@ def fixed_dictionaries( check_type(dict, optional, "optional") for k, v in optional.items(): check_strategy(v, f"optional[{k!r}]") - if type(mapping) != type(optional): + if not isinstance(mapping, type(optional)): raise InvalidArgument( "Got arguments of different types: mapping=%s, optional=%s" % (nicerepr(type(mapping)), nicerepr(type(optional))) @@ -1094,9 +1093,9 @@ def as_strategy(strat_or_callable, thing, final=True): pass if ( hasattr(typing, "_TypedDictMeta") - and type(thing) is typing._TypedDictMeta # type: ignore + and isinstance(thing, typing._TypedDictMeta) or hasattr(types.typing_extensions, "_TypedDictMeta") # type: ignore - and type(thing) is types.typing_extensions._TypedDictMeta # type: ignore + and isinstance(thing, types.typing_extensions._TypedDictMeta) ): # pragma: no cover # The __optional_keys__ attribute may or may not be present, but if there's no # way to tell and we just have to assume that everything is required. @@ -1773,10 +1772,8 @@ def do_draw(self, data): "Cannot use runner() strategy with no " "associated runner or explicit default." ) - else: - return self.default - else: - return runner + return self.default + return runner @defines_strategy(force_reusable_values=True) @@ -1899,14 +1896,14 @@ def register_type_strategy( f"custom_type={custom_type!r} is not allowed to be registered, " f"because there is no such thing as a runtime instance of {custom_type!r}" ) - elif not (isinstance(strategy, SearchStrategy) or callable(strategy)): + if not (isinstance(strategy, SearchStrategy) or callable(strategy)): raise InvalidArgument( "strategy=%r must be a SearchStrategy, or a function that takes " "a generic type and returns a specific SearchStrategy" ) - elif isinstance(strategy, SearchStrategy) and strategy.is_empty: + if isinstance(strategy, SearchStrategy) and strategy.is_empty: raise InvalidArgument("strategy=%r must not be empty") - elif types.has_type_arguments(custom_type): + if types.has_type_arguments(custom_type): origin = getattr(custom_type, "__origin__", None) raise InvalidArgument( f"Cannot register generic type {custom_type!r}, because it has type " diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/datetime.py b/hypothesis-python/src/hypothesis/strategies/_internal/datetime.py index 5ec85ec858..6ae2717780 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/datetime.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/datetime.py @@ -103,7 +103,7 @@ def draw_capped_multipart( data, min_value, max_value, duration_names=DATENAMES + TIMENAMES ): assert isinstance(min_value, (dt.date, dt.time, dt.datetime)) - assert type(min_value) == type(max_value) + assert isinstance(min_value, type(max_value)) assert min_value <= max_value result = {} cap_low, cap_high = True, True @@ -346,21 +346,21 @@ def _valid_key_cacheable(tzpath, key): if os.path.exists(os.path.join(root, key)): # pragma: no branch # No branch because most systems only have one TZPATH component. return True - else: # pragma: no cover - # This branch is only taken for names which are known to zoneinfo - # but not present on the filesystem, i.e. on Windows with tzdata, - # and so is never executed by our coverage tests. - *package_loc, resource_name = key.split("/") - package = "tzdata.zoneinfo." + ".".join(package_loc) + # pragma: no cover + # This branch is only taken for names which are known to zoneinfo + # but not present on the filesystem, i.e. on Windows with tzdata, + # and so is never executed by our coverage tests. + *package_loc, resource_name = key.split("/") + package = "tzdata.zoneinfo." + ".".join(package_loc) + try: try: - try: - traversable = resources.files(package) / resource_name - return traversable.exists() - except (AttributeError, ValueError): - # .files() was added in Python 3.9 - return resources.is_resource(package, resource_name) - except ModuleNotFoundError: - return False + traversable = resources.files(package) / resource_name + return traversable.exists() + except (AttributeError, ValueError): + # .files() was added in Python 3.9 + return resources.is_resource(package, resource_name) + except ModuleNotFoundError: + return False @defines_strategy(force_reusable_values=True) diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/functions.py b/hypothesis-python/src/hypothesis/strategies/_internal/functions.py index 9eb6fcb755..2ce1d3058a 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/functions.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/functions.py @@ -53,10 +53,9 @@ def inner(*args, **kwargs): rep = repr_call(self.like, args, kwargs, reorder=False) note(f"Called function: {rep} -> {cache[key]!r}") return cache[key] - else: - val = data.draw(self.returns) - rep = repr_call(self.like, args, kwargs, reorder=False) - note(f"Called function: {rep} -> {val!r}") - return val + val = data.draw(self.returns) + rep = repr_call(self.like, args, kwargs, reorder=False) + note(f"Called function: {rep} -> {val!r}") + return val return inner diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/numbers.py b/hypothesis-python/src/hypothesis/strategies/_internal/numbers.py index 380c8732cf..d558b93f4f 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/numbers.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/numbers.py @@ -75,24 +75,22 @@ def do_draw(self, data): if self.start is None: if self.end <= 0: return self.end - abs(d.unbounded_integers(data)) - else: - probe = self.end + 1 - while self.end < probe: - data.start_example(ONE_BOUND_INTEGERS_LABEL) - probe = d.unbounded_integers(data) - data.stop_example(discard=self.end < probe) - return probe + probe = self.end + 1 + while self.end < probe: + data.start_example(ONE_BOUND_INTEGERS_LABEL) + probe = d.unbounded_integers(data) + data.stop_example(discard=self.end < probe) + return probe if self.end is None: if self.start >= 0: return self.start + abs(d.unbounded_integers(data)) - else: - probe = self.start - 1 - while probe < self.start: - data.start_example(ONE_BOUND_INTEGERS_LABEL) - probe = d.unbounded_integers(data) - data.stop_example(discard=probe < self.start) - return probe + probe = self.start - 1 + while probe < self.start: + data.start_example(ONE_BOUND_INTEGERS_LABEL) + probe = d.unbounded_integers(data) + data.stop_example(discard=probe < self.start) + return probe # For bounded integers, make the bounds and near-bounds more likely. forced = None @@ -209,8 +207,7 @@ def _sign_aware_lte(x: float, y: float) -> bool: """Less-than-or-equals, but strictly orders -0.0 and 0.0""" if x == 0.0 == y: return math.copysign(1.0, x) <= math.copysign(1.0, y) - else: - return x <= y + return x <= y class FloatStrategy(SearchStrategy): diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/random.py b/hypothesis-python/src/hypothesis/strategies/_internal/random.py index 2c8997e523..be02f0f8e7 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/random.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/random.py @@ -177,8 +177,7 @@ def state_for_seed(data, seed): def normalize_zero(f: float) -> float: if f == 0.0: return 0.0 - else: - return f + return f class ArtificialRandom(HypothesisRandom): @@ -432,7 +431,6 @@ def do_draw(self, data): if self.__use_true_random: seed = data.draw_bits(64) return TrueRandom(seed=seed, note_method_calls=self.__note_method_calls) - else: - return ArtificialRandom( - note_method_calls=self.__note_method_calls, data=data - ) + return ArtificialRandom( + note_method_calls=self.__note_method_calls, data=data + ) diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/regex.py b/hypothesis-python/src/hypothesis/strategies/_internal/regex.py index b93e8d192b..96423d9afd 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/regex.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/regex.py @@ -72,8 +72,7 @@ def group_conditional(draw, group_name, if_yes, if_no): cache = draw(GROUP_CACHE_STRATEGY) if group_name in cache: return draw(if_yes) - else: - return draw(if_no) + return draw(if_no) @st.composite @@ -234,8 +233,7 @@ def regex_strategy(regex, fullmatch, *, _temp_jsonschema_hack_no_end_newline=Fal if not parsed: if is_unicode: return st.text() - else: - return st.binary() + return st.binary() if is_unicode: base_padding_strategy = st.text() @@ -351,151 +349,147 @@ def recurse(codes): if len(strategies) == 1: return strategies[0] return st.tuples(*strategies).map(empty.join) - else: - # Single code - code, value = codes - if code == sre.LITERAL: - # Regex 'a' (single char) - c = to_char(value) - if ( - context.flags & re.IGNORECASE - and c != c.swapcase() - and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None - ): - # We do the explicit check for swapped-case matching because - # eg 'ß'.upper() == 'SS' and ignorecase doesn't match it. - return st.sampled_from([c, c.swapcase()]) - return st.just(c) - - elif code == sre.NOT_LITERAL: - # Regex '[^a]' (negation of a single char) - c = to_char(value) - blacklist = {c} - if ( - context.flags & re.IGNORECASE - and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None - ): - # There are a few cases where .swapcase() returns two characters, - # but is still a case-insensitive match. In such cases we add *both* - # characters to our blacklist, to avoid doing the wrong thing for - # patterns such as r"[^\u0130]+" where "i\u0307" matches. - # - # (that's respectively 'Latin letter capital I with dot above' and - # 'latin latter i' + 'combining dot above'; see issue #2657) - # - # As a final additional wrinkle, "latin letter capital I" *also* - # case-insensitive-matches, with or without combining dot character. - # We therefore have to chain .swapcase() calls until a fixpoint. - stack = [c.swapcase()] - while stack: - for char in stack.pop(): - blacklist.add(char) - stack.extend(set(char.swapcase()) - blacklist) - - if is_unicode: - return st.characters(blacklist_characters=blacklist) - else: - return binary_char.filter(lambda c: c not in blacklist) - - elif code == sre.IN: - # Regex '[abc0-9]' (set of characters) - negate = value[0][0] == sre.NEGATE - if is_unicode: - builder = CharactersBuilder(negate, context.flags) - else: - builder = BytesBuilder(negate, context.flags) - - for charset_code, charset_value in value: - if charset_code == sre.NEGATE: - # Regex '[^...]' (negation) - # handled by builder = CharactersBuilder(...) above - pass - elif charset_code == sre.LITERAL: - # Regex '[a]' (single char) - builder.add_char(charset_value) - elif charset_code == sre.RANGE: - # Regex '[a-z]' (char range) - low, high = charset_value - for char_code in range(low, high + 1): - builder.add_char(char_code) - elif charset_code == sre.CATEGORY: - # Regex '[\w]' (char category) - builder.add_category(charset_value) - else: - # Currently there are no known code points other than - # handled here. This code is just future proofing - raise NotImplementedError(f"Unknown charset code: {charset_code}") - return builder.strategy - - elif code == sre.ANY: - # Regex '.' (any char) - if is_unicode: - if context.flags & re.DOTALL: - return st.characters() - return st.characters(blacklist_characters="\n") - else: - if context.flags & re.DOTALL: - return binary_char - return binary_char.filter(lambda c: c != b"\n") - - elif code == sre.AT: - # Regexes like '^...', '...$', '\bfoo', '\Bfoo' - # An empty string (or newline) will match the token itself, but - # we don't and can't check the position (eg '%' at the end) - return st.just(empty) - - elif code == sre.SUBPATTERN: - # Various groups: '(...)', '(:...)' or '(?P...)' - old_flags = context.flags - context.flags = (context.flags | value[1]) & ~value[2] - - strat = _strategy(value[-1], context, is_unicode) - - context.flags = old_flags - - if value[0]: - strat = update_group(value[0], strat) - - return strat - - elif code == sre.GROUPREF: - # Regex '\\1' or '(?P=name)' (group reference) - return reuse_group(value) + # Single code + code, value = codes + if code == sre.LITERAL: + # Regex 'a' (single char) + c = to_char(value) + if ( + context.flags & re.IGNORECASE + and c != c.swapcase() + and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None + ): + # We do the explicit check for swapped-case matching because + # eg 'ß'.upper() == 'SS' and ignorecase doesn't match it. + return st.sampled_from([c, c.swapcase()]) + return st.just(c) + + if code == sre.NOT_LITERAL: + # Regex '[^a]' (negation of a single char) + c = to_char(value) + blacklist = {c} + if ( + context.flags & re.IGNORECASE + and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None + ): + # There are a few cases where .swapcase() returns two characters, + # but is still a case-insensitive match. In such cases we add *both* + # characters to our blacklist, to avoid doing the wrong thing for + # patterns such as r"[^\u0130]+" where "i\u0307" matches. + # + # (that's respectively 'Latin letter capital I with dot above' and + # 'latin latter i' + 'combining dot above'; see issue #2657) + # + # As a final additional wrinkle, "latin letter capital I" *also* + # case-insensitive-matches, with or without combining dot character. + # We therefore have to chain .swapcase() calls until a fixpoint. + stack = [c.swapcase()] + while stack: + for char in stack.pop(): + blacklist.add(char) + stack.extend(set(char.swapcase()) - blacklist) - elif code == sre.ASSERT: - # Regex '(?=...)' or '(?<=...)' (positive lookahead/lookbehind) - return recurse(value[1]) + if is_unicode: + return st.characters(blacklist_characters=blacklist) + return binary_char.filter(lambda c: c not in blacklist) - elif code == sre.ASSERT_NOT: - # Regex '(?!...)' or '(?...)' + old_flags = context.flags + context.flags = (context.flags | value[1]) & ~value[2] + + strat = _strategy(value[-1], context, is_unicode) + + context.flags = old_flags + + if value[0]: + strat = update_group(value[0], strat) + + return strat + + if code == sre.GROUPREF: + # Regex '\\1' or '(?P=name)' (group reference) + return reuse_group(value) + + if code == sre.ASSERT: + # Regex '(?=...)' or '(?<=...)' (positive lookahead/lookbehind) + return recurse(value[1]) + + if code == sre.ASSERT_NOT: + # Regex '(?!...)' or '(? Ex: "https://hypothesis.readthedocs.io/en/latest/data.html" "#composite-strategies for more details." ) - else: - raise HypothesisException( - "Using example() inside a test function is a bad " - "idea. Instead consider using hypothesis.strategies.data() " - "to draw more examples during testing. See " - "https://hypothesis.readthedocs.io/en/latest/data.html" - "#drawing-interactively-in-tests for more details." - ) + raise HypothesisException( + "Using example() inside a test function is a bad " + "idea. Instead consider using hypothesis.strategies.data() " + "to draw more examples during testing. See " + "https://hypothesis.readthedocs.io/en/latest/data.html" + "#drawing-interactively-in-tests for more details." + ) try: return self.__examples.pop() @@ -960,14 +959,13 @@ def do_filtered_draw(self, data): if self.condition(value): data.stop_example() return value - else: - data.stop_example(discard=True) - if i == 0: - self.note_retried(data) - # This is to guard against the case where we consume no data. - # As long as we consume data, we'll eventually pass or raise. - # But if we don't this could be an infinite loop. - assume(data.index > start_index) + data.stop_example(discard=True) + if i == 0: + self.note_retried(data) + # This is to guard against the case where we consume no data. + # As long as we consume data, we'll eventually pass or raise. + # But if we don't this could be an infinite loop. + assume(data.index > start_index) return filter_not_satisfied diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/types.py b/hypothesis-python/src/hypothesis/strategies/_internal/types.py index 4e410bcf58..bd49dd5c22 100644 --- a/hypothesis-python/src/hypothesis/strategies/_internal/types.py +++ b/hypothesis-python/src/hypothesis/strategies/_internal/types.py @@ -351,7 +351,7 @@ def from_typing_type(thing): and elem_types[-1] is Ellipsis ): return st.lists(st.from_type(elem_types[0])).map(tuple) - elif len(elem_types) == 1 and elem_types[0] == (): + if len(elem_types) == 1 and elem_types[0] == (): return st.tuples() # Empty tuple; see issue #1583 return st.tuples(*map(st.from_type, elem_types)) if hasattr(typing, "Final") and getattr(thing, "__origin__", None) == typing.Final: @@ -698,7 +698,7 @@ def resolve_Type(thing): # Duplicate check from from_type here - only paying when needed. args = list(args) for i, a in enumerate(args): - if type(a) == typing.ForwardRef: + if isinstance(a, typing.ForwardRef): try: args[i] = getattr(builtins, a.__forward_arg__) except AttributeError: @@ -734,8 +734,7 @@ def _can_hash(val): def _from_hashable_type(type_): if type_ in ALWAYS_HASHABLE_TYPES: return st.from_type(type_) - else: - return st.from_type(type_).filter(_can_hash) + return st.from_type(type_).filter(_can_hash) @register(typing.Set, st.builds(set)) diff --git a/hypothesis-python/src/hypothesis/utils/terminal.py b/hypothesis-python/src/hypothesis/utils/terminal.py index 6a6f410d6a..7e65a76b1e 100644 --- a/hypothesis-python/src/hypothesis/utils/terminal.py +++ b/hypothesis-python/src/hypothesis/utils/terminal.py @@ -30,7 +30,7 @@ def guess_background_color(): # 0=black, 7=light-grey, 15=white ; we don't interpret other colors if fg in ("7", "15") and bg == "0": return "dark" - elif fg == "0" and bg in ("7", "15"): + if fg == "0" and bg in ("7", "15"): return "light" # TODO: Guessing based on the xterm control sequence return "unknown" diff --git a/hypothesis-python/src/hypothesis/vendor/pretty.py b/hypothesis-python/src/hypothesis/vendor/pretty.py index 2f52ecf642..81eaedc483 100644 --- a/hypothesis-python/src/hypothesis/vendor/pretty.py +++ b/hypothesis-python/src/hypothesis/vendor/pretty.py @@ -355,20 +355,18 @@ def pretty(self, obj): if cls in self.type_pprinters: # printer registered in self.type_pprinters return self.type_pprinters[cls](obj, self, cycle) - else: - # deferred printer - printer = self._in_deferred_types(cls) - if printer is not None: - return printer(obj, self, cycle) - else: - # Finally look for special method names. - # Some objects automatically create any requested - # attribute. Try to ignore most of them by checking for - # callability. - if "_repr_pretty_" in cls.__dict__: - meth = cls._repr_pretty_ - if callable(meth): - return meth(obj, self, cycle) + # deferred printer + printer = self._in_deferred_types(cls) + if printer is not None: + return printer(obj, self, cycle) + # Finally look for special method names. + # Some objects automatically create any requested + # attribute. Try to ignore most of them by checking for + # callability. + if "_repr_pretty_" in cls.__dict__: + meth = cls._repr_pretty_ + if callable(meth): + return meth(obj, self, cycle) return _default_pprint(obj, self, cycle) finally: self.end_group() @@ -537,7 +535,7 @@ def inner(obj, p, cycle): p.text(",") p.breakable() p.pretty(x) - if len(obj) == 1 and type(obj) is tuple: + if len(obj) == 1 and isinstance(obj, tuple): # Special case for 1-item tuples. p.text(",") p.end_group(step, end) diff --git a/hypothesis-python/tests/array_api/conftest.py b/hypothesis-python/tests/array_api/conftest.py index 7ee6a1f4eb..ce2fb888fb 100644 --- a/hypothesis-python/tests/array_api/conftest.py +++ b/hypothesis-python/tests/array_api/conftest.py @@ -16,6 +16,8 @@ import pytest +from tests.array_api.common import installed_array_modules + from hypothesis.errors import HypothesisWarning, InvalidArgument from hypothesis.extra.array_api import ( NOMINAL_VERSIONS, @@ -24,8 +26,6 @@ mock_xp, ) -from tests.array_api.common import installed_array_modules - # See README.md in regards to the env variables test_xp_option = getenv("HYPOTHESIS_TEST_ARRAY_API", "default") diff --git a/hypothesis-python/tests/array_api/test_argument_validation.py b/hypothesis-python/tests/array_api/test_argument_validation.py index 3a14ee9987..72f097fe4f 100644 --- a/hypothesis-python/tests/array_api/test_argument_validation.py +++ b/hypothesis-python/tests/array_api/test_argument_validation.py @@ -12,11 +12,11 @@ import pytest +from tests.array_api.common import MIN_VER_FOR_COMPLEX + from hypothesis.errors import InvalidArgument from hypothesis.extra.array_api import NominalVersion, make_strategies_namespace -from tests.array_api.common import MIN_VER_FOR_COMPLEX - def e(name, *, _min_version: Optional[NominalVersion] = None, **kwargs): kw = ", ".join(f"{k}={v!r}" for k, v in kwargs.items()) diff --git a/hypothesis-python/tests/array_api/test_arrays.py b/hypothesis-python/tests/array_api/test_arrays.py index b36520688d..351be191dd 100644 --- a/hypothesis-python/tests/array_api/test_arrays.py +++ b/hypothesis-python/tests/array_api/test_arrays.py @@ -10,11 +10,6 @@ import pytest -from hypothesis import given, strategies as st -from hypothesis.errors import InvalidArgument -from hypothesis.extra.array_api import COMPLEX_NAMES, REAL_NAMES -from hypothesis.internal.floats import width_smallest_normals - from tests.array_api.common import ( MIN_VER_FOR_COMPLEX, dtype_name_params, @@ -23,6 +18,11 @@ from tests.common.debug import assert_all_examples, find_any, minimal from tests.common.utils import flaky +from hypothesis import given, strategies as st +from hypothesis.errors import InvalidArgument +from hypothesis.extra.array_api import COMPLEX_NAMES, REAL_NAMES +from hypothesis.internal.floats import width_smallest_normals + def skip_on_missing_unique_values(xp): if not hasattr(xp, "unique_values"): diff --git a/hypothesis-python/tests/array_api/test_from_dtype.py b/hypothesis-python/tests/array_api/test_from_dtype.py index 18f6d081f1..7862200305 100644 --- a/hypothesis-python/tests/array_api/test_from_dtype.py +++ b/hypothesis-python/tests/array_api/test_from_dtype.py @@ -12,9 +12,6 @@ import pytest -from hypothesis.extra.array_api import find_castable_builtin_for_dtype -from hypothesis.internal.floats import width_smallest_normals - from tests.array_api.common import dtype_name_params, flushes_to_zero from tests.common.debug import ( assert_all_examples, @@ -23,6 +20,8 @@ minimal, ) +from hypothesis.extra.array_api import find_castable_builtin_for_dtype +from hypothesis.internal.floats import width_smallest_normals @pytest.mark.parametrize("dtype_name", dtype_name_params) def test_strategies_have_reusable_values(xp, xps, dtype_name): diff --git a/hypothesis-python/tests/array_api/test_indices.py b/hypothesis-python/tests/array_api/test_indices.py index d89b6b3936..c4662d02d9 100644 --- a/hypothesis-python/tests/array_api/test_indices.py +++ b/hypothesis-python/tests/array_api/test_indices.py @@ -12,11 +12,11 @@ import pytest +from tests.common.debug import assert_all_examples, find_any + from hypothesis import assume, given, note, strategies as st from hypothesis.extra._array_helpers import NDIM_MAX -from tests.common.debug import assert_all_examples, find_any - @pytest.mark.parametrize( "condition", diff --git a/hypothesis-python/tests/array_api/test_pretty.py b/hypothesis-python/tests/array_api/test_pretty.py index bb38f6427f..abe6dc295d 100644 --- a/hypothesis-python/tests/array_api/test_pretty.py +++ b/hypothesis-python/tests/array_api/test_pretty.py @@ -12,11 +12,11 @@ import pytest +from tests.array_api.common import MIN_VER_FOR_COMPLEX + from hypothesis.errors import InvalidArgument from hypothesis.extra.array_api import make_strategies_namespace -from tests.array_api.common import MIN_VER_FOR_COMPLEX - @pytest.mark.parametrize( "name", diff --git a/hypothesis-python/tests/array_api/test_scalar_dtypes.py b/hypothesis-python/tests/array_api/test_scalar_dtypes.py index 09e294bd1d..2d4b258c46 100644 --- a/hypothesis-python/tests/array_api/test_scalar_dtypes.py +++ b/hypothesis-python/tests/array_api/test_scalar_dtypes.py @@ -10,6 +10,9 @@ import pytest +from tests.array_api.common import MIN_VER_FOR_COMPLEX +from tests.common.debug import assert_all_examples, find_any, minimal + from hypothesis.extra.array_api import ( COMPLEX_NAMES, DTYPE_NAMES, @@ -20,9 +23,6 @@ UINT_NAMES, ) -from tests.array_api.common import MIN_VER_FOR_COMPLEX -from tests.common.debug import assert_all_examples, find_any, minimal - @pytest.mark.parametrize( ("strat_name", "dtype_names"), diff --git a/hypothesis-python/tests/common/__init__.py b/hypothesis-python/tests/common/__init__.py index 7edb4f204a..e14b4cc2e2 100644 --- a/hypothesis-python/tests/common/__init__.py +++ b/hypothesis-python/tests/common/__init__.py @@ -11,6 +11,8 @@ import sys from collections import namedtuple +from tests.common.debug import TIME_INCREMENT + from hypothesis.strategies import ( binary, booleans, @@ -35,7 +37,7 @@ tuples, ) -from tests.common.debug import TIME_INCREMENT + __all__ = ["standard_types", "OrderedPair", "TIME_INCREMENT"] diff --git a/hypothesis-python/tests/common/debug.py b/hypothesis-python/tests/common/debug.py index 8c75d2974d..78ca830780 100644 --- a/hypothesis-python/tests/common/debug.py +++ b/hypothesis-python/tests/common/debug.py @@ -8,6 +8,8 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.utils import no_shrink + from hypothesis import ( HealthCheck, Verbosity, @@ -19,7 +21,7 @@ from hypothesis.internal.conjecture.data import ConjectureData, StopTest from hypothesis.internal.reflection import get_pretty_function_description -from tests.common.utils import no_shrink + TIME_INCREMENT = 0.01 diff --git a/hypothesis-python/tests/common/strategies.py b/hypothesis-python/tests/common/strategies.py index e0cc13f16a..6d143d179c 100644 --- a/hypothesis-python/tests/common/strategies.py +++ b/hypothesis-python/tests/common/strategies.py @@ -38,8 +38,7 @@ def do_draw(self, data): self.__last = x self.accepted.add(x) return True - else: - return False + return False diffs = [i for i in range(len(x)) if x[i] != ls[i]] if len(diffs) == 1: i = diffs[0] diff --git a/hypothesis-python/tests/conftest.py b/hypothesis-python/tests/conftest.py index cb015988fb..e0638ea3a0 100644 --- a/hypothesis-python/tests/conftest.py +++ b/hypothesis-python/tests/conftest.py @@ -15,12 +15,12 @@ import pytest -from hypothesis._settings import is_in_ci -from hypothesis.internal.detection import is_hypothesis_test - from tests.common import TIME_INCREMENT from tests.common.setup import run +from hypothesis._settings import is_in_ci +from hypothesis.internal.detection import is_hypothesis_test + run() # Skip collection of tests which require the Django test runner, diff --git a/hypothesis-python/tests/conjecture/test_choice_tree.py b/hypothesis-python/tests/conjecture/test_choice_tree.py index 5d566cb445..95ebc9dd4b 100644 --- a/hypothesis-python/tests/conjecture/test_choice_tree.py +++ b/hypothesis-python/tests/conjecture/test_choice_tree.py @@ -66,7 +66,7 @@ def test_all_filtered_child(): def all_filtered(chooser): chooser.choose(range(10), condition=lambda j: False) - assert all_filtered == [] + assert not all_filtered def test_skips_over_exhausted_children(): diff --git a/hypothesis-python/tests/conjecture/test_dfa.py b/hypothesis-python/tests/conjecture/test_dfa.py index 2ccfb36c1b..a48b9bc93b 100644 --- a/hypothesis-python/tests/conjecture/test_dfa.py +++ b/hypothesis-python/tests/conjecture/test_dfa.py @@ -191,7 +191,7 @@ def test_max_length_of_recursive_dfa(order): def test_transitions_out_of_dead_are_empty(): dfa = ConcreteDFA([{}], {0}) - assert list(dfa.raw_transitions(DEAD)) == [] + assert not list(dfa.raw_transitions(DEAD)) def test_can_transition_from_dead(): diff --git a/hypothesis-python/tests/conjecture/test_engine.py b/hypothesis-python/tests/conjecture/test_engine.py index 5177bb20ba..fd6703f8cf 100644 --- a/hypothesis-python/tests/conjecture/test_engine.py +++ b/hypothesis-python/tests/conjecture/test_engine.py @@ -15,6 +15,18 @@ import pytest +from tests.common.strategies import SLOW, HardToShrink +from tests.common.utils import no_shrink +from tests.conjecture.common import ( + SOME_LABEL, + TEST_SETTINGS, + buffer_size_limit, + run_to_buffer, + run_to_data, + shrinking_from, +) + + from hypothesis import HealthCheck, Phase, Verbosity, settings from hypothesis.database import ExampleDatabase, InMemoryExampleDatabase from hypothesis.errors import FailedHealthCheck, Flaky @@ -32,17 +44,6 @@ from hypothesis.internal.conjecture.utils import integer_range from hypothesis.internal.entropy import deterministic_PRNG -from tests.common.strategies import SLOW, HardToShrink -from tests.common.utils import no_shrink -from tests.conjecture.common import ( - SOME_LABEL, - TEST_SETTINGS, - buffer_size_limit, - run_to_buffer, - run_to_data, - shrinking_from, -) - def test_can_index_results(): @run_to_buffer diff --git a/hypothesis-python/tests/conjecture/test_float_encoding.py b/hypothesis-python/tests/conjecture/test_float_encoding.py index d35c169738..36dffa8e12 100644 --- a/hypothesis-python/tests/conjecture/test_float_encoding.py +++ b/hypothesis-python/tests/conjecture/test_float_encoding.py @@ -184,7 +184,7 @@ def minimal_from(start, condition): ], ) def test_can_shrink_downwards(start, end): - assert minimal_from(start, lambda x: not (x < end)) == end + assert minimal_from(start, lambda x: not x < end) == end @pytest.mark.parametrize( diff --git a/hypothesis-python/tests/conjecture/test_junkdrawer.py b/hypothesis-python/tests/conjecture/test_junkdrawer.py index f0b0f8f5eb..64ce58bb2e 100644 --- a/hypothesis-python/tests/conjecture/test_junkdrawer.py +++ b/hypothesis-python/tests/conjecture/test_junkdrawer.py @@ -132,7 +132,7 @@ def test_int_list_equality(): assert ls != x assert x != ls - assert not (x == ls) + assert not x == ls assert x == x assert x == y diff --git a/hypothesis-python/tests/conjecture/test_optimiser.py b/hypothesis-python/tests/conjecture/test_optimiser.py index 9a0e457c4d..34512aecb6 100644 --- a/hypothesis-python/tests/conjecture/test_optimiser.py +++ b/hypothesis-python/tests/conjecture/test_optimiser.py @@ -10,14 +10,14 @@ import pytest +from tests.conjecture.common import TEST_SETTINGS, buffer_size_limit + from hypothesis import settings from hypothesis.internal.compat import int_to_bytes from hypothesis.internal.conjecture.data import Status from hypothesis.internal.conjecture.engine import ConjectureRunner, RunIsComplete from hypothesis.internal.entropy import deterministic_PRNG -from tests.conjecture.common import TEST_SETTINGS, buffer_size_limit - def test_optimises_to_maximum(): with deterministic_PRNG(): diff --git a/hypothesis-python/tests/conjecture/test_shrinker.py b/hypothesis-python/tests/conjecture/test_shrinker.py index 0ae9885bcb..418177f617 100644 --- a/hypothesis-python/tests/conjecture/test_shrinker.py +++ b/hypothesis-python/tests/conjecture/test_shrinker.py @@ -12,6 +12,8 @@ import pytest +from tests.conjecture.common import SOME_LABEL, run_to_buffer, shrinking_from + from hypothesis.internal.compat import int_to_bytes from hypothesis.internal.conjecture import floats as flt from hypothesis.internal.conjecture.engine import ConjectureRunner @@ -24,8 +26,6 @@ from hypothesis.internal.conjecture.shrinking import Float from hypothesis.internal.conjecture.utils import Sampler -from tests.conjecture.common import SOME_LABEL, run_to_buffer, shrinking_from - @pytest.mark.parametrize("n", [1, 5, 8, 15]) def test_can_shrink_variable_draws_with_just_deletion(n, monkeypatch): diff --git a/hypothesis-python/tests/conjecture/test_shrinking_interface.py b/hypothesis-python/tests/conjecture/test_shrinking_interface.py index 247b72d8e1..f5163c4919 100644 --- a/hypothesis-python/tests/conjecture/test_shrinking_interface.py +++ b/hypothesis-python/tests/conjecture/test_shrinking_interface.py @@ -10,10 +10,10 @@ from random import Random -from hypothesis.internal.conjecture.shrinking import Integer - from tests.common.utils import capture_out +from hypothesis.internal.conjecture.shrinking import Integer + def test_debug_output(): with capture_out() as o: diff --git a/hypothesis-python/tests/conjecture/test_test_data.py b/hypothesis-python/tests/conjecture/test_test_data.py index 346063452c..ed54500e39 100644 --- a/hypothesis-python/tests/conjecture/test_test_data.py +++ b/hypothesis-python/tests/conjecture/test_test_data.py @@ -452,13 +452,13 @@ def test_example_equality(): examples = list(d.examples) for ex1, ex2 in itertools.combinations(examples, 2): assert ex1 != ex2 - assert not (ex1 == ex2) + assert not ex1 == ex2 for ex in examples: assert ex == ex - not (ex != ex) + not ex != ex - assert not (ex == "hello") + assert not ex == "hello" assert ex != "hello" diff --git a/hypothesis-python/tests/cover/test_charmap.py b/hypothesis-python/tests/cover/test_charmap.py index 4c6a64d46a..7a67ab8aca 100644 --- a/hypothesis-python/tests/cover/test_charmap.py +++ b/hypothesis-python/tests/cover/test_charmap.py @@ -116,7 +116,7 @@ def test_uses_cached_charmap(): def test_union_empty(): - assert cm._union_intervals([], []) == () + assert not cm._union_intervals([], []) assert cm._union_intervals([], [[1, 2]]) == ((1, 2),) assert cm._union_intervals([[1, 2]], []) == ((1, 2),) diff --git a/hypothesis-python/tests/cover/test_complex_numbers.py b/hypothesis-python/tests/cover/test_complex_numbers.py index 90dc65cab5..2544a64994 100644 --- a/hypothesis-python/tests/cover/test_complex_numbers.py +++ b/hypothesis-python/tests/cover/test_complex_numbers.py @@ -13,13 +13,12 @@ import pytest +from tests.common.debug import assert_no_examples, find_any, minimal + from hypothesis import given, reject, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.strategies import complex_numbers -from tests.common.debug import assert_no_examples, find_any, minimal - - def test_minimal(): assert minimal(complex_numbers(), lambda x: True) == 0 diff --git a/hypothesis-python/tests/cover/test_composite.py b/hypothesis-python/tests/cover/test_composite.py index 6b19fd3a4c..6910fdfc69 100644 --- a/hypothesis-python/tests/cover/test_composite.py +++ b/hypothesis-python/tests/cover/test_composite.py @@ -10,12 +10,11 @@ import pytest -from hypothesis import assume, given, strategies as st -from hypothesis.errors import HypothesisDeprecationWarning, InvalidArgument - from tests.common.debug import minimal from tests.common.utils import flaky +from hypothesis import assume, given, strategies as st +from hypothesis.errors import HypothesisDeprecationWarning, InvalidArgument @st.composite def badly_draw_lists(draw, m=0): diff --git a/hypothesis-python/tests/cover/test_control.py b/hypothesis-python/tests/cover/test_control.py index 41c1eb1c55..73963946af 100644 --- a/hypothesis-python/tests/cover/test_control.py +++ b/hypothesis-python/tests/cover/test_control.py @@ -10,6 +10,8 @@ import pytest +from tests.common.utils import capture_out + from hypothesis import Verbosity, given, reporting, settings from hypothesis.control import ( BuildContext, @@ -26,9 +28,6 @@ from hypothesis.stateful import RuleBasedStateMachine, rule from hypothesis.strategies import integers -from tests.common.utils import capture_out - - def bc(): return BuildContext(TD.for_buffer(b"")) diff --git a/hypothesis-python/tests/cover/test_database_backend.py b/hypothesis-python/tests/cover/test_database_backend.py index 8e0c4249f5..f7eb29e31d 100644 --- a/hypothesis-python/tests/cover/test_database_backend.py +++ b/hypothesis-python/tests/cover/test_database_backend.py @@ -82,7 +82,7 @@ def test_can_delete_a_key_that_is_not_present(exampledatabase): def test_can_fetch_a_key_that_is_not_present(exampledatabase): - assert list(exampledatabase.fetch(b"foo")) == [] + assert not list(exampledatabase.fetch(b"foo")) def test_saving_a_key_twice_fetches_it_once(exampledatabase): diff --git a/hypothesis-python/tests/cover/test_datetimes.py b/hypothesis-python/tests/cover/test_datetimes.py index 9062501d7d..2807a30ea1 100644 --- a/hypothesis-python/tests/cover/test_datetimes.py +++ b/hypothesis-python/tests/cover/test_datetimes.py @@ -12,11 +12,10 @@ import pytest -from hypothesis import given, settings -from hypothesis.strategies import dates, datetimes, timedeltas, times - from tests.common.debug import find_any, minimal +from hypothesis import given, settings +from hypothesis.strategies import dates, datetimes, timedeltas, times def test_can_find_positive_delta(): assert minimal(timedeltas(), lambda x: x.days > 0) == dt.timedelta(1) diff --git a/hypothesis-python/tests/cover/test_deadline.py b/hypothesis-python/tests/cover/test_deadline.py index d7927d9560..b829d05966 100644 --- a/hypothesis-python/tests/cover/test_deadline.py +++ b/hypothesis-python/tests/cover/test_deadline.py @@ -12,11 +12,10 @@ import pytest -from hypothesis import given, settings, strategies as st -from hypothesis.errors import DeadlineExceeded, Flaky, InvalidArgument - from tests.common.utils import assert_falsifying_output, fails_with +from hypothesis import given, settings, strategies as st +from hypothesis.errors import DeadlineExceeded, Flaky, InvalidArgument def test_raises_deadline_on_slow_test(): @settings(deadline=500) @@ -85,8 +84,7 @@ def slow(i): if not failed_once[0]: if i * 0.9 <= 100: return - else: - failed_once[0] = True + failed_once[0] = True t = i / 1000 if i in seen: diff --git a/hypothesis-python/tests/cover/test_debug_information.py b/hypothesis-python/tests/cover/test_debug_information.py index 7d96a3c5f8..9c21c9aa12 100644 --- a/hypothesis-python/tests/cover/test_debug_information.py +++ b/hypothesis-python/tests/cover/test_debug_information.py @@ -12,9 +12,11 @@ import pytest +from tests.common.utils import capture_out + from hypothesis import Verbosity, given, settings, strategies as st -from tests.common.utils import capture_out + def test_reports_passes(): diff --git a/hypothesis-python/tests/cover/test_deferred_strategies.py b/hypothesis-python/tests/cover/test_deferred_strategies.py index 1621604fea..f9b190c3c4 100644 --- a/hypothesis-python/tests/cover/test_deferred_strategies.py +++ b/hypothesis-python/tests/cover/test_deferred_strategies.py @@ -10,11 +10,11 @@ import pytest +from tests.common.debug import assert_no_examples, minimal + from hypothesis import given, strategies as st from hypothesis.errors import InvalidArgument -from tests.common.debug import assert_no_examples, minimal - def test_binary_tree(): tree = st.deferred(lambda: st.integers() | st.tuples(tree, tree)) @@ -123,8 +123,7 @@ def test_very_deep_deferral(): def strat(i): if i == 0: return st.deferred(lambda: st.one_of(strategies + [st.none()])) - else: - return st.deferred(lambda: st.tuples(strategies[(i + 1) % len(strategies)])) + return st.deferred(lambda: st.tuples(strategies[(i + 1) % len(strategies)])) strategies = list(map(strat, range(100))) diff --git a/hypothesis-python/tests/cover/test_direct_strategies.py b/hypothesis-python/tests/cover/test_direct_strategies.py index 9845626b90..9c6d5799aa 100644 --- a/hypothesis-python/tests/cover/test_direct_strategies.py +++ b/hypothesis-python/tests/cover/test_direct_strategies.py @@ -18,12 +18,12 @@ import pytest +from tests.common.debug import minimal + from hypothesis import given, settings, strategies as ds from hypothesis.errors import InvalidArgument from hypothesis.vendor.pretty import pretty -from tests.common.debug import minimal - # Use `pretty` instead of `repr` for building test names, so that set and dict # parameters print consistently across multiple worker processes with different # PYTHONHASHSEED values. @@ -421,7 +421,7 @@ def test_iterables_are_exhaustible(it): def test_minimal_iterable(): - assert list(minimal(ds.iterables(ds.integers()), lambda x: True)) == [] + assert not list(minimal(ds.iterables(ds.integers()), lambda x: True)) @pytest.mark.parametrize("parameter_name", ["min_value", "max_value"]) diff --git a/hypothesis-python/tests/cover/test_draw_example.py b/hypothesis-python/tests/cover/test_draw_example.py index 8fd5c16672..659fe41393 100644 --- a/hypothesis-python/tests/cover/test_draw_example.py +++ b/hypothesis-python/tests/cover/test_draw_example.py @@ -10,10 +10,8 @@ import pytest -from hypothesis.strategies import lists - from tests.common import standard_types - +from hypothesis.strategies import lists @pytest.mark.parametrize("spec", standard_types, ids=list(map(repr, standard_types))) def test_single_example(spec): diff --git a/hypothesis-python/tests/cover/test_example.py b/hypothesis-python/tests/cover/test_example.py index dc272ad9c0..f402924cbc 100644 --- a/hypothesis-python/tests/cover/test_example.py +++ b/hypothesis-python/tests/cover/test_example.py @@ -15,6 +15,8 @@ import pexpect import pytest +from tests.common.utils import fails_with + from hypothesis import example, find, given, strategies as st from hypothesis.errors import ( HypothesisException, @@ -23,8 +25,6 @@ ) from hypothesis.internal.compat import WINDOWS -from tests.common.utils import fails_with - def test_example_of_none_is_none(): assert st.none().example() is None diff --git a/hypothesis-python/tests/cover/test_explicit_examples.py b/hypothesis-python/tests/cover/test_explicit_examples.py index d47e9ae41e..703b2cd12f 100644 --- a/hypothesis-python/tests/cover/test_explicit_examples.py +++ b/hypothesis-python/tests/cover/test_explicit_examples.py @@ -13,6 +13,8 @@ import pytest +from tests.common.utils import assert_falsifying_output, capture_out + from hypothesis import ( Phase, Verbosity, @@ -27,8 +29,6 @@ from hypothesis.internal.compat import ExceptionGroup from hypothesis.strategies import floats, integers, text -from tests.common.utils import assert_falsifying_output, capture_out - class TestInstanceMethods(TestCase): @given(integers()) diff --git a/hypothesis-python/tests/cover/test_feature_flags.py b/hypothesis-python/tests/cover/test_feature_flags.py index cb71ccea95..adbe22fae6 100644 --- a/hypothesis-python/tests/cover/test_feature_flags.py +++ b/hypothesis-python/tests/cover/test_feature_flags.py @@ -8,11 +8,11 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.debug import find_any, minimal + from hypothesis import given, strategies as st from hypothesis.strategies._internal.featureflags import FeatureFlags, FeatureStrategy -from tests.common.debug import find_any, minimal - STRAT = FeatureStrategy() diff --git a/hypothesis-python/tests/cover/test_filter_rewriting.py b/hypothesis-python/tests/cover/test_filter_rewriting.py index b505f11a8e..a1bfc839d3 100644 --- a/hypothesis-python/tests/cover/test_filter_rewriting.py +++ b/hypothesis-python/tests/cover/test_filter_rewriting.py @@ -17,6 +17,8 @@ import pytest +from tests.common.utils import fails_with + from hypothesis import given, strategies as st from hypothesis.errors import HypothesisWarning, Unsatisfiable from hypothesis.internal.floats import next_down, next_up @@ -25,8 +27,6 @@ from hypothesis.strategies._internal.numbers import FloatStrategy, IntegersStrategy from hypothesis.strategies._internal.strategies import FilteredStrategy -from tests.common.utils import fails_with - @pytest.mark.parametrize( "strategy, predicate, start, end", diff --git a/hypothesis-python/tests/cover/test_find.py b/hypothesis-python/tests/cover/test_find.py index 3aa7226e7a..d5b45f3124 100644 --- a/hypothesis-python/tests/cover/test_find.py +++ b/hypothesis-python/tests/cover/test_find.py @@ -23,9 +23,8 @@ def test(v): if len(v) > 5: if seen: return v == seen[0] - else: - seen.append(v) - return True + seen.append(v) + return True result = find( st.text(), diff --git a/hypothesis-python/tests/cover/test_flakiness.py b/hypothesis-python/tests/cover/test_flakiness.py index 62251d11d8..6140e35c51 100644 --- a/hypothesis-python/tests/cover/test_flakiness.py +++ b/hypothesis-python/tests/cover/test_flakiness.py @@ -10,14 +10,13 @@ import pytest +from tests.common.utils import no_shrink + from hypothesis import HealthCheck, Verbosity, assume, example, given, reject, settings from hypothesis.errors import Flaky, Unsatisfiable, UnsatisfiedAssumption from hypothesis.internal.conjecture.engine import MIN_TEST_CALLS from hypothesis.strategies import booleans, composite, integers, lists, random_module -from tests.common.utils import no_shrink - - class Nope(Exception): pass @@ -111,10 +110,9 @@ def test(x): return if i == 1: return - elif i == 2: + if i == 2: reject() - else: - raise Nope() + raise Nope() try: test() diff --git a/hypothesis-python/tests/cover/test_float_nastiness.py b/hypothesis-python/tests/cover/test_float_nastiness.py index d0a7977d72..a13e8db273 100644 --- a/hypothesis-python/tests/cover/test_float_nastiness.py +++ b/hypothesis-python/tests/cover/test_float_nastiness.py @@ -14,6 +14,8 @@ import pytest +from tests.common.debug import find_any, minimal + from hypothesis import assume, given, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.internal.floats import ( @@ -25,8 +27,6 @@ next_up, ) -from tests.common.debug import find_any, minimal - try: import numpy except ImportError: diff --git a/hypothesis-python/tests/cover/test_given_error_conditions.py b/hypothesis-python/tests/cover/test_given_error_conditions.py index e417a6fc1a..bc9d581f2d 100644 --- a/hypothesis-python/tests/cover/test_given_error_conditions.py +++ b/hypothesis-python/tests/cover/test_given_error_conditions.py @@ -10,12 +10,12 @@ import pytest +from tests.common.utils import fails_with + from hypothesis import assume, given, reject, settings from hypothesis.errors import InvalidArgument, Unsatisfiable from hypothesis.strategies import booleans, integers, nothing -from tests.common.utils import fails_with - def test_raises_unsatisfiable_if_all_false_in_finite_set(): @given(booleans()) diff --git a/hypothesis-python/tests/cover/test_health_checks.py b/hypothesis-python/tests/cover/test_health_checks.py index 406c56b238..e37ac3cabf 100644 --- a/hypothesis-python/tests/cover/test_health_checks.py +++ b/hypothesis-python/tests/cover/test_health_checks.py @@ -13,6 +13,8 @@ import pytest from pytest import raises +from tests.common.utils import no_shrink + from hypothesis import HealthCheck, Phase, given, settings, strategies as st from hypothesis.control import assume from hypothesis.errors import FailedHealthCheck, InvalidArgument @@ -29,8 +31,6 @@ from hypothesis.strategies._internal.lazy import LazyStrategy from hypothesis.strategies._internal.strategies import SearchStrategy -from tests.common.utils import no_shrink - HEALTH_CHECK_SETTINGS = settings(max_examples=11, database=None) diff --git a/hypothesis-python/tests/cover/test_lookup.py b/hypothesis-python/tests/cover/test_lookup.py index 07922ab94b..a98a1a5779 100644 --- a/hypothesis-python/tests/cover/test_lookup.py +++ b/hypothesis-python/tests/cover/test_lookup.py @@ -31,9 +31,6 @@ from hypothesis.strategies import from_type from hypothesis.strategies._internal import types -from tests.common.debug import assert_all_examples, find_any, minimal -from tests.common.utils import fails_with, temp_registered - sentinel = object() BUILTIN_TYPES = tuple( v @@ -308,7 +305,7 @@ def test_typevar_type_is_consistent(data, var, expected): v1 = data.draw(strat) v2 = data.draw(strat) assume(v1 != v2) # Values may vary, just not types - assert type(v1) == type(v2) + assert isinstance(v1, type(v2)) assert isinstance(v1, expected) @@ -317,7 +314,7 @@ def test_distinct_typevars_same_constraint(): B = typing.TypeVar("B", int, str) find_any( st.tuples(st.from_type(A), st.from_type(B)), - lambda ab: type(ab[0]) != type(ab[1]), # noqa + lambda ab: not isinstance(ab[0], type(ab[1])), ) @@ -327,7 +324,7 @@ def test_distinct_typevars_distinct_type(): B = typing.TypeVar("B") find_any( st.tuples(st.from_type(A), st.from_type(B)), - lambda ab: type(ab[0]) != type(ab[1]), # noqa + lambda ab: not isinstance(ab[0], type(ab[1])), ) @@ -335,7 +332,7 @@ def test_distinct_typevars_distinct_type(): def same_type_args(a: A, b: A): - assert type(a) == type(b) + assert isinstance(a, type(b)) @given(st.builds(same_type_args)) diff --git a/hypothesis-python/tests/cover/test_lookup_py310.py b/hypothesis-python/tests/cover/test_lookup_py310.py index c24d1268ef..76c14a236d 100644 --- a/hypothesis-python/tests/cover/test_lookup_py310.py +++ b/hypothesis-python/tests/cover/test_lookup_py310.py @@ -8,10 +8,9 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import strategies as st - from tests.common.debug import find_any +from hypothesis import strategies as st def test_native_unions(): s = st.from_type(int | list[str]) diff --git a/hypothesis-python/tests/cover/test_lookup_py38.py b/hypothesis-python/tests/cover/test_lookup_py38.py index 5b65389998..dfe06f89cf 100644 --- a/hypothesis-python/tests/cover/test_lookup_py38.py +++ b/hypothesis-python/tests/cover/test_lookup_py38.py @@ -16,6 +16,9 @@ import pytest +from tests.common.debug import find_any +from tests.common.utils import fails_with, temp_registered + from hypothesis import example, given, strategies as st from hypothesis.errors import InvalidArgument, Unsatisfiable from hypothesis.internal.reflection import ( @@ -24,8 +27,6 @@ ) from hypothesis.strategies import from_type -from tests.common.debug import find_any -from tests.common.utils import fails_with, temp_registered @given(st.data()) @@ -60,7 +61,7 @@ class A(typing.TypedDict): @given(from_type(A)) def test_simple_typeddict(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value) == {"a"} assert isinstance(value["a"], int) @@ -72,7 +73,7 @@ class B(A, total=False): @given(from_type(B)) def test_typeddict_with_optional(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value).issubset({"a", "b"}) assert isinstance(value["a"], int) if "b" in value: @@ -101,7 +102,7 @@ class C(B): @given(from_type(C)) def test_typeddict_with_optional_then_required_again(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value).issubset({"a", "b", "c"}) assert isinstance(value["a"], int) if "b" in value: @@ -115,7 +116,7 @@ class NestedDict(typing.TypedDict): @given(from_type(NestedDict)) def test_typeddict_with_nested_value(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value) == {"inner"} assert isinstance(value["inner"]["a"], int) diff --git a/hypothesis-python/tests/cover/test_lookup_py39.py b/hypothesis-python/tests/cover/test_lookup_py39.py index 7d7a5ac447..db5808fdc1 100644 --- a/hypothesis-python/tests/cover/test_lookup_py39.py +++ b/hypothesis-python/tests/cover/test_lookup_py39.py @@ -14,10 +14,12 @@ import pytest +from tests.common.debug import find_any + from hypothesis import given, strategies as st from hypothesis.errors import InvalidArgument -from tests.common.debug import find_any + @pytest.mark.parametrize( diff --git a/hypothesis-python/tests/cover/test_map.py b/hypothesis-python/tests/cover/test_map.py index 11eed6dc1f..122df325a3 100644 --- a/hypothesis-python/tests/cover/test_map.py +++ b/hypothesis-python/tests/cover/test_map.py @@ -8,11 +8,10 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import assume, given, strategies as st -from hypothesis.strategies._internal.lazy import unwrap_strategies - from tests.common.debug import assert_no_examples +from hypothesis import assume, given, strategies as st +from hypothesis.strategies._internal.lazy import unwrap_strategies @given(st.integers().map(lambda x: assume(x % 3 != 0) and x)) def test_can_assume_in_map(x): diff --git a/hypothesis-python/tests/cover/test_nothing.py b/hypothesis-python/tests/cover/test_nothing.py index 1d61387173..bc5a52d07f 100644 --- a/hypothesis-python/tests/cover/test_nothing.py +++ b/hypothesis-python/tests/cover/test_nothing.py @@ -10,11 +10,11 @@ import pytest +from tests.common.debug import assert_no_examples, minimal + from hypothesis import given, strategies as st from hypothesis.errors import InvalidArgument -from tests.common.debug import assert_no_examples, minimal - def test_resampling(): x = minimal( diff --git a/hypothesis-python/tests/cover/test_numerics.py b/hypothesis-python/tests/cover/test_numerics.py index de63164608..7ee12633e4 100644 --- a/hypothesis-python/tests/cover/test_numerics.py +++ b/hypothesis-python/tests/cover/test_numerics.py @@ -13,6 +13,8 @@ import pytest +from tests.common.debug import find_any + from hypothesis import HealthCheck, assume, given, reject, settings from hypothesis.errors import InvalidArgument from hypothesis.internal.floats import next_down, next_up @@ -28,9 +30,6 @@ tuples, ) -from tests.common.debug import find_any - - @settings(suppress_health_check=HealthCheck.all()) @given(data()) def test_fuzz_floats_bounds(data): diff --git a/hypothesis-python/tests/cover/test_one_of.py b/hypothesis-python/tests/cover/test_one_of.py index 72bc7b55d3..c930e5ec31 100644 --- a/hypothesis-python/tests/cover/test_one_of.py +++ b/hypothesis-python/tests/cover/test_one_of.py @@ -12,11 +12,10 @@ import pytest -from hypothesis import given, strategies as st -from hypothesis.errors import InvalidArgument - from tests.common.debug import assert_no_examples +from hypothesis import given, strategies as st +from hypothesis.errors import InvalidArgument def test_one_of_empty(): e = st.one_of() diff --git a/hypothesis-python/tests/cover/test_permutations.py b/hypothesis-python/tests/cover/test_permutations.py index c6712bb56f..b54084b413 100644 --- a/hypothesis-python/tests/cover/test_permutations.py +++ b/hypothesis-python/tests/cover/test_permutations.py @@ -8,13 +8,12 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import given -from hypothesis.errors import InvalidArgument -from hypothesis.strategies import permutations - from tests.common.debug import minimal from tests.common.utils import fails_with +from hypothesis import given +from hypothesis.errors import InvalidArgument +from hypothesis.strategies import permutations def test_can_find_non_trivial_permutation(): x = minimal(permutations(list(range(5))), lambda x: x[0] != 0) diff --git a/hypothesis-python/tests/cover/test_pretty.py b/hypothesis-python/tests/cover/test_pretty.py index 86359362fd..60c0a79986 100644 --- a/hypothesis-python/tests/cover/test_pretty.py +++ b/hypothesis-python/tests/cover/test_pretty.py @@ -543,12 +543,11 @@ class BigList(list): def _repr_pretty_(self, printer, cycle): if cycle: return "[...]" - else: - with printer.group(open="[", close="]"): - with printer.indent(5): - for v in self: - printer.pretty(v) - printer.breakable(",") + with printer.group(open="[", close="]"): + with printer.indent(5): + for v in self: + printer.pretty(v) + printer.breakable(",") def test_print_with_indent(): diff --git a/hypothesis-python/tests/cover/test_provisional_strategies.py b/hypothesis-python/tests/cover/test_provisional_strategies.py index 621db25631..85d7342c8e 100644 --- a/hypothesis-python/tests/cover/test_provisional_strategies.py +++ b/hypothesis-python/tests/cover/test_provisional_strategies.py @@ -13,6 +13,8 @@ import pytest +from tests.common.debug import find_any + from hypothesis import given, settings from hypothesis.errors import InvalidArgument from hypothesis.provisional import ( @@ -22,8 +24,6 @@ urls, ) -from tests.common.debug import find_any - @given(urls()) def test_is_URL(url): diff --git a/hypothesis-python/tests/cover/test_randoms.py b/hypothesis-python/tests/cover/test_randoms.py index 4b4db455e3..4dcd772047 100644 --- a/hypothesis-python/tests/cover/test_randoms.py +++ b/hypothesis-python/tests/cover/test_randoms.py @@ -15,6 +15,8 @@ import pytest +from tests.common.debug import find_any + from hypothesis import assume, given, strategies as st from hypothesis.internal.compat import ExceptionGroup from hypothesis.strategies._internal.random import ( @@ -25,9 +27,6 @@ normalize_zero, ) -from tests.common.debug import find_any - - def test_implements_all_random_methods(): for name in dir(HypothesisRandom): if not name.startswith("_") or name == "_randbelow": diff --git a/hypothesis-python/tests/cover/test_recursive.py b/hypothesis-python/tests/cover/test_recursive.py index b85bd324db..8e0b9ddf5c 100644 --- a/hypothesis-python/tests/cover/test_recursive.py +++ b/hypothesis-python/tests/cover/test_recursive.py @@ -10,19 +10,17 @@ import pytest -from hypothesis import given, strategies as st -from hypothesis.errors import InvalidArgument - from tests.common.debug import find_any, minimal +from hypothesis import given, strategies as st +from hypothesis.errors import InvalidArgument @given(st.recursive(st.booleans(), st.lists, max_leaves=10)) def test_respects_leaf_limit(xs): def flatten(x): if isinstance(x, list): return sum(map(flatten, x), []) - else: - return [x] + return [x] assert len(flatten(xs)) <= 10 diff --git a/hypothesis-python/tests/cover/test_regex.py b/hypothesis-python/tests/cover/test_regex.py index 4ce0d1144a..ff1ed49d20 100644 --- a/hypothesis-python/tests/cover/test_regex.py +++ b/hypothesis-python/tests/cover/test_regex.py @@ -14,6 +14,8 @@ import pytest +from tests.common.debug import assert_all_examples, assert_no_examples, find_any + from hypothesis import HealthCheck, assume, given, settings, strategies as st from hypothesis._settings import local_settings from hypothesis.errors import InvalidArgument @@ -28,8 +30,6 @@ regex_strategy, ) -from tests.common.debug import assert_all_examples, assert_no_examples, find_any - def is_ascii(s): return all(ord(c) < 128 for c in s) @@ -339,7 +339,7 @@ def test_can_handle_binary_regex_which_is_not_ascii(): def test_regex_have_same_type_as_pattern(pattern): @given(st.from_regex(pattern)) def test_result_type(s): - assert type(s) == type(pattern) + assert isinstance(s,type(pattern)) test_result_type() diff --git a/hypothesis-python/tests/cover/test_reporting.py b/hypothesis-python/tests/cover/test_reporting.py index 7faaf0c2f4..c233741b29 100644 --- a/hypothesis-python/tests/cover/test_reporting.py +++ b/hypothesis-python/tests/cover/test_reporting.py @@ -13,13 +13,13 @@ import pytest +from tests.common.utils import capture_out + from hypothesis import given, reporting from hypothesis._settings import Verbosity, settings from hypothesis.reporting import debug_report, report, verbose_report from hypothesis.strategies import integers -from tests.common.utils import capture_out - def test_can_print_bytes(): with capture_out() as o: diff --git a/hypothesis-python/tests/cover/test_reproduce_failure.py b/hypothesis-python/tests/cover/test_reproduce_failure.py index cb954ace4c..e21ec20a5b 100644 --- a/hypothesis-python/tests/cover/test_reproduce_failure.py +++ b/hypothesis-python/tests/cover/test_reproduce_failure.py @@ -14,6 +14,8 @@ import pytest +from tests.common.utils import capture_out, no_shrink + from hypothesis import ( Verbosity, __version__, @@ -27,8 +29,6 @@ from hypothesis.core import decode_failure, encode_failure from hypothesis.errors import DidNotReproduce, InvalidArgument, UnsatisfiedAssumption -from tests.common.utils import capture_out, no_shrink - @example(bytes(20)) # shorter compressed @example(bytes(3)) # shorter uncompressed diff --git a/hypothesis-python/tests/cover/test_sampled_from.py b/hypothesis-python/tests/cover/test_sampled_from.py index 0d8ba38751..a486ec3a1d 100644 --- a/hypothesis-python/tests/cover/test_sampled_from.py +++ b/hypothesis-python/tests/cover/test_sampled_from.py @@ -13,6 +13,9 @@ import pytest + +from tests.common.utils import fails_with + from hypothesis import given, strategies as st from hypothesis.errors import ( FailedHealthCheck, @@ -28,8 +31,6 @@ filter_not_satisfied, ) -from tests.common.utils import fails_with - an_enum = enum.Enum("A", "a b c") an_ordereddict = collections.OrderedDict([("a", 1), ("b", 2), ("c", 3)]) @@ -50,7 +51,7 @@ def test_can_sample_ordereddict_without_warning(): @given(sampled_from(an_enum)) def test_can_sample_enums(member): - assert isinstance(member, an_enum) + assert isinstance(member, type(an_enum)) @fails_with(FailedHealthCheck) diff --git a/hypothesis-python/tests/cover/test_searchstrategy.py b/hypothesis-python/tests/cover/test_searchstrategy.py index ef93f0c47a..bfacf4758d 100644 --- a/hypothesis-python/tests/cover/test_searchstrategy.py +++ b/hypothesis-python/tests/cover/test_searchstrategy.py @@ -13,12 +13,12 @@ import pytest +from tests.common.debug import assert_no_examples + from hypothesis.errors import InvalidArgument from hypothesis.internal.conjecture.data import ConjectureData from hypothesis.strategies import booleans, integers, just, none, tuples -from tests.common.debug import assert_no_examples - def test_or_errors_when_given_non_strategy(): bools = tuples(booleans()) diff --git a/hypothesis-python/tests/cover/test_seed_printing.py b/hypothesis-python/tests/cover/test_seed_printing.py index 8b65d79b7e..69ac49eb32 100644 --- a/hypothesis-python/tests/cover/test_seed_printing.py +++ b/hypothesis-python/tests/cover/test_seed_printing.py @@ -12,12 +12,12 @@ import pytest +from tests.common.utils import all_values, capture_out + from hypothesis import Verbosity, assume, core, given, settings, strategies as st from hypothesis.database import InMemoryExampleDatabase from hypothesis.errors import FailedHealthCheck -from tests.common.utils import all_values, capture_out - @pytest.mark.parametrize("in_pytest", [False, True]) @pytest.mark.parametrize("fail_healthcheck", [False, True]) diff --git a/hypothesis-python/tests/cover/test_settings.py b/hypothesis-python/tests/cover/test_settings.py index e3ca7376ce..4a8719c0bd 100644 --- a/hypothesis-python/tests/cover/test_settings.py +++ b/hypothesis-python/tests/cover/test_settings.py @@ -15,6 +15,8 @@ import pytest +from tests.common.utils import counts_calls, fails_with + from hypothesis import example, given, strategies as st from hypothesis._settings import ( Phase, @@ -33,9 +35,6 @@ from hypothesis.stateful import RuleBasedStateMachine, rule from hypothesis.utils.conventions import not_set -from tests.common.utils import counts_calls, fails_with - - def test_has_docstrings(): assert settings.verbosity.__doc__ diff --git a/hypothesis-python/tests/cover/test_simple_characters.py b/hypothesis-python/tests/cover/test_simple_characters.py index d90a8b1d60..bf8053f84a 100644 --- a/hypothesis-python/tests/cover/test_simple_characters.py +++ b/hypothesis-python/tests/cover/test_simple_characters.py @@ -12,12 +12,12 @@ import pytest -from hypothesis.errors import InvalidArgument -from hypothesis.strategies import characters - from tests.common.debug import assert_no_examples, find_any, minimal from tests.common.utils import fails_with +from hypothesis.errors import InvalidArgument +from hypothesis.strategies import characters + @fails_with(InvalidArgument) def test_nonexistent_category_argument(): diff --git a/hypothesis-python/tests/cover/test_simple_collections.py b/hypothesis-python/tests/cover/test_simple_collections.py index 576f9f9ba2..25e51a7e73 100644 --- a/hypothesis-python/tests/cover/test_simple_collections.py +++ b/hypothesis-python/tests/cover/test_simple_collections.py @@ -13,6 +13,9 @@ import pytest +from tests.common.debug import find_any, minimal +from tests.common.utils import flaky + from hypothesis import given, settings from hypothesis.strategies import ( booleans, @@ -28,8 +31,7 @@ tuples, ) -from tests.common.debug import find_any, minimal -from tests.common.utils import flaky + @pytest.mark.parametrize( diff --git a/hypothesis-python/tests/cover/test_simple_strings.py b/hypothesis-python/tests/cover/test_simple_strings.py index 805484a919..69ad828872 100644 --- a/hypothesis-python/tests/cover/test_simple_strings.py +++ b/hypothesis-python/tests/cover/test_simple_strings.py @@ -8,11 +8,11 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.debug import minimal + from hypothesis import given from hypothesis.strategies import binary, characters, text, tuples -from tests.common.debug import minimal - def test_can_minimize_up_to_zero(): s = minimal(text(), lambda x: any(lambda t: t <= "0" for t in x)) diff --git a/hypothesis-python/tests/cover/test_slices.py b/hypothesis-python/tests/cover/test_slices.py index a3bf3da018..62f69b51b2 100644 --- a/hypothesis-python/tests/cover/test_slices.py +++ b/hypothesis-python/tests/cover/test_slices.py @@ -10,10 +10,10 @@ import pytest -from hypothesis import given, settings, strategies as st - from tests.common.debug import assert_all_examples, find_any, minimal +from hypothesis import given, settings, strategies as st + use_several_sizes = pytest.mark.parametrize("size", [1, 2, 5, 10, 100, 1000]) diff --git a/hypothesis-python/tests/cover/test_slippage.py b/hypothesis-python/tests/cover/test_slippage.py index 4561000fcf..511e901887 100644 --- a/hypothesis-python/tests/cover/test_slippage.py +++ b/hypothesis-python/tests/cover/test_slippage.py @@ -10,12 +10,6 @@ import pytest -from hypothesis import Phase, assume, given, settings, strategies as st, target -from hypothesis.database import InMemoryExampleDatabase -from hypothesis.errors import Flaky -from hypothesis.internal.compat import ExceptionGroup -from hypothesis.internal.conjecture.engine import MIN_TEST_CALLS - from tests.common.utils import ( assert_output_contains_failure, capture_out, @@ -23,6 +17,12 @@ ) +from hypothesis import Phase, assume, given, settings, strategies as st, target +from hypothesis.database import InMemoryExampleDatabase +from hypothesis.errors import Flaky +from hypothesis.internal.compat import ExceptionGroup +from hypothesis.internal.conjecture.engine import MIN_TEST_CALLS + def capture_reports(test): with capture_out() as o, pytest.raises(ExceptionGroup) as err: test() @@ -77,8 +77,7 @@ def test(i): target[0] = i if target[0] == i: raise ValueError("loc 1") - else: - raise ValueError("loc 2") + raise ValueError("loc 2") output = capture_reports(test) assert "loc 1" in output @@ -252,7 +251,7 @@ def test(i): if i == 1: seen.add(TypeError) raise TypeError - elif i >= 2: + if i >= 2: seen.add(ValueError) raise ValueError diff --git a/hypothesis-python/tests/cover/test_stateful.py b/hypothesis-python/tests/cover/test_stateful.py index ce6f60b55c..705ee4e829 100644 --- a/hypothesis-python/tests/cover/test_stateful.py +++ b/hypothesis-python/tests/cover/test_stateful.py @@ -16,6 +16,9 @@ from _pytest.outcomes import Failed, Skipped from pytest import raises +from tests.common.utils import capture_out, validate_deprecation +from tests.nocover.test_stateful import DepthMachine + from hypothesis import __version__, reproduce_failure, seed, settings as Settings from hypothesis.control import current_build_context from hypothesis.database import ExampleDatabase @@ -35,9 +38,6 @@ ) from hypothesis.strategies import binary, data, integers, just, lists -from tests.common.utils import capture_out, validate_deprecation -from tests.nocover.test_stateful import DepthMachine - NO_BLOB_SETTINGS = Settings(print_blob=False) diff --git a/hypothesis-python/tests/cover/test_subnormal_floats.py b/hypothesis-python/tests/cover/test_subnormal_floats.py index 4877ce8ed5..792ee9fa35 100644 --- a/hypothesis-python/tests/cover/test_subnormal_floats.py +++ b/hypothesis-python/tests/cover/test_subnormal_floats.py @@ -12,14 +12,14 @@ import pytest +from tests.common.debug import assert_no_examples, find_any +from tests.common.utils import PYTHON_FTZ + from hypothesis.errors import InvalidArgument from hypothesis.internal.floats import next_down, next_up from hypothesis.strategies import floats from hypothesis.strategies._internal.numbers import next_down_normal, next_up_normal -from tests.common.debug import assert_no_examples, find_any -from tests.common.utils import PYTHON_FTZ - pytestmark = [pytest.mark.skipif(PYTHON_FTZ, reason="broken by unsafe compiler flags")] diff --git a/hypothesis-python/tests/cover/test_testdecorators.py b/hypothesis-python/tests/cover/test_testdecorators.py index 2bd583e658..7fd631a3f1 100644 --- a/hypothesis-python/tests/cover/test_testdecorators.py +++ b/hypothesis-python/tests/cover/test_testdecorators.py @@ -12,6 +12,16 @@ import threading from collections import namedtuple +from tests.common.utils import ( + assert_falsifying_output, + capture_out, + fails, + fails_with, + no_shrink, + raises, +) + + from hypothesis import HealthCheck, Verbosity, assume, given, note, reporting, settings from hypothesis.strategies import ( binary, @@ -29,15 +39,6 @@ text, ) -from tests.common.utils import ( - assert_falsifying_output, - capture_out, - fails, - fails_with, - no_shrink, - raises, -) - # This particular test file is run under both pytest and nose, so it can't # rely on pytest-specific helpers like `pytest.raises` unless we define a # fallback in tests.common.utils. @@ -139,7 +140,7 @@ def test_can_be_given_keyword_args(x, name): @fails @given(one_of(floats(), booleans()), one_of(floats(), booleans())) def test_one_of_produces_different_values(x, y): - assert type(x) == type(y) + assert isinstance(x, type(y)) @given(just(42)) @@ -202,7 +203,7 @@ def test_can_test_sets_sampled_from(xs): @fails @given(mix, mix) def test_can_mix_sampling_with_generating(x, y): - assert type(x) == type(y) + assert isinstance(x,type(y)) @fails diff --git a/hypothesis-python/tests/cover/test_type_lookup.py b/hypothesis-python/tests/cover/test_type_lookup.py index 14460d9df6..e6d6b97261 100644 --- a/hypothesis-python/tests/cover/test_type_lookup.py +++ b/hypothesis-python/tests/cover/test_type_lookup.py @@ -15,6 +15,9 @@ import pytest +from tests.common.debug import assert_all_examples, find_any +from tests.common.utils import fails_with, temp_registered + from hypothesis import given, infer, settings, strategies as st from hypothesis.errors import ( HypothesisDeprecationWarning, @@ -28,9 +31,6 @@ from hypothesis.strategies._internal.types import _global_type_lookup from hypothesis.strategies._internal.utils import _strategies -from tests.common.debug import assert_all_examples, find_any -from tests.common.utils import fails_with, temp_registered - # Build a set of all types output by core strategies blocklist = { "builds", diff --git a/hypothesis-python/tests/cover/test_type_lookup_forward_ref.py b/hypothesis-python/tests/cover/test_type_lookup_forward_ref.py index 488023b6c7..92935d2572 100644 --- a/hypothesis-python/tests/cover/test_type_lookup_forward_ref.py +++ b/hypothesis-python/tests/cover/test_type_lookup_forward_ref.py @@ -26,11 +26,11 @@ import pytest +from tests.common import utils + from hypothesis import given, strategies as st from hypothesis.errors import ResolutionFailed -from tests.common import utils - if TYPE_CHECKING: from tests.common.utils import ExcInfo # we just need any type # noqa: F401 diff --git a/hypothesis-python/tests/cover/test_unittest.py b/hypothesis-python/tests/cover/test_unittest.py index af638045a0..14f95ada22 100644 --- a/hypothesis-python/tests/cover/test_unittest.py +++ b/hypothesis-python/tests/cover/test_unittest.py @@ -14,11 +14,11 @@ import pytest +from tests.common.utils import fails_with + from hypothesis import given, strategies as st from hypothesis.errors import FailedHealthCheck, HypothesisWarning -from tests.common.utils import fails_with - class Thing_with_a_subThing(unittest.TestCase): """Example test case using subTest for the actual test below.""" diff --git a/hypothesis-python/tests/cover/test_uuids.py b/hypothesis-python/tests/cover/test_uuids.py index 3103439186..8c08129702 100644 --- a/hypothesis-python/tests/cover/test_uuids.py +++ b/hypothesis-python/tests/cover/test_uuids.py @@ -12,11 +12,10 @@ import pytest -from hypothesis import strategies as st -from hypothesis.errors import InvalidArgument - from tests.common.debug import assert_no_examples, find_any +from hypothesis import strategies as st +from hypothesis.errors import InvalidArgument def test_no_nil_uuid_by_default(): assert_no_examples(st.uuids(), lambda x: x == uuid.UUID(int=0)) diff --git a/hypothesis-python/tests/cover/test_validation.py b/hypothesis-python/tests/cover/test_validation.py index c7c57573ce..122bc76431 100644 --- a/hypothesis-python/tests/cover/test_validation.py +++ b/hypothesis-python/tests/cover/test_validation.py @@ -12,6 +12,8 @@ import pytest +from tests.common.utils import fails_with + from hypothesis import find, given from hypothesis.errors import InvalidArgument from hypothesis.internal.validation import check_type @@ -32,8 +34,6 @@ ) from hypothesis.strategies._internal.strategies import check_strategy -from tests.common.utils import fails_with - def test_errors_when_given_varargs(): @given(integers()) diff --git a/hypothesis-python/tests/cover/test_verbosity.py b/hypothesis-python/tests/cover/test_verbosity.py index f26ce8b22c..c10b1a220c 100644 --- a/hypothesis-python/tests/cover/test_verbosity.py +++ b/hypothesis-python/tests/cover/test_verbosity.py @@ -10,14 +10,14 @@ from contextlib import contextmanager +from tests.common.debug import minimal +from tests.common.utils import capture_out, fails + from hypothesis import example, find, given from hypothesis._settings import Verbosity, settings from hypothesis.reporting import default as default_reporter, with_reporter from hypothesis.strategies import booleans, integers, lists -from tests.common.debug import minimal -from tests.common.utils import capture_out, fails - @contextmanager def capture_verbosity(): diff --git a/hypothesis-python/tests/datetime/test_dateutil_timezones.py b/hypothesis-python/tests/datetime/test_dateutil_timezones.py index 0f6181831f..c93fc6a36a 100644 --- a/hypothesis-python/tests/datetime/test_dateutil_timezones.py +++ b/hypothesis-python/tests/datetime/test_dateutil_timezones.py @@ -13,16 +13,15 @@ import pytest from dateutil import tz, zoneinfo +from tests.common.debug import assert_all_examples, find_any, minimal +from tests.common.utils import fails_with + from hypothesis import assume, given from hypothesis.errors import FailedHealthCheck, InvalidArgument from hypothesis.extra.dateutil import timezones from hypothesis.strategies import data, datetimes, just, sampled_from, times from hypothesis.strategies._internal.datetime import datetime_does_not_exist -from tests.common.debug import assert_all_examples, find_any, minimal -from tests.common.utils import fails_with - - def test_utc_is_minimal(): assert tz.UTC is minimal(timezones()) diff --git a/hypothesis-python/tests/datetime/test_pytz_timezones.py b/hypothesis-python/tests/datetime/test_pytz_timezones.py index 1023401d10..0a4af3056c 100644 --- a/hypothesis-python/tests/datetime/test_pytz_timezones.py +++ b/hypothesis-python/tests/datetime/test_pytz_timezones.py @@ -14,12 +14,6 @@ import pytz from dateutil.tz import datetime_exists -from hypothesis import assume, given -from hypothesis.errors import InvalidArgument -from hypothesis.extra.pytz import timezones -from hypothesis.strategies import data, datetimes, just, sampled_from, times -from hypothesis.strategies._internal.datetime import datetime_does_not_exist - from tests.common.debug import ( assert_all_examples, assert_can_trigger_event, @@ -27,6 +21,12 @@ minimal, ) +from hypothesis import assume, given +from hypothesis.errors import InvalidArgument +from hypothesis.extra.pytz import timezones +from hypothesis.strategies import data, datetimes, just, sampled_from, times +from hypothesis.strategies._internal.datetime import datetime_does_not_exist + def test_utc_is_minimal(): assert pytz.UTC is minimal(timezones()) diff --git a/hypothesis-python/tests/datetime/test_zoneinfo_timezones.py b/hypothesis-python/tests/datetime/test_zoneinfo_timezones.py index 4832d4de83..90433b4739 100644 --- a/hypothesis-python/tests/datetime/test_zoneinfo_timezones.py +++ b/hypothesis-python/tests/datetime/test_zoneinfo_timezones.py @@ -12,13 +12,12 @@ import pytest +from tests.common.debug import assert_no_examples, find_any, minimal + from hypothesis import given, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.strategies._internal.datetime import zoneinfo -from tests.common.debug import assert_no_examples, find_any, minimal - - def test_utc_is_minimal(): assert minimal(st.timezones()) is zoneinfo.ZoneInfo("UTC") diff --git a/hypothesis-python/tests/django/manage.py b/hypothesis-python/tests/django/manage.py index be364ea9a3..940ddf5699 100755 --- a/hypothesis-python/tests/django/manage.py +++ b/hypothesis-python/tests/django/manage.py @@ -12,9 +12,11 @@ import sys import warnings +from tests.common.setup import run + from hypothesis import HealthCheck, settings -from tests.common.setup import run + if __name__ == "__main__": run() diff --git a/hypothesis-python/tests/django/toystore/test_basic_configuration.py b/hypothesis-python/tests/django/toystore/test_basic_configuration.py index 1e08417be4..0810936fb1 100644 --- a/hypothesis-python/tests/django/toystore/test_basic_configuration.py +++ b/hypothesis-python/tests/django/toystore/test_basic_configuration.py @@ -14,15 +14,14 @@ from django.db import IntegrityError from django.test import TestCase as DjangoTestCase +from tests.django.toystore.models import Company + from hypothesis import HealthCheck, Verbosity, given, settings from hypothesis.errors import InvalidArgument from hypothesis.extra.django import TestCase, TransactionTestCase from hypothesis.internal.compat import PYPY from hypothesis.strategies import integers -from tests.django.toystore.models import Company - - class SomeStuff: @settings(suppress_health_check=[HealthCheck.too_slow]) @given(integers()) diff --git a/hypothesis-python/tests/django/toystore/test_given_forms.py b/hypothesis-python/tests/django/toystore/test_given_forms.py index 9925a52657..3364cc1748 100644 --- a/hypothesis-python/tests/django/toystore/test_given_forms.py +++ b/hypothesis-python/tests/django/toystore/test_given_forms.py @@ -8,10 +8,6 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import given -from hypothesis.extra.django import TestCase, from_form, register_field_strategy -from hypothesis.strategies import booleans, sampled_from - from tests.django.toystore.forms import ( BasicFieldForm, BroadBooleanField, @@ -34,6 +30,10 @@ WithValidatorsForm, ) +from hypothesis import given +from hypothesis.extra.django import TestCase, from_form, register_field_strategy +from hypothesis.strategies import booleans, sampled_from + register_field_strategy( BroadBooleanField, booleans() | sampled_from(["1", "0", "True", "False"]) ) diff --git a/hypothesis-python/tests/django/toystore/test_given_models.py b/hypothesis-python/tests/django/toystore/test_given_models.py index f8e571a258..881c55a0f5 100644 --- a/hypothesis-python/tests/django/toystore/test_given_models.py +++ b/hypothesis-python/tests/django/toystore/test_given_models.py @@ -15,18 +15,6 @@ from django.conf import settings as django_settings from django.contrib.auth.models import User -from hypothesis import HealthCheck, assume, given, settings -from hypothesis.control import reject -from hypothesis.errors import HypothesisException, InvalidArgument -from hypothesis.extra.django import ( - TestCase, - TransactionTestCase, - from_model, - register_field_strategy, -) -from hypothesis.internal.conjecture.data import ConjectureData -from hypothesis.strategies import binary, just, lists - from tests.django.toystore.models import ( Car, Company, @@ -45,6 +33,19 @@ Store, ) + +from hypothesis import HealthCheck, assume, given, settings +from hypothesis.control import reject +from hypothesis.errors import HypothesisException, InvalidArgument +from hypothesis.extra.django import ( + TestCase, + TransactionTestCase, + from_model, + register_field_strategy, +) +from hypothesis.internal.conjecture.data import ConjectureData +from hypothesis.strategies import binary, just, lists + register_field_strategy(CustomishField, just("a")) diff --git a/hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py b/hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py index dddd434a57..c451f056da 100644 --- a/hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py +++ b/hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py @@ -176,7 +176,7 @@ def test_error_import_from_class(tmpdir, classname, thing, kind): def test_magic_discovery_from_module(tmpdir): (tmpdir / "mycode.py").write(CLASS_CODE_TO_TEST) result = subprocess.run( - f"hypothesis write mycode", + "hypothesis write mycode", capture_output=True, shell=True, text=True, @@ -223,7 +223,7 @@ def from_json(cls, json: str) -> Union[dict,list]: def test_roundtrip_correct_pairs(tmpdir): (tmpdir / "mycode.py").write(ROUNDTRIP_CODE_TO_TEST) result = subprocess.run( - f"hypothesis write mycode", + "hypothesis write mycode", capture_output=True, shell=True, text=True, diff --git a/hypothesis-python/tests/ghostwriter/try-writing-for-installed.py b/hypothesis-python/tests/ghostwriter/try-writing-for-installed.py index 2c0ba6cd53..3853bccfeb 100644 --- a/hypothesis-python/tests/ghostwriter/try-writing-for-installed.py +++ b/hypothesis-python/tests/ghostwriter/try-writing-for-installed.py @@ -19,7 +19,7 @@ just have such weird semantics that we don't _want_ to support them. """ -import distutils.sysconfig as sysconfig +import sysconfig import multiprocessing import os import subprocess diff --git a/hypothesis-python/tests/lark/test_grammar.py b/hypothesis-python/tests/lark/test_grammar.py index cd770d4b9e..14fbbf0353 100644 --- a/hypothesis-python/tests/lark/test_grammar.py +++ b/hypothesis-python/tests/lark/test_grammar.py @@ -13,12 +13,14 @@ import pytest from lark.lark import Lark +from tests.common.debug import find_any + from hypothesis import given from hypothesis.errors import InvalidArgument from hypothesis.extra.lark import from_lark from hypothesis.strategies import data, just -from tests.common.debug import find_any + # Adapted from the official Lark tutorial, with modifications to ensure # that the generated JSON is valid. i.e. no numbers starting with ".", diff --git a/hypothesis-python/tests/nocover/test_argument_validation.py b/hypothesis-python/tests/nocover/test_argument_validation.py index 9a43c7534f..3dcfec99fb 100644 --- a/hypothesis-python/tests/nocover/test_argument_validation.py +++ b/hypothesis-python/tests/nocover/test_argument_validation.py @@ -12,11 +12,11 @@ import pytest +from tests.common.arguments import argument_validation_test, e + from hypothesis import strategies as st from hypothesis.strategies._internal.utils import _strategies -from tests.common.arguments import argument_validation_test, e - BAD_ARGS = [] diff --git a/hypothesis-python/tests/nocover/test_boundary_exploration.py b/hypothesis-python/tests/nocover/test_boundary_exploration.py index 083e920449..d9252385db 100644 --- a/hypothesis-python/tests/nocover/test_boundary_exploration.py +++ b/hypothesis-python/tests/nocover/test_boundary_exploration.py @@ -10,12 +10,11 @@ import pytest -from hypothesis import HealthCheck, Verbosity, given, reject, settings, strategies as st -from hypothesis.errors import Unsatisfiable - from tests.common.debug import minimal from tests.common.utils import no_shrink +from hypothesis import HealthCheck, Verbosity, given, reject, settings, strategies as st +from hypothesis.errors import Unsatisfiable @pytest.mark.parametrize("strat", [st.text(min_size=5)]) @settings(phases=no_shrink, deadline=None, suppress_health_check=HealthCheck.all()) diff --git a/hypothesis-python/tests/nocover/test_build_signature.py b/hypothesis-python/tests/nocover/test_build_signature.py index c92136e8b1..18db6d8329 100644 --- a/hypothesis-python/tests/nocover/test_build_signature.py +++ b/hypothesis-python/tests/nocover/test_build_signature.py @@ -11,10 +11,10 @@ from inspect import signature from typing import List, get_type_hints -from hypothesis import given, strategies as st - from tests.common.debug import find_any +from hypothesis import given, strategies as st + def use_this_signature(self, a: int, b: bool = None, *, x: float, y: str): pass diff --git a/hypothesis-python/tests/nocover/test_collective_minimization.py b/hypothesis-python/tests/nocover/test_collective_minimization.py index bd51b2099c..05c44f424c 100644 --- a/hypothesis-python/tests/nocover/test_collective_minimization.py +++ b/hypothesis-python/tests/nocover/test_collective_minimization.py @@ -10,14 +10,13 @@ import pytest -from hypothesis import settings -from hypothesis.errors import Unsatisfiable -from hypothesis.strategies import lists - from tests.common import standard_types from tests.common.debug import minimal from tests.common.utils import flaky +from hypothesis import settings +from hypothesis.errors import Unsatisfiable +from hypothesis.strategies import lists @pytest.mark.parametrize("spec", standard_types, ids=list(map(repr, standard_types))) @flaky(min_passes=1, max_runs=2) diff --git a/hypothesis-python/tests/nocover/test_conjecture_engine.py b/hypothesis-python/tests/nocover/test_conjecture_engine.py index 3d6008d907..89622bca51 100644 --- a/hypothesis-python/tests/nocover/test_conjecture_engine.py +++ b/hypothesis-python/tests/nocover/test_conjecture_engine.py @@ -8,6 +8,9 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.utils import counts_calls, non_covering_examples +from tests.conjecture.common import run_to_buffer, shrinking_from + from hypothesis import given, settings, strategies as st from hypothesis.database import InMemoryExampleDatabase from hypothesis.internal.compat import int_from_bytes @@ -15,10 +18,6 @@ from hypothesis.internal.conjecture.engine import ConjectureRunner from hypothesis.internal.conjecture.shrinker import Shrinker, block_program -from tests.common.utils import counts_calls, non_covering_examples -from tests.conjecture.common import run_to_buffer, shrinking_from - - def test_lot_of_dead_nodes(): @run_to_buffer def x(data): @@ -34,7 +33,7 @@ def test_saves_data_while_shrinking(monkeypatch): key = b"hi there" n = 5 db = InMemoryExampleDatabase() - assert list(db.fetch(key)) == [] + assert not list(db.fetch(key)) seen = set() monkeypatch.setattr( diff --git a/hypothesis-python/tests/nocover/test_database_usage.py b/hypothesis-python/tests/nocover/test_database_usage.py index dcd8fafdda..2ea1742c48 100644 --- a/hypothesis-python/tests/nocover/test_database_usage.py +++ b/hypothesis-python/tests/nocover/test_database_usage.py @@ -10,14 +10,13 @@ import os.path +from tests.common.utils import all_values, non_covering_examples + from hypothesis import assume, core, find, given, settings, strategies as st from hypothesis.database import ExampleDatabase, InMemoryExampleDatabase from hypothesis.errors import NoSuchExample, Unsatisfiable from hypothesis.internal.entropy import deterministic_PRNG -from tests.common.utils import all_values, non_covering_examples - - def has_a_non_zero_byte(x): return any(bytes(x)) diff --git a/hypothesis-python/tests/nocover/test_drypython_returns.py b/hypothesis-python/tests/nocover/test_drypython_returns.py index 08167667c0..cece3c51f4 100644 --- a/hypothesis-python/tests/nocover/test_drypython_returns.py +++ b/hypothesis-python/tests/nocover/test_drypython_returns.py @@ -12,11 +12,12 @@ import pytest +from tests.common.debug import find_any +from tests.common.utils import temp_registered + from hypothesis import given, strategies as st from hypothesis.errors import ResolutionFailed -from tests.common.debug import find_any -from tests.common.utils import temp_registered # Primitives: # =========== diff --git a/hypothesis-python/tests/nocover/test_find.py b/hypothesis-python/tests/nocover/test_find.py index 2fd6c9c3fb..9343e0217f 100644 --- a/hypothesis-python/tests/nocover/test_find.py +++ b/hypothesis-python/tests/nocover/test_find.py @@ -12,12 +12,12 @@ import pytest +from tests.common.debug import minimal + from hypothesis import find, settings as Settings from hypothesis.errors import NoSuchExample from hypothesis.strategies import booleans, dictionaries, floats, integers, lists -from tests.common.debug import minimal - def test_can_find_an_int(): assert minimal(integers(), lambda x: True) == 0 diff --git a/hypothesis-python/tests/nocover/test_flatmap.py b/hypothesis-python/tests/nocover/test_flatmap.py index 2843ddef02..6f6195b693 100644 --- a/hypothesis-python/tests/nocover/test_flatmap.py +++ b/hypothesis-python/tests/nocover/test_flatmap.py @@ -12,6 +12,8 @@ import pytest +from tests.common.debug import minimal + from hypothesis import HealthCheck, assume, given, settings from hypothesis.database import ExampleDatabase from hypothesis.strategies import ( @@ -25,8 +27,6 @@ tuples, ) -from tests.common.debug import minimal - ConstantLists = integers().flatmap(lambda i: lists(just(i))) OrderedPairs = integers(1, 200).flatmap(lambda e: tuples(integers(0, e - 1), just(e))) diff --git a/hypothesis-python/tests/nocover/test_floating.py b/hypothesis-python/tests/nocover/test_floating.py index fd679c3429..d9465c3a52 100644 --- a/hypothesis-python/tests/nocover/test_floating.py +++ b/hypothesis-python/tests/nocover/test_floating.py @@ -15,13 +15,13 @@ import pytest +from tests.common.debug import find_any +from tests.common.utils import fails + from hypothesis import HealthCheck, assume, given, settings from hypothesis.internal.floats import float_to_int from hypothesis.strategies import data, floats, lists -from tests.common.debug import find_any -from tests.common.utils import fails - TRY_HARDER = settings( max_examples=1000, suppress_health_check=[HealthCheck.filter_too_much] ) diff --git a/hypothesis-python/tests/nocover/test_integer_ranges.py b/hypothesis-python/tests/nocover/test_integer_ranges.py index f8c949e161..d5bf225688 100644 --- a/hypothesis-python/tests/nocover/test_integer_ranges.py +++ b/hypothesis-python/tests/nocover/test_integer_ranges.py @@ -10,13 +10,13 @@ import pytest +from tests.common.debug import minimal + from hypothesis import given from hypothesis.internal.conjecture.utils import integer_range from hypothesis.strategies import integers from hypothesis.strategies._internal.strategies import SearchStrategy -from tests.common.debug import minimal - class interval(SearchStrategy): def __init__(self, lower, upper, center=None): diff --git a/hypothesis-python/tests/nocover/test_interesting_origin.py b/hypothesis-python/tests/nocover/test_interesting_origin.py index caa50ae91e..e786756125 100644 --- a/hypothesis-python/tests/nocover/test_interesting_origin.py +++ b/hypothesis-python/tests/nocover/test_interesting_origin.py @@ -10,11 +10,11 @@ import pytest +from tests.common.utils import flaky + from hypothesis import given, settings, strategies as st from hypothesis.internal.compat import ExceptionGroup -from tests.common.utils import flaky - def go_wrong_naive(a, b): try: diff --git a/hypothesis-python/tests/nocover/test_large_examples.py b/hypothesis-python/tests/nocover/test_large_examples.py index 72c8bfce2f..3e157a29c4 100644 --- a/hypothesis-python/tests/nocover/test_large_examples.py +++ b/hypothesis-python/tests/nocover/test_large_examples.py @@ -8,10 +8,9 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import strategies as st - from tests.common.debug import find_any +from hypothesis import strategies as st def test_can_generate_large_lists_with_min_size(): find_any(st.lists(st.integers(), min_size=400)) diff --git a/hypothesis-python/tests/nocover/test_nesting.py b/hypothesis-python/tests/nocover/test_nesting.py index 4546fba07e..5007d0f0a5 100644 --- a/hypothesis-python/tests/nocover/test_nesting.py +++ b/hypothesis-python/tests/nocover/test_nesting.py @@ -10,10 +10,8 @@ from pytest import raises -from hypothesis import Verbosity, given, settings, strategies as st - from tests.common.utils import no_shrink - +from hypothesis import Verbosity, given, settings, strategies as st def test_nesting_1(): @given(st.integers(0, 100)) diff --git a/hypothesis-python/tests/nocover/test_randomization.py b/hypothesis-python/tests/nocover/test_randomization.py index b44461fe4c..7610e8f042 100644 --- a/hypothesis-python/tests/nocover/test_randomization.py +++ b/hypothesis-python/tests/nocover/test_randomization.py @@ -10,10 +10,10 @@ from pytest import raises -from hypothesis import Verbosity, core, find, given, settings, strategies as st - from tests.common.utils import no_shrink +from hypothesis import Verbosity, core, find, given, settings, strategies as st + def test_seeds_off_internal_random(): s = settings(phases=no_shrink, database=None) diff --git a/hypothesis-python/tests/nocover/test_recursive.py b/hypothesis-python/tests/nocover/test_recursive.py index 244eaa9382..ad7760e618 100644 --- a/hypothesis-python/tests/nocover/test_recursive.py +++ b/hypothesis-python/tests/nocover/test_recursive.py @@ -10,18 +10,16 @@ import threading -from hypothesis import HealthCheck, given, settings, strategies as st - from tests.common.debug import find_any, minimal from tests.common.utils import flaky +from hypothesis import HealthCheck, given, settings, strategies as st def test_can_generate_with_large_branching(): def flatten(x): if isinstance(x, list): return sum(map(flatten, x), []) - else: - return [x] + return [x] size = 20 @@ -41,8 +39,7 @@ def test_can_generate_some_depth_with_large_branching(): def depth(x): if x and isinstance(x, list): return 1 + max(map(depth, x)) - else: - return 1 + return 1 xs = minimal( st.recursive(st.integers(), st.lists), @@ -56,8 +53,7 @@ def test_can_find_quite_broad_lists(): def breadth(x): if isinstance(x, list): return sum(map(breadth, x)) - else: - return 1 + return 1 target = 10 @@ -96,13 +92,12 @@ def test_can_use_recursive_data_in_sets(): def flatten(x): if isinstance(x, bool): return frozenset((x,)) - else: - result = frozenset() - for t in x: - result |= flatten(t) - if len(result) == 2: - break - return result + result = frozenset() + for t in x: + result |= flatten(t) + if len(result) == 2: + break + return result x = minimal(nested_sets, lambda x: len(flatten(x)) == 2, settings(deadline=None)) assert x in ( diff --git a/hypothesis-python/tests/nocover/test_regex.py b/hypothesis-python/tests/nocover/test_regex.py index 316b982adc..94cf554050 100644 --- a/hypothesis-python/tests/nocover/test_regex.py +++ b/hypothesis-python/tests/nocover/test_regex.py @@ -22,8 +22,7 @@ def charset(draw): chars = draw(st.text(string.ascii_letters + string.digits, min_size=1)) if negated: return f"[^{chars}]" - else: - return f"[{chars}]" + return f"[{chars}]" COMBINED_MATCHER = re.compile("[?+*]{2}") diff --git a/hypothesis-python/tests/nocover/test_reusable_values.py b/hypothesis-python/tests/nocover/test_reusable_values.py index ce3701a389..fb2366c072 100644 --- a/hypothesis-python/tests/nocover/test_reusable_values.py +++ b/hypothesis-python/tests/nocover/test_reusable_values.py @@ -121,8 +121,7 @@ def nontrivial_map(x): some strategies introspect their mappings.""" if cond: return x - else: - return None + return None assert s.has_reusable_values assert not s.map(nontrivial_map).has_reusable_values @@ -138,8 +137,7 @@ def nontrivial_flatmap(x): if some strategies introspect their flat-mappings.""" if cond: return st.just(x) - else: - return st.none() + return st.none() assert s.has_reusable_values assert not s.flatmap(nontrivial_flatmap).has_reusable_values diff --git a/hypothesis-python/tests/nocover/test_sampled_from.py b/hypothesis-python/tests/nocover/test_sampled_from.py index d850935cb5..501a6de7e4 100644 --- a/hypothesis-python/tests/nocover/test_sampled_from.py +++ b/hypothesis-python/tests/nocover/test_sampled_from.py @@ -12,11 +12,10 @@ import pytest -from hypothesis import given, strategies as st -from hypothesis.errors import InvalidArgument - from tests.common.utils import counts_calls, fails_with +from hypothesis import given, strategies as st +from hypothesis.errors import InvalidArgument @pytest.mark.parametrize("n", [100, 10**5, 10**6, 2**25]) def test_filter_large_lists(n): diff --git a/hypothesis-python/tests/nocover/test_sets.py b/hypothesis-python/tests/nocover/test_sets.py index 9350db9275..8b6532420f 100644 --- a/hypothesis-python/tests/nocover/test_sets.py +++ b/hypothesis-python/tests/nocover/test_sets.py @@ -8,11 +8,11 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.debug import find_any + from hypothesis import given, settings from hypothesis.strategies import floats, integers, sets -from tests.common.debug import find_any - def test_can_draw_sets_of_hard_to_find_elements(): rarebool = floats(0, 1).map(lambda x: x <= 0.05) diff --git a/hypothesis-python/tests/nocover/test_sharing.py b/hypothesis-python/tests/nocover/test_sharing.py index bc41945c08..3507f7a3ce 100644 --- a/hypothesis-python/tests/nocover/test_sharing.py +++ b/hypothesis-python/tests/nocover/test_sharing.py @@ -8,10 +8,10 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import given, strategies as st - from tests.common.debug import find_any, minimal +from hypothesis import given, strategies as st + x = st.shared(st.integers()) diff --git a/hypothesis-python/tests/nocover/test_simple_numbers.py b/hypothesis-python/tests/nocover/test_simple_numbers.py index c3dfda4034..6490916b52 100644 --- a/hypothesis-python/tests/nocover/test_simple_numbers.py +++ b/hypothesis-python/tests/nocover/test_simple_numbers.py @@ -13,11 +13,11 @@ import pytest +from tests.common.debug import minimal + from hypothesis import given from hypothesis.strategies import floats, integers, lists -from tests.common.debug import minimal - def test_minimize_negative_int(): assert minimal(integers(), lambda x: x < 0) == -1 diff --git a/hypothesis-python/tests/nocover/test_skipping.py b/hypothesis-python/tests/nocover/test_skipping.py index 608b9d679a..6e62734966 100644 --- a/hypothesis-python/tests/nocover/test_skipping.py +++ b/hypothesis-python/tests/nocover/test_skipping.py @@ -12,13 +12,13 @@ import pytest +from tests.common.utils import capture_out + + from hypothesis import given from hypothesis.core import skip_exceptions_to_reraise from hypothesis.strategies import integers -from tests.common.utils import capture_out - - @pytest.mark.parametrize("skip_exception", skip_exceptions_to_reraise()) def test_no_falsifying_example_if_unittest_skip(skip_exception): """If a ``SkipTest`` exception is raised during a test, Hypothesis should @@ -30,8 +30,7 @@ class DemoTest(unittest.TestCase): def test_to_be_skipped(self, xs): if xs == 0: raise skip_exception - else: - assert xs == 0 + assert xs == 0 with capture_out() as o: suite = unittest.defaultTestLoader.loadTestsFromTestCase(DemoTest) diff --git a/hypothesis-python/tests/nocover/test_stateful.py b/hypothesis-python/tests/nocover/test_stateful.py index b9a2e07429..e62d166800 100644 --- a/hypothesis-python/tests/nocover/test_stateful.py +++ b/hypothesis-python/tests/nocover/test_stateful.py @@ -35,16 +35,14 @@ def split(self, left, right): def test_is_balanced(self, tree): if isinstance(tree, Leaf): return - else: - assert abs(self.size(tree.left) - self.size(tree.right)) <= 1 - self.test_is_balanced(tree.left) - self.test_is_balanced(tree.right) + assert abs(self.size(tree.left) - self.size(tree.right)) <= 1 + self.test_is_balanced(tree.left) + self.test_is_balanced(tree.right) def size(self, tree): if isinstance(tree, Leaf): return 1 - else: - return 1 + self.size(tree.left) + self.size(tree.right) + return 1 + self.size(tree.left) + self.size(tree.right) class DepthCharge: @@ -83,8 +81,7 @@ def shallow(self, source): def d(ls): if not ls: return 0 - else: - return 1 + max(map(d, ls)) + return 1 + max(map(d, ls)) assert d(source) <= 5 diff --git a/hypothesis-python/tests/nocover/test_strategy_state.py b/hypothesis-python/tests/nocover/test_strategy_state.py index 97ab43e7a8..5366330f25 100644 --- a/hypothesis-python/tests/nocover/test_strategy_state.py +++ b/hypothesis-python/tests/nocover/test_strategy_state.py @@ -150,8 +150,7 @@ def do_map(value): random = Random(hashlib.sha384((mixer + rep).encode()).digest()) if random.random() <= p: return result1 - else: - return result2 + return result2 return source.flatmap(do_map) diff --git a/hypothesis-python/tests/nocover/test_subnormal_floats.py b/hypothesis-python/tests/nocover/test_subnormal_floats.py index 22881eb51c..239604bc2b 100644 --- a/hypothesis-python/tests/nocover/test_subnormal_floats.py +++ b/hypothesis-python/tests/nocover/test_subnormal_floats.py @@ -13,12 +13,12 @@ import pytest -from hypothesis.internal.floats import width_smallest_normals -from hypothesis.strategies import floats - from tests.common.debug import assert_all_examples, find_any from tests.common.utils import PYTHON_FTZ +from hypothesis.internal.floats import width_smallest_normals +from hypothesis.strategies import floats + def test_python_compiled_with_sane_math_options(): """Python does not flush-to-zero, which violates IEEE-754 diff --git a/hypothesis-python/tests/nocover/test_type_lookup_forward_ref.py b/hypothesis-python/tests/nocover/test_type_lookup_forward_ref.py index 5f4f60a98d..d9538e6063 100644 --- a/hypothesis-python/tests/nocover/test_type_lookup_forward_ref.py +++ b/hypothesis-python/tests/nocover/test_type_lookup_forward_ref.py @@ -12,11 +12,11 @@ import pytest +from tests.common import utils + from hypothesis import given, strategies as st from hypothesis.errors import ResolutionFailed -from tests.common import utils - # Mutually-recursive types # See https://github.com/HypothesisWorks/hypothesis/issues/2722 diff --git a/hypothesis-python/tests/nocover/test_uuids.py b/hypothesis-python/tests/nocover/test_uuids.py index 2b4c2ffed6..95d12d8a57 100644 --- a/hypothesis-python/tests/nocover/test_uuids.py +++ b/hypothesis-python/tests/nocover/test_uuids.py @@ -10,10 +10,9 @@ import pytest -from hypothesis import given, strategies as st - from tests.common.debug import minimal +from hypothesis import given, strategies as st @given(st.lists(st.uuids())) def test_are_unique(ls): diff --git a/hypothesis-python/tests/numpy/test_argument_validation.py b/hypothesis-python/tests/numpy/test_argument_validation.py index 3215945152..1b41789bc3 100644 --- a/hypothesis-python/tests/numpy/test_argument_validation.py +++ b/hypothesis-python/tests/numpy/test_argument_validation.py @@ -11,13 +11,12 @@ import numpy import pytest +from tests.common.utils import checks_deprecated_behaviour + from hypothesis import strategies as st from hypothesis.errors import InvalidArgument from hypothesis.extra import numpy as nps -from tests.common.utils import checks_deprecated_behaviour - - def e(a, **kwargs): kw = ", ".join(f"{k}={v!r}" for k, v in kwargs.items()) return pytest.param(a, kwargs, id=f"{a.__name__}({kw})") diff --git a/hypothesis-python/tests/numpy/test_fill_values.py b/hypothesis-python/tests/numpy/test_fill_values.py index bb535e3da1..67814b5564 100644 --- a/hypothesis-python/tests/numpy/test_fill_values.py +++ b/hypothesis-python/tests/numpy/test_fill_values.py @@ -8,11 +8,11 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.debug import find_any, minimal + from hypothesis import given, strategies as st from hypothesis.extra.numpy import arrays -from tests.common.debug import find_any, minimal - @given(arrays(object, 100, elements=st.builds(list))) def test_generated_lists_are_distinct(ls): diff --git a/hypothesis-python/tests/numpy/test_floor_ceil.py b/hypothesis-python/tests/numpy/test_floor_ceil.py index 1d3f35f30e..f8568b0a52 100644 --- a/hypothesis-python/tests/numpy/test_floor_ceil.py +++ b/hypothesis-python/tests/numpy/test_floor_ceil.py @@ -37,8 +37,8 @@ def test_our_floor_and_ceil_avoid_numpy_rounding(value): f = floor(a) c = ceil(a) - assert type(f) == int - assert type(c) == int + assert isinstance(f, int) + assert isinstance(c, int) # Using math.floor or math.ceil for these values would give an incorrect # result. diff --git a/hypothesis-python/tests/numpy/test_from_dtype.py b/hypothesis-python/tests/numpy/test_from_dtype.py index 5b4850d18c..14c6305cb5 100644 --- a/hypothesis-python/tests/numpy/test_from_dtype.py +++ b/hypothesis-python/tests/numpy/test_from_dtype.py @@ -11,13 +11,13 @@ import numpy as np import pytest +from tests.common.debug import find_any + from hypothesis import assume, given, settings, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.extra import numpy as nps from hypothesis.strategies._internal import SearchStrategy -from tests.common.debug import find_any - STANDARD_TYPES = [ np.dtype(t) for t in ( @@ -168,14 +168,14 @@ def test_all_inferred_scalar_strategies_roundtrip(data, dtype): @given(data=st.data()) def test_from_dtype_works_without_time_unit(data, dtype_str): arr = data.draw(nps.from_dtype(np.dtype(dtype_str))) - assert (dtype_str + "[") in arr.dtype.str + assert dtype_str + "[" in arr.dtype.str @pytest.mark.parametrize("dtype_str", ["m8", "M8"]) @given(data=st.data()) def test_arrays_selects_consistent_time_unit(data, dtype_str): arr = data.draw(nps.arrays(dtype_str, 10)) - assert (dtype_str + "[") in arr.dtype.str + assert dtype_str + "[" in arr.dtype.str def test_arrays_gives_useful_error_on_inconsistent_time_unit(): diff --git a/hypothesis-python/tests/numpy/test_gen_data.py b/hypothesis-python/tests/numpy/test_gen_data.py index 554efc1df8..8a7801aff8 100644 --- a/hypothesis-python/tests/numpy/test_gen_data.py +++ b/hypothesis-python/tests/numpy/test_gen_data.py @@ -15,6 +15,9 @@ import numpy as np import pytest +from tests.common.debug import find_any, minimal +from tests.common.utils import fails_with, flaky + from hypothesis import ( HealthCheck, assume, @@ -27,9 +30,6 @@ from hypothesis.errors import InvalidArgument, UnsatisfiedAssumption from hypothesis.extra import numpy as nps -from tests.common.debug import find_any, minimal -from tests.common.utils import fails_with, flaky - ANY_SHAPE = nps.array_shapes(min_dims=0, max_dims=32, min_side=0, max_side=32) ANY_NONZERO_SHAPE = nps.array_shapes(min_dims=0, max_dims=32, min_side=1, max_side=32) diff --git a/hypothesis-python/tests/numpy/test_gufunc.py b/hypothesis-python/tests/numpy/test_gufunc.py index 9ec70f2dc7..c7bff0d4ab 100644 --- a/hypothesis-python/tests/numpy/test_gufunc.py +++ b/hypothesis-python/tests/numpy/test_gufunc.py @@ -12,6 +12,8 @@ import pytest from pytest import param +from tests.common.debug import find_any, minimal + from hypothesis import example, given, note, settings, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.extra import numpy as nps @@ -20,8 +22,6 @@ _hypothesis_parse_gufunc_signature, ) -from tests.common.debug import find_any, minimal - def use_signature_examples(func): for sig in [ diff --git a/hypothesis-python/tests/numpy/test_sampled_from.py b/hypothesis-python/tests/numpy/test_sampled_from.py index 6904b60877..52c844449c 100644 --- a/hypothesis-python/tests/numpy/test_sampled_from.py +++ b/hypothesis-python/tests/numpy/test_sampled_from.py @@ -8,13 +8,13 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. +from tests.common.utils import fails_with + from hypothesis import given from hypothesis.errors import InvalidArgument from hypothesis.extra import numpy as npst from hypothesis.strategies import data, sampled_from -from tests.common.utils import fails_with - @given( data(), npst.arrays(dtype=npst.scalar_dtypes(), shape=npst.array_shapes(max_dims=1)) diff --git a/hypothesis-python/tests/pandas/test_argument_validation.py b/hypothesis-python/tests/pandas/test_argument_validation.py index 4d2d5d1ba2..16e45be714 100644 --- a/hypothesis-python/tests/pandas/test_argument_validation.py +++ b/hypothesis-python/tests/pandas/test_argument_validation.py @@ -12,12 +12,12 @@ import pandas as pd -from hypothesis import given, strategies as st -from hypothesis.extra import pandas as pdst - from tests.common.arguments import argument_validation_test, e from tests.common.utils import checks_deprecated_behaviour +from hypothesis import given, strategies as st +from hypothesis.extra import pandas as pdst + BAD_ARGS = [ e(pdst.data_frames), e(pdst.data_frames, pdst.columns(1, dtype="not a dtype")), diff --git a/hypothesis-python/tests/pandas/test_data_frame.py b/hypothesis-python/tests/pandas/test_data_frame.py index 1a0789c332..531b6f08fa 100644 --- a/hypothesis-python/tests/pandas/test_data_frame.py +++ b/hypothesis-python/tests/pandas/test_data_frame.py @@ -11,12 +11,12 @@ import numpy as np import pytest -from hypothesis import HealthCheck, given, reject, settings, strategies as st -from hypothesis.extra import numpy as npst, pandas as pdst - from tests.common.debug import find_any from tests.pandas.helpers import supported_by_pandas +from hypothesis import HealthCheck, given, reject, settings, strategies as st +from hypothesis.extra import numpy as npst, pandas as pdst + @given(pdst.data_frames([pdst.column("a", dtype=int), pdst.column("b", dtype=float)])) def test_can_have_columns_of_distinct_types(df): diff --git a/hypothesis-python/tests/pandas/test_indexes.py b/hypothesis-python/tests/pandas/test_indexes.py index ac5caeba5b..836525071f 100644 --- a/hypothesis-python/tests/pandas/test_indexes.py +++ b/hypothesis-python/tests/pandas/test_indexes.py @@ -12,12 +12,12 @@ import pandas import pytest +from tests.pandas.helpers import supported_by_pandas + from hypothesis import HealthCheck, given, reject, settings, strategies as st from hypothesis.errors import Unsatisfiable from hypothesis.extra import numpy as npst, pandas as pdst -from tests.pandas.helpers import supported_by_pandas - @given(pdst.indexes(dtype=int, max_size=0)) def test_gets_right_dtype_for_empty_indices(ix): diff --git a/hypothesis-python/tests/pandas/test_series.py b/hypothesis-python/tests/pandas/test_series.py index c796b8175d..28ed988eca 100644 --- a/hypothesis-python/tests/pandas/test_series.py +++ b/hypothesis-python/tests/pandas/test_series.py @@ -11,12 +11,12 @@ import numpy as np import pandas -from hypothesis import assume, given, strategies as st -from hypothesis.extra import numpy as npst, pandas as pdst - from tests.common.debug import find_any from tests.pandas.helpers import supported_by_pandas +from hypothesis import assume, given, strategies as st +from hypothesis.extra import numpy as npst, pandas as pdst + @given(st.data()) def test_can_create_a_series_of_any_dtype(data): diff --git a/hypothesis-python/tests/pytest/test_capture.py b/hypothesis-python/tests/pytest/test_capture.py index 33688aab85..a6b00e63ed 100644 --- a/hypothesis-python/tests/pytest/test_capture.py +++ b/hypothesis-python/tests/pytest/test_capture.py @@ -78,8 +78,7 @@ def get_line_num(token, result, skip_n=0): if token in line: if skip_n == skipped: return i - else: - skipped += 1 + skipped += 1 raise AssertionError( f"Token {token!r} not found (skipped {skipped} of planned {skip_n} skips)" ) diff --git a/hypothesis-python/tests/pytest/test_fixtures.py b/hypothesis-python/tests/pytest/test_fixtures.py index 368911d395..cfe963c348 100644 --- a/hypothesis-python/tests/pytest/test_fixtures.py +++ b/hypothesis-python/tests/pytest/test_fixtures.py @@ -12,11 +12,11 @@ import pytest +from tests.common.utils import fails + from hypothesis import example, given from hypothesis.strategies import integers -from tests.common.utils import fails - pytest_plugins = "pytester" @@ -206,7 +206,7 @@ def test(x): def test_fixture_errors_if_already_decorated_with_given(testdir): script = testdir.makepyfile(TESTSCRIPT_GIVEN_THEN_FIXTURE) - if int(pytest.__version__.split(".")[0]) > 5: + if int(pytest.__version__.split('.', maxsplit=1)[0]) > 5: testdir.runpytest(script).assert_outcomes(errors=1) else: testdir.runpytest(script).assert_outcomes(error=1) diff --git a/hypothesis-python/tests/pytest/test_runs.py b/hypothesis-python/tests/pytest/test_runs.py index cd1a147f38..50c0ba643f 100644 --- a/hypothesis-python/tests/pytest/test_runs.py +++ b/hypothesis-python/tests/pytest/test_runs.py @@ -8,11 +8,10 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import given -from hypothesis.strategies import integers - from tests.common.utils import fails +from hypothesis import given +from hypothesis.strategies import integers @given(integers()) def test_ints_are_ints(x): diff --git a/hypothesis-python/tests/quality/test_deferred_strategies.py b/hypothesis-python/tests/quality/test_deferred_strategies.py index e395b9749c..6ae74b4b45 100644 --- a/hypothesis-python/tests/quality/test_deferred_strategies.py +++ b/hypothesis-python/tests/quality/test_deferred_strategies.py @@ -8,10 +8,9 @@ # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at https://mozilla.org/MPL/2.0/. -from hypothesis import strategies as st - from tests.common.debug import minimal +from hypothesis import strategies as st def test_large_branching_tree(): tree = st.deferred(lambda: st.integers() | st.tuples(tree, tree, tree, tree, tree)) diff --git a/hypothesis-python/tests/quality/test_discovery_ability.py b/hypothesis-python/tests/quality/test_discovery_ability.py index 0e6d9c0378..9f3cabf63c 100644 --- a/hypothesis-python/tests/quality/test_discovery_ability.py +++ b/hypothesis-python/tests/quality/test_discovery_ability.py @@ -22,6 +22,8 @@ import math import re +from tests.common.utils import no_shrink + from hypothesis import HealthCheck, settings as Settings from hypothesis.errors import UnsatisfiedAssumption from hypothesis.internal import reflection @@ -40,8 +42,6 @@ tuples, ) -from tests.common.utils import no_shrink - RUNS = 100 diff --git a/hypothesis-python/tests/quality/test_float_shrinking.py b/hypothesis-python/tests/quality/test_float_shrinking.py index 3e545dc427..d640d5c3e5 100644 --- a/hypothesis-python/tests/quality/test_float_shrinking.py +++ b/hypothesis-python/tests/quality/test_float_shrinking.py @@ -10,6 +10,8 @@ import pytest +from tests.common.debug import minimal + from hypothesis import ( HealthCheck, Verbosity, @@ -21,9 +23,6 @@ ) from hypothesis.internal.compat import ceil -from tests.common.debug import minimal - - def test_shrinks_to_simple_floats(): assert minimal(st.floats(), lambda x: x > 1) == 2.0 assert minimal(st.floats(), lambda x: x > 0) == 1.0 diff --git a/hypothesis-python/tests/quality/test_normalization.py b/hypothesis-python/tests/quality/test_normalization.py index 8355380045..710f823ab8 100644 --- a/hypothesis-python/tests/quality/test_normalization.py +++ b/hypothesis-python/tests/quality/test_normalization.py @@ -13,19 +13,18 @@ import pytest +from tests.quality.test_shrinking_order import iter_values + from hypothesis import strategies as st from hypothesis.errors import UnsatisfiedAssumption from hypothesis.internal.conjecture.shrinking import dfas -from tests.quality.test_shrinking_order import iter_values - @pytest.fixture def normalize_kwargs(request): if request.config.getoption("--hypothesis-learn-to-normalize"): return {"allowed_to_update": True, "required_successes": 1000} - else: - return {"allowed_to_update": False, "required_successes": 10} + return {"allowed_to_update": False, "required_successes": 10} @pytest.mark.parametrize("n", range(10, -1, -1)) diff --git a/hypothesis-python/tests/quality/test_poisoned_lists.py b/hypothesis-python/tests/quality/test_poisoned_lists.py index 1d5c8d5f96..74015a7d4b 100644 --- a/hypothesis-python/tests/quality/test_poisoned_lists.py +++ b/hypothesis-python/tests/quality/test_poisoned_lists.py @@ -30,8 +30,7 @@ def __init__(self, poison_chance): def do_draw(self, data): if cu.biased_coin(data, self.__poison_chance): return POISON - else: - return data.draw(self.__ints) + return data.draw(self.__ints) class LinearLists(SearchStrategy): diff --git a/hypothesis-python/tests/quality/test_poisoned_trees.py b/hypothesis-python/tests/quality/test_poisoned_trees.py index 60b7ec5f3c..0e4eebc4ce 100644 --- a/hypothesis-python/tests/quality/test_poisoned_trees.py +++ b/hypothesis-python/tests/quality/test_poisoned_trees.py @@ -36,16 +36,14 @@ def __init__(self, p): def do_draw(self, data): if cu.biased_coin(data, self.__p): return data.draw(self) + data.draw(self) - else: - # We draw n as two separate calls so that it doesn't show up as a - # single block. If it did, the heuristics that allow us to move - # blocks around would fire and it would move right, which would - # then allow us to shrink it more easily. - n = (data.draw_bits(16) << 16) | data.draw_bits(16) - if n == MAX_INT: - return (POISON,) - else: - return (None,) + # We draw n as two separate calls so that it doesn't show up as a + # single block. If it did, the heuristics that allow us to move + # blocks around would fire and it would move right, which would + # then allow us to shrink it more easily. + n = (data.draw_bits(16) << 16) | data.draw_bits(16) + if n == MAX_INT: + return (POISON,) + return (None,) LOTS = 10**6 diff --git a/hypothesis-python/tests/quality/test_shrink_quality.py b/hypothesis-python/tests/quality/test_shrink_quality.py index 1586289dd0..fabf4ce4dd 100644 --- a/hypothesis-python/tests/quality/test_shrink_quality.py +++ b/hypothesis-python/tests/quality/test_shrink_quality.py @@ -14,6 +14,9 @@ import pytest +from tests.common.debug import minimal +from tests.common.utils import flaky + import hypothesis.strategies as st from hypothesis import assume, settings from hypothesis.strategies import ( @@ -33,9 +36,6 @@ tuples, ) -from tests.common.debug import minimal -from tests.common.utils import flaky - def test_integers_from_minimizes_leftwards(): assert minimal(integers(min_value=101)) == 101 @@ -375,11 +375,10 @@ def div_subterms(e): def evaluate(e): if isinstance(e, int): return e - elif e[0] == "+": + if e[0] == "+": return evaluate(e[1]) + evaluate(e[2]) - else: - assert e[0] == "/" - return evaluate(e[1]) // evaluate(e[2]) + assert e[0] == "/" + return evaluate(e[1]) // evaluate(e[2]) def is_failing(e): assume(div_subterms(e)) diff --git a/hypothesis-python/tests/redis/test_redis_exampledatabase.py b/hypothesis-python/tests/redis/test_redis_exampledatabase.py index f51a89f517..9894ba6ece 100644 --- a/hypothesis-python/tests/redis/test_redis_exampledatabase.py +++ b/hypothesis-python/tests/redis/test_redis_exampledatabase.py @@ -36,10 +36,10 @@ def test_all_methods(): db.save(b"key1", b"value") assert list(db.fetch(b"key1")) == [b"value"] db.move(b"key1", b"key2", b"value") - assert list(db.fetch(b"key1")) == [] + assert not list(db.fetch(b"key1")) assert list(db.fetch(b"key2")) == [b"value"] db.delete(b"key2", b"value") - assert list(db.fetch(b"key2")) == [] + assert not list(db.fetch(b"key2")) db.delete(b"key2", b"unknown value") diff --git a/hypothesis-python/tests/typing_extensions/test_backported_types.py b/hypothesis-python/tests/typing_extensions/test_backported_types.py index a6f3512de0..cf508ef7db 100644 --- a/hypothesis-python/tests/typing_extensions/test_backported_types.py +++ b/hypothesis-python/tests/typing_extensions/test_backported_types.py @@ -24,13 +24,13 @@ TypeGuard, ) +from tests.common.debug import assert_all_examples, find_any + from hypothesis import assume, given, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.strategies import from_type from hypothesis.strategies._internal.types import NON_RUNTIME_TYPES -from tests.common.debug import assert_all_examples, find_any - # See also nocover/test_type_lookup.py @@ -63,7 +63,7 @@ class A(TypedDict): @given(from_type(A)) def test_simple_typeddict(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value) == {"a"} assert isinstance(value["a"], int) @@ -212,7 +212,7 @@ class Movie(TypedDict): # implicitly total=True @given(from_type(Movie)) def test_typeddict_not_required(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value).issubset({"title", "year"}) assert isinstance(value["title"], str) if "year" in value: @@ -230,7 +230,7 @@ class OtherMovie(TypedDict, total=False): @given(from_type(OtherMovie)) def test_typeddict_required(value): - assert type(value) == dict + assert isinstance(value, dict) assert set(value).issubset({"title", "year"}) assert isinstance(value["title"], str) if "year" in value: diff --git a/tooling/src/hypothesistooling/__main__.py b/tooling/src/hypothesistooling/__main__.py index b73f31bc6d..36af508b81 100644 --- a/tooling/src/hypothesistooling/__main__.py +++ b/tooling/src/hypothesistooling/__main__.py @@ -299,7 +299,7 @@ def update_vendored_files(): # Turns out that as well as adding new gTLDs, IANA can *terminate* old ones url = "http://data.iana.org/TLD/tlds-alpha-by-domain.txt" - fname = vendor / url.split("/")[-1] + fname = vendor / url.split("/", maxsplit=1)[-1] new = requests.get(url).content # If only the timestamp in the header comment has changed, skip the update. if fname.read_bytes().splitlines()[1:] != new.splitlines()[1:]: From 1999cd2079472a35897e06ac67c83f355b4c44eb Mon Sep 17 00:00:00 2001 From: Mark Mayo Date: Wed, 2 Nov 2022 17:17:57 +1300 Subject: [PATCH 2/2] Update escalation.py Stupid typo fixed --- hypothesis-python/src/hypothesis/internal/escalation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hypothesis-python/src/hypothesis/internal/escalation.py b/hypothesis-python/src/hypothesis/internal/escalation.py index 59d504e137..4eb1fd421b 100644 --- a/hypothesis-python/src/hypothesis/internal/escalation.py +++ b/hypothesis-python/src/hypothesis/internal/escalation.py @@ -1,4 +1,4 @@ -v# This file is part of Hypothesis, which may be found at +# This file is part of Hypothesis, which may be found at # https://github.com/HypothesisWorks/hypothesis/ # # Copyright the Hypothesis Authors.