Best Python code snippet using hypothesis
_settings.py
Source:_settings.py
...216 # @settings was applied, because @given also assigns that attribute.217 test._hypothesis_internal_settings_applied = True218 return test_to_use219 @classmethod220 def _define_setting(221 cls, name, description, default, options=None,222 validator=None, show_default=True, future_default=not_set,223 deprecation_message=None, hide_repr=not_set,224 ):225 """Add a new setting.226 - name is the name of the property that will be used to access the227 setting. This must be a valid python identifier.228 - description will appear in the property's docstring229 - default is the default value. This may be a zero argument230 function in which case it is evaluated and its result is stored231 the first time it is accessed on any given settings object.232 """233 if settings.__definitions_are_locked:234 raise InvalidState(235 'settings have been locked and may no longer be defined.'236 )237 if options is not None:238 options = tuple(options)239 assert default in options240 if future_default is not_set:241 future_default = default242 if hide_repr is not_set:243 hide_repr = bool(deprecation_message)244 all_settings[name] = Setting(245 name, description.strip(), default, options, validator,246 future_default, deprecation_message, hide_repr,247 )248 setattr(settings, name, settingsProperty(name, show_default))249 @classmethod250 def lock_further_definitions(cls):251 settings.__definitions_are_locked = True252 def __setattr__(self, name, value):253 if name in settings._WHITELISTED_REAL_PROPERTIES:254 return object.__setattr__(self, name, value)255 elif name in all_settings:256 if self._construction_complete:257 raise AttributeError(258 'settings objects are immutable and may not be assigned to'259 ' after construction.'260 )261 else:262 setting = all_settings[name]263 if (264 setting.options is not None and265 value not in setting.options266 ):267 raise InvalidArgument(268 'Invalid %s, %r. Valid options: %r' % (269 name, value, setting.options270 )271 )272 return object.__setattr__(self, name, value)273 else:274 raise AttributeError('No such setting %s' % (name,))275 def __repr__(self):276 bits = []277 for name, setting in all_settings.items():278 value = getattr(self, name)279 # The only settings that are not shown are those that are280 # deprecated and left at their default values.281 if value != setting.default or not setting.hide_repr:282 bits.append('%s=%r' % (name, value))283 return 'settings(%s)' % ', '.join(sorted(bits))284 def show_changed(self):285 bits = []286 for name, setting in all_settings.items():287 value = getattr(self, name)288 if value != setting.default:289 bits.append('%s=%r' % (name, value))290 return ', '.join(sorted(bits, key=len))291 def __enter__(self):292 note_deprecation(293 'Settings should be determined only by global state or with the '294 '@settings decorator.'295 )296 default_context_manager = default_variable.with_value(self)297 self.defaults_stack().append(default_context_manager)298 default_context_manager.__enter__()299 return self300 def __exit__(self, *args, **kwargs):301 default_context_manager = self.defaults_stack().pop()302 return default_context_manager.__exit__(*args, **kwargs)303 @staticmethod304 def register_profile(name, parent=None, **kwargs):305 # type: (str, settings, **Any) -> None306 """Registers a collection of values to be used as a settings profile.307 Settings profiles can be loaded by name - for example, you might308 create a 'fast' profile which runs fewer examples, keep the 'default'309 profile, and create a 'ci' profile that increases the number of310 examples and uses a different database to store failures.311 The arguments to this method are exactly as for312 :class:`~hypothesis.settings`: optional ``parent`` settings, and313 keyword arguments for each setting that will be set differently to314 parent (or settings.default, if parent is None).315 """316 if not isinstance(name, (str, text_type)):317 note_deprecation('name=%r must be a string' % (name,))318 if 'settings' in kwargs:319 if parent is None:320 parent = kwargs.pop('settings')321 note_deprecation('The `settings` argument is deprecated - '322 'use `parent` instead.')323 else:324 raise InvalidArgument(325 'The `settings` argument is deprecated, and has been '326 'replaced by the `parent` argument. Use `parent` only.'327 )328 settings._profiles[name] = settings(parent=parent, **kwargs)329 @staticmethod330 def get_profile(name):331 # type: (str) -> settings332 """Return the profile with the given name."""333 if not isinstance(name, (str, text_type)):334 note_deprecation('name=%r must be a string' % (name,))335 try:336 return settings._profiles[name]337 except KeyError:338 raise InvalidArgument('Profile %r is not registered' % (name,))339 @staticmethod340 def load_profile(name):341 # type: (str) -> None342 """Loads in the settings defined in the profile provided.343 If the profile does not exist, InvalidArgument will be raised.344 Any setting not defined in the profile will be the library345 defined default for that setting.346 """347 if not isinstance(name, (str, text_type)):348 note_deprecation('name=%r must be a string' % (name,))349 settings._current_profile = name350 settings._assign_default_internal(settings.get_profile(name))351@contextlib.contextmanager352def local_settings(s):353 default_context_manager = default_variable.with_value(s)354 with default_context_manager:355 yield s356@attr.s()357class Setting(object):358 name = attr.ib()359 description = attr.ib()360 default = attr.ib()361 options = attr.ib()362 validator = attr.ib()363 future_default = attr.ib()364 deprecation_message = attr.ib()365 hide_repr = attr.ib()366settings._define_setting(367 'min_satisfying_examples',368 default=not_set,369 description="""370This doesn't actually do anything, but remains for compatibility reasons.371""",372 deprecation_message="""373The min_satisfying_examples setting has been deprecated and disabled, due to374overlap with the filter_too_much healthcheck and poor interaction with the375max_examples setting.376"""377)378settings._define_setting(379 'max_examples',380 default=100,381 description="""382Once this many satisfying examples have been considered without finding any383counter-example, falsification will terminate.384"""385)386settings._define_setting(387 'max_iterations',388 default=not_set,389 description="""390This doesn't actually do anything, but remains for compatibility reasons.391""",392 deprecation_message="""393The max_iterations setting has been disabled, as internal heuristics are more394useful for this purpose than a user setting. It no longer has any effect.395"""396)397settings._define_setting(398 'buffer_size',399 default=8 * 1024,400 description="""401The size of the underlying data used to generate examples. If you need to402generate really large examples you may want to increase this, but it will make403your tests slower.404"""405)406settings._define_setting(407 'max_shrinks',408 default=not_set,409 description="""410Passing ``max_shrinks=0`` disables the shrinking phase (see the ``phases``411setting), but any other value has no effect and uses a general heuristic.412""",413 deprecation_message="""414The max_shrinks setting has been disabled, as internal heuristics are more415useful for this purpose than a user setting.416"""417)418def _validate_timeout(n):419 if n is unlimited:420 return -1421 else:422 return n423settings._define_setting(424 'timeout',425 default=60,426 description="""427Once this many seconds have passed, falsify will terminate even428if it has not found many examples. This is a soft rather than a hard429limit - Hypothesis won't e.g. interrupt execution of the called430function to stop it. If this value is <= 0 then no timeout will be431applied.432""",433 hide_repr=False, # Still affects behaviour at runtime434 deprecation_message="""435The timeout setting is deprecated and will be removed in a future version of436Hypothesis. To get the future behaviour set ``timeout=hypothesis.unlimited``437instead (which will remain valid for a further deprecation period after this438setting has gone away).439""",440 future_default=unlimited,441 validator=_validate_timeout442)443settings._define_setting(444 'derandomize',445 default=False,446 description="""447If this is True then hypothesis will run in deterministic mode448where each falsification uses a random number generator that is seeded449based on the hypothesis to falsify, which will be consistent across450multiple runs. This has the advantage that it will eliminate any451randomness from your tests, which may be preferable for some situations.452It does have the disadvantage of making your tests less likely to453find novel breakages.454"""455)456settings._define_setting(457 'strict',458 default=os.getenv('HYPOTHESIS_STRICT_MODE') == 'true',459 description="""460Strict mode has been deprecated in favor of Python's standard warnings461controls. Ironically, enabling it is therefore an error - it only exists so462that users get the right *type* of error!463""",464 deprecation_message="""465Strict mode is deprecated and will go away in a future version of Hypothesis.466To get the same behaviour, use467warnings.simplefilter('error', HypothesisDeprecationWarning).468""",469 future_default=False,470)471def _validate_database(db, _from_db_file=False):472 from hypothesis.database import ExampleDatabase473 if db is None or isinstance(db, ExampleDatabase):474 return db475 if _from_db_file or db is not_set:476 return ExampleDatabase(db)477 raise InvalidArgument(478 'Arguments to the database setting must be None or an instance of '479 'ExampleDatabase. Try passing database=ExampleDatabase(%r), or '480 'construct and use one of the specific subclasses in '481 'hypothesis.database' % (db,)482 )483settings._define_setting(484 'database',485 default=not_set,486 show_default=False,487 description="""488An instance of hypothesis.database.ExampleDatabase that will be489used to save examples to and load previous examples from. May be None490in which case no storage will be used, `:memory:` for an in-memory491database, or any path for a directory-based example database.492""",493 validator=_validate_database,494)495settings._define_setting(496 'database_file',497 default=not_set,498 show_default=False,499 description="""500The file or directory location to save and load previously tried examples;501`:memory:` for an in-memory cache or None to disable caching entirely.502""",503 validator=lambda f: _validate_database(f, _from_db_file=True),504 deprecation_message="""505The `database_file` setting is deprecated in favor of the `database`506setting, and will be removed in a future version. It only exists at507all for complicated historical reasons and you should just use508`database` instead.509""",510)511@unique512class Phase(IntEnum):513 explicit = 0514 reuse = 1515 generate = 2516 shrink = 3517@unique518class HealthCheck(Enum):519 """Arguments for :attr:`~hypothesis.settings.suppress_health_check`.520 Each member of this enum is a type of health check to suppress.521 """522 def __repr__(self):523 return '%s.%s' % (self.__class__.__name__, self.name)524 @classmethod525 def all(cls):526 # type: () -> List[HealthCheck]527 bad = (HealthCheck.exception_in_generation, HealthCheck.random_module)528 return [h for h in list(cls) if h not in bad]529 exception_in_generation = 0530 """Deprecated and no longer does anything. It used to convert errors in531 data generation into FailedHealthCheck error."""532 data_too_large = 1533 """Check for when the typical size of the examples you are generating534 exceeds the maximum allowed size too often."""535 filter_too_much = 2536 """Check for when the test is filtering out too many examples, either537 through use of :func:`~hypothesis.assume()` or :ref:`filter() <filtering>`,538 or occasionally for Hypothesis internal reasons."""539 too_slow = 3540 """Check for when your data generation is extremely slow and likely to hurt541 testing."""542 random_module = 4543 """Deprecated and no longer does anything. It used to check for whether544 your tests used the global random module. Now @given tests automatically545 seed random so this is no longer an error."""546 return_value = 5547 """Checks if your tests return a non-None value (which will be ignored and548 is unlikely to do what you want)."""549 hung_test = 6550 """Checks if your tests have been running for a very long time."""551 large_base_example = 7552 """Checks if the natural example to shrink towards is very large."""553 not_a_test_method = 8554 """Checks if @given has been applied to a method of unittest.TestCase."""555@unique556class Statistics(IntEnum):557 never = 0558 interesting = 1559 always = 2560@unique561class Verbosity(IntEnum):562 quiet = 0563 normal = 1564 verbose = 2565 debug = 3566 @staticmethod567 def _get_default():568 # type: () -> Verbosity569 var = os.getenv('HYPOTHESIS_VERBOSITY_LEVEL')570 if var is not None: # pragma: no cover571 try:572 result = Verbosity[var]573 except KeyError:574 raise InvalidArgument('No such verbosity level %r' % (var,))575 warnings.warn(HypothesisDeprecationWarning(576 'The HYPOTHESIS_VERBOSITY_LEVEL environment variable is '577 'deprecated, and will be ignored by a future version of '578 'Hypothesis. Configure your verbosity level via a '579 'settings profile instead.'580 ))581 return result582 return Verbosity.normal583 def __repr__(self):584 return 'Verbosity.%s' % (self.name,)585settings._define_setting(586 'verbosity',587 options=tuple(Verbosity),588 default=Verbosity._get_default(),589 description='Control the verbosity level of Hypothesis messages',590)591def _validate_phases(phases):592 if phases is None:593 return tuple(Phase)594 phases = tuple(phases)595 for a in phases:596 if not isinstance(a, Phase):597 raise InvalidArgument('%r is not a valid phase' % (a,))598 return phases599settings._define_setting(600 'phases',601 default=tuple(Phase),602 description=(603 'Control which phases should be run. ' +604 'See :ref:`the full documentation for more details <phases>`'605 ),606 validator=_validate_phases,607)608settings._define_setting(609 name='stateful_step_count',610 default=50,611 description="""612Number of steps to run a stateful program for before giving up on it breaking.613"""614)615settings._define_setting(616 'perform_health_check',617 default=not_set,618 description=u"""619If set to True, Hypothesis will run a preliminary health check before620attempting to actually execute your test.621""",622 deprecation_message="""623This setting is deprecated, as `perform_health_check=False` duplicates the624effect of `suppress_health_check=HealthCheck.all()`. Use that instead!625""",626)627def validate_health_check_suppressions(suppressions):628 suppressions = try_convert(list, suppressions, 'suppress_health_check')629 for s in suppressions:630 if not isinstance(s, HealthCheck):631 note_deprecation((632 'Non-HealthCheck value %r of type %s in suppress_health_check '633 'will be ignored, and will become an error in a future '634 'version of Hypothesis') % (635 s, type(s).__name__,636 ))637 elif s in (638 HealthCheck.exception_in_generation, HealthCheck.random_module639 ):640 note_deprecation((641 '%s is now ignored and suppressing it is a no-op. This will '642 'become an error in a future version of Hypothesis. Simply '643 'remove it from your list of suppressions to get the same '644 'effect.') % (s,))645 return suppressions646settings._define_setting(647 'suppress_health_check',648 default=(),649 description="""A list of health checks to disable.""",650 validator=validate_health_check_suppressions651)652settings._define_setting(653 'deadline',654 default=not_set,655 description=u"""656If set, a time in milliseconds (which may be a float to express657smaller units of time) that each individual example (i.e. each time your test658function is called, not the whole decorated test) within a test is not659allowed to exceed. Tests which take longer than that may be converted into660errors (but will not necessarily be if close to the deadline, to allow some661variability in test run time).662Set this to None to disable this behaviour entirely.663In future this will default to 200. For now, a664HypothesisDeprecationWarning will be emitted if you exceed that default665deadline and have not explicitly set a deadline yourself.666"""667)668settings._define_setting(669 'use_coverage',670 default=not_set,671 deprecation_message="""672use_coverage no longer does anything and can be removed from your settings.673""",674 description="""675A flag to enable a feature that no longer exists. This setting is present676only for backwards compatibility purposes.677"""678)679class PrintSettings(Enum):680 """Flags to determine whether or not to print a detailed example blob to681 use with :func:`~hypothesis.reproduce_failure` for failing test cases."""682 NEVER = 0683 """Never print a blob."""684 INFER = 1685 """Make an educated guess as to whether it would be appropriate to print686 the blob.687 The current rules are that this will print if:688 1. The output from Hypothesis appears to be unsuitable for use with689 :func:`~hypothesis.example`, and690 2. The output is not too long, and691 3. Verbosity is at least normal."""692 ALWAYS = 2693 """Always print a blob on failure."""694settings._define_setting(695 'print_blob',696 default=PrintSettings.INFER,697 description="""698Determines whether to print blobs after tests that can be used to reproduce699failures.700See :ref:`the documentation on @reproduce_failure <reproduce_failure>` for701more details of this behaviour.702"""703)704settings.lock_further_definitions()705def note_deprecation(message, s=None):706 # type: (str, settings) -> None707 if s is None:708 s = settings.default...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!