How to use populate_bundle method in hypothesis

Best Python code snippet using hypothesis

test_stateful.py

Source:test_stateful.py Github

copy

Full Screen

...261 @invariant()262 def bundle_length(self):263 assert len(self.bundle("b")) == self.expected_bundle_length264 @rule(target=b, items=lists(elements=integers(), max_size=10))265 def populate_bundle(self, items):266 self.expected_bundle_length += len(items)267 return multiple(*items)268 @rule(target=b)269 def do_not_populate(self):270 return multiple()271TestMachineUsingMultiple = MachineUsingMultiple.TestCase272def test_multiple_variables_printed():273 class ProducesMultiple(RuleBasedStateMachine):274 b = Bundle("b")275 @initialize(target=b)276 def populate_bundle(self):277 return multiple(1, 2)278 @rule()279 def fail_fast(self):280 assert False281 with capture_out() as o:282 # The state machine must raise an exception for the283 # falsifying example to be printed.284 with raises(AssertionError):285 run_state_machine_as_test(ProducesMultiple)286 # This is tightly coupled to the output format of the step printing.287 # The first line is "Falsifying Example:..." the second is creating288 # the state machine, the third is calling the "initialize" method.289 assignment_line = o.getvalue().split("\n")[2]290 # 'populate_bundle()' returns 2 values, so should be291 # expanded to 2 variables.292 assert assignment_line == "v1, v2 = state.populate_bundle()"293 # Make sure MultipleResult is iterable so the printed code is valid.294 # See https://github.com/HypothesisWorks/hypothesis/issues/2311295 state = ProducesMultiple()296 v1, v2 = state.populate_bundle()297 with raises(AssertionError):298 state.fail_fast()299def test_no_variables_printed():300 class ProducesNoVariables(RuleBasedStateMachine):301 b = Bundle("b")302 @initialize(target=b)303 def populate_bundle(self):304 return multiple()305 @rule()306 def fail_fast(self):307 assert False308 with capture_out() as o:309 # The state machine must raise an exception for the310 # falsifying example to be printed.311 with raises(AssertionError):312 run_state_machine_as_test(ProducesNoVariables)313 # This is tightly coupled to the output format of the step printing.314 # The first line is "Falsifying Example:..." the second is creating315 # the state machine, the third is calling the "initialize" method.316 assignment_line = o.getvalue().split("\n")[2]317 # 'populate_bundle()' returns 0 values, so there should be no318 # variable assignment.319 assert assignment_line == "state.populate_bundle()"320def test_consumes_typecheck():321 with pytest.raises(TypeError):322 consumes(integers())323def test_ratchetting_raises_flaky():324 with raises(Flaky):325 FlakyRatchettingMachine.TestCase().runTest()326def test_empty_machine_is_invalid():327 class EmptyMachine(RuleBasedStateMachine):328 pass329 with raises(InvalidDefinition):330 EmptyMachine.TestCase().runTest()331def test_machine_with_no_terminals_is_invalid():332 class NonTerminalMachine(RuleBasedStateMachine):333 @rule(value=Bundle("hi"))334 def bye(self, hi):335 pass336 with raises(InvalidDefinition):337 NonTerminalMachine.TestCase().runTest()338class DynamicMachine(RuleBasedStateMachine):339 @rule(value=Bundle("hi"))340 def test_stuff(x):341 pass342DynamicMachine.define_rule(targets=(), function=lambda self: 1, arguments={})343class IntAdder(RuleBasedStateMachine):344 pass345IntAdder.define_rule(346 targets=("ints",), function=lambda self, x: x, arguments={"x": integers()}347)348IntAdder.define_rule(349 targets=("ints",),350 function=lambda self, x, y: x,351 arguments={"x": integers(), "y": Bundle("ints")},352)353TestDynamicMachine = DynamicMachine.TestCase354TestIntAdder = IntAdder.TestCase355TestPrecondition = PreconditionMachine.TestCase356for test_case in (TestDynamicMachine, TestIntAdder, TestPrecondition):357 test_case.settings = Settings(test_case.settings, max_examples=10)358def test_picks_up_settings_at_first_use_of_testcase():359 assert TestDynamicMachine.settings.max_examples == 10360def test_new_rules_are_picked_up_before_and_after_rules_call():361 class Foo(RuleBasedStateMachine):362 pass363 Foo.define_rule(targets=(), function=lambda self: 1, arguments={})364 assert len(Foo.rules()) == 1365 Foo.define_rule(targets=(), function=lambda self: 2, arguments={})366 assert len(Foo.rules()) == 2367def test_minimizes_errors_in_teardown():368 counter = [0]369 class Foo(RuleBasedStateMachine):370 @initialize()371 def init(self):372 counter[0] = 0373 @rule()374 def increment(self):375 counter[0] += 1376 def teardown(self):377 assert not counter[0]378 with raises(AssertionError):379 run_state_machine_as_test(Foo)380 assert counter[0] == 1381class RequiresInit(RuleBasedStateMachine):382 def __init__(self, threshold):383 super().__init__()384 self.threshold = threshold385 @rule(value=integers())386 def action(self, value):387 if value > self.threshold:388 raise ValueError("%d is too high" % (value,))389def test_can_use_factory_for_tests():390 with raises(ValueError):391 run_state_machine_as_test(392 lambda: RequiresInit(42), settings=Settings(max_examples=100)393 )394class FailsEventually(RuleBasedStateMachine):395 def __init__(self):396 super().__init__()397 self.counter = 0398 @rule()399 def increment(self):400 self.counter += 1401 assert self.counter < 10402FailsEventually.TestCase.settings = Settings(stateful_step_count=5)403def test_can_explicitly_pass_settings():404 run_state_machine_as_test(FailsEventually)405 try:406 FailsEventually.TestCase.settings = Settings(407 FailsEventually.TestCase.settings, stateful_step_count=15408 )409 run_state_machine_as_test(410 FailsEventually, settings=Settings(stateful_step_count=2)411 )412 finally:413 FailsEventually.TestCase.settings = Settings(414 FailsEventually.TestCase.settings, stateful_step_count=5415 )416def test_settings_argument_is_validated():417 with pytest.raises(InvalidArgument):418 run_state_machine_as_test(FailsEventually, settings=object())419def test_runner_that_checks_factory_produced_a_machine():420 with pytest.raises(InvalidArgument):421 run_state_machine_as_test(object)422def test_settings_attribute_is_validated():423 real_settings = FailsEventually.TestCase.settings424 try:425 FailsEventually.TestCase.settings = object()426 with pytest.raises(InvalidArgument):427 run_state_machine_as_test(FailsEventually)428 finally:429 FailsEventually.TestCase.settings = real_settings430def test_saves_failing_example_in_database():431 db = ExampleDatabase(":memory:")432 with raises(AssertionError):433 run_state_machine_as_test(434 DepthMachine, settings=Settings(database=db, max_examples=100)435 )436 assert any(list(db.data.values()))437def test_can_run_with_no_db():438 with raises(AssertionError):439 run_state_machine_as_test(DepthMachine, settings=Settings(database=None))440def test_stateful_double_rule_is_forbidden(recwarn):441 with pytest.raises(InvalidDefinition):442 class DoubleRuleMachine(RuleBasedStateMachine):443 @rule(num=just(1))444 @rule(num=just(2))445 def whatevs(self, num):446 pass447def test_can_explicitly_call_functions_when_precondition_not_satisfied():448 class BadPrecondition(RuleBasedStateMachine):449 def __init__(self):450 super().__init__()451 @precondition(lambda self: False)452 @rule()453 def test_blah(self):454 raise ValueError()455 @rule()456 def test_foo(self):457 self.test_blah()458 with pytest.raises(ValueError):459 run_state_machine_as_test(BadPrecondition)460def test_invariant():461 """If an invariant raise an exception, the exception is propagated."""462 class Invariant(RuleBasedStateMachine):463 def __init__(self):464 super().__init__()465 @invariant()466 def test_blah(self):467 raise ValueError()468 @rule()469 def do_stuff(self):470 pass471 with pytest.raises(ValueError):472 run_state_machine_as_test(Invariant)473def test_no_double_invariant():474 """The invariant decorator can't be applied multiple times to a single475 function."""476 with raises(InvalidDefinition):477 class Invariant(RuleBasedStateMachine):478 def __init__(self):479 super().__init__()480 @invariant()481 @invariant()482 def test_blah(self):483 pass484 @rule()485 def do_stuff(self):486 pass487def test_invariant_precondition():488 """If an invariant precodition isn't met, the invariant isn't run.489 The precondition decorator can be applied in any order.490 """491 class Invariant(RuleBasedStateMachine):492 def __init__(self):493 super().__init__()494 @invariant()495 @precondition(lambda _: False)496 def an_invariant(self):497 raise ValueError()498 @precondition(lambda _: False)499 @invariant()500 def another_invariant(self):501 raise ValueError()502 @rule()503 def do_stuff(self):504 pass505 run_state_machine_as_test(Invariant)506def test_invalid_rule_argument():507 """Rule kwargs that are not a Strategy are expected to raise an InvalidArgument error."""508 with pytest.raises(InvalidArgument):509 class InvalidRuleMachine(RuleBasedStateMachine):510 @rule(strategy=object())511 def do_stuff(self):512 pass513def test_invalid_initialize_argument():514 """Initialize kwargs that are not a Strategy are expected to raise an InvalidArgument error."""515 with pytest.raises(InvalidArgument):516 class InvalidInitialize(RuleBasedStateMachine):517 @initialize(strategy=object())518 def initialize(self):519 pass520def test_multiple_invariants():521 """If multiple invariants are present, they all get run."""522 class Invariant(RuleBasedStateMachine):523 def __init__(self):524 super().__init__()525 self.first_invariant_ran = False526 @invariant()527 def invariant_1(self):528 self.first_invariant_ran = True529 @precondition(lambda self: self.first_invariant_ran)530 @invariant()531 def invariant_2(self):532 raise ValueError()533 @rule()534 def do_stuff(self):535 pass536 with pytest.raises(ValueError):537 run_state_machine_as_test(Invariant)538def test_explicit_invariant_call_with_precondition():539 """Invariants can be called explicitly even if their precondition is not540 satisfied."""541 class BadPrecondition(RuleBasedStateMachine):542 def __init__(self):543 super().__init__()544 @precondition(lambda self: False)545 @invariant()546 def test_blah(self):547 raise ValueError()548 @rule()549 def test_foo(self):550 self.test_blah()551 with pytest.raises(ValueError):552 run_state_machine_as_test(BadPrecondition)553def test_invariant_checks_initial_state():554 """Invariants are checked before any rules run."""555 class BadPrecondition(RuleBasedStateMachine):556 def __init__(self):557 super().__init__()558 self.num = 0559 @invariant()560 def test_blah(self):561 if self.num == 0:562 raise ValueError()563 @rule()564 def test_foo(self):565 self.num += 1566 with pytest.raises(ValueError):567 run_state_machine_as_test(BadPrecondition)568def test_always_runs_at_least_one_step():569 class CountSteps(RuleBasedStateMachine):570 def __init__(self):571 super().__init__()572 self.count = 0573 @rule()574 def do_something(self):575 self.count += 1576 def teardown(self):577 assert self.count > 0578 run_state_machine_as_test(CountSteps)579def test_removes_needless_steps():580 """Regression test from an example based on581 tests/nocover/test_database_agreement.py, but without the expensive bits.582 Comparing two database implementations in which deletion is broken, so as583 soon as a key/value pair is successfully deleted the test will now fail if584 you ever check that key.585 The main interesting feature of this is that it has a lot of586 opportunities to generate keys and values before it actually fails,587 but will still fail with very high probability.588 """589 @Settings(derandomize=True, max_examples=1000, deadline=None)590 class IncorrectDeletion(RuleBasedStateMachine):591 def __init__(self):592 super().__init__()593 self.__saved = defaultdict(set)594 self.__deleted = defaultdict(set)595 keys = Bundle("keys")596 values = Bundle("values")597 @rule(target=keys, k=binary())598 def k(self, k):599 return k600 @rule(target=values, v=binary())601 def v(self, v):602 return v603 @rule(k=keys, v=values)604 def save(self, k, v):605 self.__saved[k].add(v)606 @rule(k=keys, v=values)607 def delete(self, k, v):608 if v in self.__saved[k]:609 self.__deleted[k].add(v)610 @rule(k=keys)611 def values_agree(self, k):612 assert not self.__deleted[k]613 with capture_out() as o:614 with pytest.raises(AssertionError):615 run_state_machine_as_test(IncorrectDeletion)616 assert o.getvalue().count(" = state.k(") == 1617 assert o.getvalue().count(" = state.v(") == 1618def test_prints_equal_values_with_correct_variable_name():619 @Settings(max_examples=100)620 class MovesBetweenBundles(RuleBasedStateMachine):621 b1 = Bundle("b1")622 b2 = Bundle("b2")623 @rule(target=b1)624 def create(self):625 return []626 @rule(target=b2, source=b1)627 def transfer(self, source):628 return source629 @rule(source=b2)630 def fail(self, source):631 assert False632 with capture_out() as o:633 with pytest.raises(AssertionError):634 run_state_machine_as_test(MovesBetweenBundles)635 result = o.getvalue()636 for m in ["create", "transfer", "fail"]:637 assert result.count("state." + m) == 1638 assert "v1 = state.create()" in result639 assert "v2 = state.transfer(source=v1)" in result640 assert "state.fail(source=v2)" in result641def test_initialize_rule():642 @Settings(max_examples=1000)643 class WithInitializeRules(RuleBasedStateMachine):644 initialized = []645 @initialize()646 def initialize_a(self):647 self.initialized.append("a")648 @initialize()649 def initialize_b(self):650 self.initialized.append("b")651 @initialize()652 def initialize_c(self):653 self.initialized.append("c")654 @rule()655 def fail_fast(self):656 assert False657 with capture_out() as o:658 with pytest.raises(AssertionError):659 run_state_machine_as_test(WithInitializeRules)660 assert set(WithInitializeRules.initialized[-3:]) == {"a", "b", "c"}661 result = o.getvalue().splitlines()[1:]662 assert result[0] == "state = WithInitializeRules()"663 # Initialize rules call order is shuffled664 assert {result[1], result[2], result[3]} == {665 "state.initialize_a()",666 "state.initialize_b()",667 "state.initialize_c()",668 }669 assert result[4] == "state.fail_fast()"670 assert result[5] == "state.teardown()"671def test_initialize_rule_populate_bundle():672 class WithInitializeBundleRules(RuleBasedStateMachine):673 a = Bundle("a")674 @initialize(target=a, dep=just("dep"))675 def initialize_a(self, dep):676 return "a v1 with (%s)" % dep677 @rule(param=a)678 def fail_fast(self, param):679 assert False680 WithInitializeBundleRules.TestCase.settings = NO_BLOB_SETTINGS681 with capture_out() as o:682 with pytest.raises(AssertionError):683 run_state_machine_as_test(WithInitializeBundleRules)684 result = o.getvalue()685 assert (...

Full Screen

Full Screen

get_locale_item.py

Source:get_locale_item.py Github

copy

Full Screen

...129 return self130 def with_language(self, value: str) -> GetLocaleItem:131 self.language = value132 return self133 def with_populate_bundle(self, value: bool) -> GetLocaleItem:134 self.populate_bundle = value135 return self136 def with_region(self, value: str) -> GetLocaleItem:137 self.region = value138 return self139 def with_store_id(self, value: str) -> GetLocaleItem:140 self.store_id = value141 return self142 # endregion with_x methods143 # region to methods144 def to_dict(self, include_empty: bool = False) -> dict:145 result: dict = {}146 if hasattr(self, "item_id") and self.item_id:147 result["itemId"] = str(self.item_id)...

Full Screen

Full Screen

public_get_item.py

Source:public_get_item.py Github

copy

Full Screen

...121 return self122 def with_language(self, value: str) -> PublicGetItem:123 self.language = value124 return self125 def with_populate_bundle(self, value: bool) -> PublicGetItem:126 self.populate_bundle = value127 return self128 def with_region(self, value: str) -> PublicGetItem:129 self.region = value130 return self131 def with_store_id(self, value: str) -> PublicGetItem:132 self.store_id = value133 return self134 # endregion with_x methods135 # region to methods136 def to_dict(self, include_empty: bool = False) -> dict:137 result: dict = {}138 if hasattr(self, "item_id") and self.item_id:139 result["itemId"] = str(self.item_id)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful