Best Python code snippet using slash
sit_stand_target_test.py
Source:sit_stand_target_test.py
...3import pandas as pd4from mock import Mock5from libcbm.model.cbm.rule_based.sit import sit_stand_target6from libcbm.model.cbm.rule_based import rule_target7def get_test_function(mock_sit_event_row, mock_state_variables, mock_pools,8 mock_random_generator,9 mock_disturbance_production_func=None):10 mock_rule_target = Mock(spec=rule_target)11 mock_inventory = "inventory"12 mock_eligible = "eligible"13 create_target = sit_stand_target.create_sit_event_target_factory(14 rule_target=mock_rule_target,15 sit_event_row=mock_sit_event_row,16 disturbance_production_func=mock_disturbance_production_func,17 random_generator=mock_random_generator18 )19 mock_cbm_vars = SimpleNamespace(20 inventory=mock_inventory,21 pools=mock_pools,22 state=mock_state_variables)23 create_target(24 cbm_vars=mock_cbm_vars,25 eligible=mock_eligible)26 return mock_rule_target27class SITStandTargetTest(unittest.TestCase):28 """Tests for functions that compute CBM rule based disturbance event29 targets based on SIT disturbance event input.30 """31 def test_proportion_sort_proportion_target(self):32 get_test_function(33 mock_sit_event_row={34 "sort_type": "PROPORTION_OF_EVERY_RECORD",35 "target_type": "Proportion",36 "target": 0.8,37 "disturbance_type": "fire"},38 mock_state_variables="mock_state_vars",39 mock_pools="mock_pools",40 mock_random_generator=None41 ).proportion_sort_proportion_target.assert_called_once_with(42 proportion_target=0.8,43 inventory="inventory",44 eligible="eligible")45 def test_proportion_sort_area_target(self):46 get_test_function(47 mock_sit_event_row={48 "sort_type": "PROPORTION_OF_EVERY_RECORD",49 "target_type": "Area",50 "target": 13,51 "disturbance_type": "fire"},52 mock_state_variables="mock_state_vars",53 mock_pools="mock_pools",54 mock_random_generator=None55 ).proportion_area_target.assert_called_once_with(56 area_target_value=13,57 inventory="inventory",58 eligible="eligible",59 )60 def test_merch_total_sort_area_target(self):61 mock_production = SimpleNamespace(62 Total=[3, 3, 3, 3],63 DisturbanceSoftProduction=[1, 1, 1, 1],64 DisturbanceHardProduction=[1, 1, 1, 1],65 DisturbanceDOMProduction=[1, 1, 1, 1])66 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):67 self.assertTrue(disturbance_type_id == 2)68 self.assertTrue(cbm_vars.inventory == "inventory")69 self.assertTrue(cbm_vars.pools == "pools")70 return mock_production71 get_test_function(72 mock_sit_event_row={73 "sort_type": "MERCHCSORT_TOTAL",74 "target_type": "Area",75 "target": 18,76 "disturbance_type_id": 2},77 mock_state_variables="mock_state_vars",78 mock_pools="pools",79 mock_random_generator=None,80 mock_disturbance_production_func=mock_disturbance_production_func81 ).sorted_area_target.assert_called_once_with(82 area_target_value=18,83 sort_value=mock_production.Total,84 inventory="inventory",85 eligible="eligible",86 )87 def test_merch_sw_sort_area_target(self):88 mock_production = SimpleNamespace(89 Total=[3, 3, 3, 3],90 DisturbanceSoftProduction=[1, 1, 1, 1],91 DisturbanceHardProduction=[1, 1, 1, 1],92 DisturbanceDOMProduction=[1, 1, 1, 1])93 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):94 self.assertTrue(disturbance_type_id == 4000)95 self.assertTrue(cbm_vars.inventory == "inventory")96 self.assertTrue(cbm_vars.pools == "pools")97 return mock_production98 # tests that the + operator is used for the correct production fields99 expected_sort_value = \100 mock_production.DisturbanceSoftProduction + \101 mock_production.DisturbanceDOMProduction102 get_test_function(103 mock_sit_event_row={104 "sort_type": "MERCHCSORT_SW",105 "target_type": "Area",106 "target": 18,107 "disturbance_type_id": 4000},108 mock_state_variables="mock_state_vars",109 mock_pools="pools",110 mock_random_generator=None,111 mock_disturbance_production_func=mock_disturbance_production_func112 ).sorted_area_target.assert_called_once_with(113 area_target_value=18,114 sort_value=expected_sort_value,115 inventory="inventory",116 eligible="eligible",117 )118 def test_merch_hw_sort_area_target(self):119 mock_production = SimpleNamespace(120 Total=[3, 3, 3, 3],121 DisturbanceSoftProduction=[1, 1, 1, 1],122 DisturbanceHardProduction=[1, 1, 1, 1],123 DisturbanceDOMProduction=[1, 1, 1, 1])124 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):125 self.assertTrue(disturbance_type_id == 100)126 self.assertTrue(cbm_vars.inventory == "inventory")127 self.assertTrue(cbm_vars.pools == "pools")128 return mock_production129 # tests that the + operator is used for the correct production fields130 expected_sort_value = \131 mock_production.DisturbanceHardProduction + \132 mock_production.DisturbanceDOMProduction133 get_test_function(134 mock_sit_event_row={135 "sort_type": "MERCHCSORT_HW",136 "target_type": "Area",137 "target": 19,138 "disturbance_type_id": 100},139 mock_state_variables="mock_state_vars",140 mock_pools="pools",141 mock_random_generator=None,142 mock_disturbance_production_func=mock_disturbance_production_func143 ).sorted_area_target.assert_called_once_with(144 area_target_value=19,145 sort_value=expected_sort_value,146 inventory="inventory",147 eligible="eligible")148 def test_random_sort_area_target(self):149 mock_pools = pd.DataFrame({"a": [12, 3, 4, 5]})150 def mock_random_gen(n_values):151 return [1] * n_values152 get_test_function(153 mock_sit_event_row={154 "sort_type": "RANDOMSORT",155 "target_type": "Area",156 "target": 11,157 "disturbance_type": "fire"},158 mock_state_variables="mock_state_vars",159 mock_pools=mock_pools,160 mock_random_generator=mock_random_gen161 ).sorted_area_target.assert_called_once_with(162 area_target_value=11,163 sort_value=mock_random_gen(mock_pools.shape[0]),164 inventory="inventory",165 eligible="eligible"166 )167 def test_total_stem_snag_sort_area_target(self):168 get_test_function(169 mock_sit_event_row={170 "sort_type": "TOTALSTEMSNAG",171 "target_type": "Area",172 "target": 50,173 "disturbance_type": "fire"},174 mock_state_variables="mock_state_vars",175 mock_pools=SimpleNamespace(176 SoftwoodStemSnag=[1, 2, 3, 4],177 HardwoodStemSnag=[5, 6, 7, 8]),178 mock_random_generator=None179 ).sorted_area_target.assert_called_once_with(180 area_target_value=50,181 # since it's difficult for mock to test with182 # pd.DataSeries (simple equality won't work)183 # just check that the '+' operater was used.184 sort_value=[1, 2, 3, 4] + [5, 6, 7, 8],185 inventory="inventory",186 eligible="eligible"187 )188 def test_sw_stem_snag_sort_area_target(self):189 get_test_function(190 mock_sit_event_row={191 "sort_type": "SWSTEMSNAG",192 "target_type": "Area",193 "target": 1,194 "disturbance_type": "fire"},195 mock_state_variables="mock_state_vars",196 mock_pools=SimpleNamespace(SoftwoodStemSnag=[1, 2, 3, 4]),197 mock_random_generator=None198 ).sorted_area_target.assert_called_once_with(199 area_target_value=1,200 sort_value=[1, 2, 3, 4],201 inventory="inventory",202 eligible="eligible"203 )204 def test_hw_stem_snag_sort_area_target(self):205 get_test_function(206 mock_sit_event_row={207 "sort_type": "HWSTEMSNAG",208 "target_type": "Area",209 "target": 1,210 "disturbance_type": "fire"},211 mock_state_variables="mock_state_vars",212 mock_pools=SimpleNamespace(HardwoodStemSnag=[1, 2, 3, 4]),213 mock_random_generator=None214 ).sorted_area_target.assert_called_once_with(215 area_target_value=1,216 sort_value=[1, 2, 3, 4],217 inventory="inventory",218 eligible="eligible"219 )220 def test_swage_sort_area_target(self):221 """confirm state_variable.age is used as a sort value222 """223 get_test_function(224 mock_sit_event_row={225 "sort_type": "SORT_BY_SW_AGE",226 "target_type": "Area",227 "target": 100,228 "disturbance_type": "fire"},229 mock_state_variables=SimpleNamespace(age=[10, 2, 30]),230 mock_pools="pools",231 mock_random_generator=None232 ).sorted_area_target.assert_called_once_with(233 area_target_value=100,234 sort_value=[10, 2, 30],235 inventory="inventory",236 eligible="eligible"237 )238 def test_hwage_sort_area_target(self):239 """confirm state_variable.age is used as a sort value240 """241 get_test_function(242 mock_sit_event_row={243 "sort_type": "SORT_BY_HW_AGE",244 "target_type": "Area",245 "target": 100,246 "disturbance_type": "fire"},247 mock_state_variables=SimpleNamespace(age=[10, 2, 30]),248 mock_pools="pools",249 mock_random_generator=None250 ).sorted_area_target.assert_called_once_with(251 area_target_value=100,252 sort_value=[10, 2, 30],253 inventory="inventory",254 eligible="eligible"255 )256 def test_proportion_sort_merch_target(self):257 mock_production = SimpleNamespace(258 Total=[3, 3, 3, 3],259 DisturbanceSoftProduction=[1, 1, 1, 1],260 DisturbanceHardProduction=[1, 1, 1, 1],261 DisturbanceDOMProduction=[1, 1, 1, 1])262 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):263 self.assertTrue(disturbance_type_id == 90)264 self.assertTrue(cbm_vars.inventory == "inventory")265 self.assertTrue(cbm_vars.pools == "pools")266 return mock_production267 get_test_function(268 mock_sit_event_row={269 "sort_type": "PROPORTION_OF_EVERY_RECORD",270 "target_type": "Merchantable",271 "target": 17,272 "disturbance_type_id": 90,273 "efficiency": 55},274 mock_state_variables="mock_state_vars",275 mock_pools="pools",276 mock_random_generator=None,277 mock_disturbance_production_func=mock_disturbance_production_func278 ).proportion_merch_target.assert_called_once_with(279 carbon_target=17,280 disturbance_production=mock_production.Total,281 inventory="inventory",282 efficiency=55,283 eligible="eligible"284 )285 def test_merch_total_sort_merch_target(self):286 mock_production = SimpleNamespace(287 Total=[3, 3, 3, 3],288 DisturbanceSoftProduction=[1, 1, 1, 1],289 DisturbanceHardProduction=[1, 1, 1, 1],290 DisturbanceDOMProduction=[1, 1, 1, 1])291 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):292 self.assertTrue(disturbance_type_id == 99)293 self.assertTrue(cbm_vars.inventory == "inventory")294 self.assertTrue(cbm_vars.pools == "pools")295 return mock_production296 get_test_function(297 mock_sit_event_row={298 "sort_type": "MERCHCSORT_TOTAL",299 "target_type": "Merchantable",300 "target": 4,301 "disturbance_type_id": 99,302 "efficiency": 100},303 mock_state_variables="mock_state_vars",304 mock_pools="pools",305 mock_random_generator=None,306 mock_disturbance_production_func=mock_disturbance_production_func307 ).sorted_merch_target.assert_called_once_with(308 carbon_target=4,309 disturbance_production=mock_production,310 inventory="inventory",311 sort_value=mock_production.Total,312 efficiency=100,313 eligible="eligible"314 )315 def test_merch_sw_sort_merch_target(self):316 mock_production = SimpleNamespace(317 Total=[3, 3, 3, 3],318 DisturbanceSoftProduction=[1, 1, 1, 1],319 DisturbanceHardProduction=[1, 1, 1, 1],320 DisturbanceDOMProduction=[1, 1, 1, 1])321 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):322 self.assertTrue(disturbance_type_id == 45)323 self.assertTrue(cbm_vars.inventory == "inventory")324 self.assertTrue(cbm_vars.pools == "pools")325 return mock_production326 # tests that the + operator is used for the correct production fields327 expected_sort_value = \328 mock_production.DisturbanceSoftProduction + \329 mock_production.DisturbanceDOMProduction330 get_test_function(331 mock_sit_event_row={332 "sort_type": "MERCHCSORT_SW",333 "target_type": "Merchantable",334 "target": 23,335 "disturbance_type_id": 45,336 "efficiency": 0.1},337 mock_state_variables="mock_state_vars",338 mock_pools="pools",339 mock_random_generator=None,340 mock_disturbance_production_func=mock_disturbance_production_func341 ).sorted_merch_target.assert_called_once_with(342 carbon_target=23,343 disturbance_production=mock_production,344 inventory="inventory",345 sort_value=expected_sort_value,346 efficiency=0.1,347 eligible="eligible"348 )349 def test_merch_hw_sort_merch_target(self):350 mock_production = SimpleNamespace(351 Total=[3, 3, 3, 3],352 DisturbanceSoftProduction=[1, 1, 1, 1],353 DisturbanceHardProduction=[1, 1, 1, 1],354 DisturbanceDOMProduction=[1, 1, 1, 1])355 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):356 self.assertTrue(disturbance_type_id == 73)357 self.assertTrue(cbm_vars.inventory == "inventory")358 self.assertTrue(cbm_vars.pools == "pools")359 return mock_production360 # tests that the + operator is used for the correct production fields361 expected_sort_value = \362 mock_production.DisturbanceHardProduction + \363 mock_production.DisturbanceDOMProduction364 get_test_function(365 mock_sit_event_row={366 "sort_type": "MERCHCSORT_HW",367 "target_type": "Merchantable",368 "target": 31,369 "disturbance_type_id": 73,370 "efficiency": 0.99},371 mock_state_variables="mock_state_vars",372 mock_pools="pools",373 mock_random_generator=None,374 mock_disturbance_production_func=mock_disturbance_production_func375 ).sorted_merch_target.assert_called_once_with(376 carbon_target=31,377 disturbance_production=mock_production,378 inventory="inventory",379 sort_value=expected_sort_value,380 efficiency=0.99,381 eligible="eligible"382 )383 def test_random_sort_merch_target(self):384 mock_pools = pd.DataFrame({"a": [12, 3, 4, 5]})385 def mock_random_gen(n_values):386 return [1] * n_values387 mock_production = SimpleNamespace(388 Total=[3, 3, 3, 3],389 DisturbanceSoftProduction=[1, 1, 1, 1],390 DisturbanceHardProduction=[1, 1, 1, 1],391 DisturbanceDOMProduction=[1, 1, 1, 1])392 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):393 self.assertTrue(disturbance_type_id == 43)394 self.assertTrue(cbm_vars.inventory == "inventory")395 self.assertTrue(list(cbm_vars.pools.a) == [12, 3, 4, 5])396 return mock_production397 get_test_function(398 mock_sit_event_row={399 "sort_type": "RANDOMSORT",400 "target_type": "Merchantable",401 "target": 31,402 "disturbance_type_id": 43,403 "efficiency": 0.99},404 mock_state_variables="mock_state_vars",405 mock_pools=mock_pools,406 mock_random_generator=mock_random_gen,407 mock_disturbance_production_func=mock_disturbance_production_func408 ).sorted_merch_target.assert_called_once_with(409 carbon_target=31,410 disturbance_production=mock_production,411 inventory="inventory",412 sort_value=mock_random_gen(mock_pools.shape[0]),413 efficiency=0.99,414 eligible="eligible"415 )416 def test_total_stem_snag_sort_merch_target(self):417 mock_production = SimpleNamespace(418 Total=[3, 3, 3, 3])419 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):420 self.assertTrue(disturbance_type_id == 15)421 self.assertTrue(cbm_vars.inventory == "inventory")422 self.assertTrue(cbm_vars.pools.SoftwoodStemSnag == [1, 2, 3])423 self.assertTrue(cbm_vars.pools.HardwoodStemSnag == [1, 2, 3])424 return mock_production425 mock_pools = SimpleNamespace(426 SoftwoodStemSnag=[1, 2, 3],427 HardwoodStemSnag=[1, 2, 3])428 get_test_function(429 mock_sit_event_row={430 "sort_type": "TOTALSTEMSNAG",431 "target_type": "Merchantable",432 "target": 37,433 "disturbance_type_id": 15,434 "efficiency": 1.0},435 mock_state_variables="mock_state_vars",436 mock_pools=mock_pools,437 mock_random_generator=None,438 mock_disturbance_production_func=mock_disturbance_production_func439 ).sorted_merch_target.assert_called_once_with(440 carbon_target=37,441 disturbance_production=mock_production,442 inventory="inventory",443 # simply confirm the '+' operator is used on the correct pools444 sort_value=(445 mock_pools.SoftwoodStemSnag +446 mock_pools.HardwoodStemSnag),447 efficiency=1.0,448 eligible="eligible"449 )450 def test_sw_stem_snag_sort_merch_target(self):451 mock_production = SimpleNamespace(452 Total=[3, 3, 3, 3])453 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):454 self.assertTrue(disturbance_type_id == 57)455 self.assertTrue(cbm_vars.inventory == "inventory")456 self.assertTrue(cbm_vars.pools.SoftwoodStemSnag == [1, 2, 3])457 return mock_production458 mock_pools = SimpleNamespace(459 SoftwoodStemSnag=[1, 2, 3])460 get_test_function(461 mock_sit_event_row={462 "sort_type": "SWSTEMSNAG",463 "target_type": "Merchantable",464 "target": 47,465 "disturbance_type_id": 57,466 "efficiency": 1.1},467 mock_state_variables="mock_state_vars",468 mock_pools=mock_pools,469 mock_random_generator=None,470 mock_disturbance_production_func=mock_disturbance_production_func471 ).sorted_merch_target.assert_called_once_with(472 carbon_target=47,473 disturbance_production=mock_production,474 inventory="inventory",475 sort_value=mock_pools.SoftwoodStemSnag,476 efficiency=1.1,477 eligible="eligible"478 )479 def test_hw_stem_snag_sort_merch_target(self):480 mock_production = SimpleNamespace(481 Total=[3, 3, 3, 3])482 def mock_disturbance_production_func(cbm_vars, disturbance_type_id):483 self.assertTrue(disturbance_type_id == 9)484 self.assertTrue(cbm_vars.inventory == "inventory")485 self.assertTrue(cbm_vars.pools.HardwoodStemSnag == [1, 2, 3])486 return mock_production487 mock_pools = SimpleNamespace(488 HardwoodStemSnag=[1, 2, 3])489 get_test_function(490 mock_sit_event_row={491 "sort_type": "HWSTEMSNAG",492 "target_type": "Merchantable",493 "target": 97,494 "disturbance_type_id": 9,495 "efficiency": 2.1},496 mock_state_variables="mock_state_vars",497 mock_pools=mock_pools,498 mock_random_generator=None,499 mock_disturbance_production_func=mock_disturbance_production_func500 ).sorted_merch_target.assert_called_once_with(501 carbon_target=97,502 disturbance_production=mock_production,503 inventory="inventory",504 sort_value=mock_pools.HardwoodStemSnag,505 efficiency=2.1,506 eligible="eligible"507 )508 def test_age_sort_area_target(self):509 get_test_function(510 mock_sit_event_row={511 "sort_type": "SORT_BY_HW_AGE",512 "target_type": "Area",513 "target": 100},514 mock_state_variables=SimpleNamespace(age=[10, 2, 30]),515 mock_pools="pools",516 mock_random_generator=None517 ).sorted_area_target.assert_called_once_with(518 area_target_value=100,519 sort_value=[10, 2, 30],520 inventory="inventory",521 eligible="eligible"522 )523 def test_svoid_sort_proportion_target(self):524 get_test_function(525 mock_sit_event_row={526 "sort_type": "SVOID",527 "target_type": "Proportion",528 "target": 100,529 "spatial_reference": 1000},530 mock_state_variables="inventory",531 mock_pools="pools",532 mock_random_generator=None533 ).spatially_indexed_target.assert_called_once_with(534 identifier=1000,535 inventory="inventory"536 )537 def test_svoid_sort_merch_target(self):538 get_test_function(539 mock_sit_event_row={540 "sort_type": "SVOID",541 "target_type": "Merchantable",542 "target": 10,543 "spatial_reference": 4000},544 mock_state_variables="inventory",545 mock_pools="pools",546 mock_random_generator=None547 ).spatially_indexed_target.assert_called_once_with(548 identifier=4000,549 inventory="inventory"550 )551 def test_svoid_sort_area_target(self):552 get_test_function(553 mock_sit_event_row={554 "sort_type": "SVOID",555 "target_type": "Area",556 "target": 130,557 "spatial_reference": 1050},558 mock_state_variables="inventory",559 mock_pools="pools",560 mock_random_generator=None561 ).spatially_indexed_target.assert_called_once_with(562 identifier=1050,563 inventory="inventory"...
test_ghostwriter.py
Source:test_ghostwriter.py
...25from hypothesis.errors import InvalidArgument, MultipleFailures, Unsatisfiable26from hypothesis.extra import ghostwriter27from hypothesis.strategies import from_type, just28varied_excepts = pytest.mark.parametrize("ex", [(), ValueError, (TypeError, re.error)])29def get_test_function(source_code):30 # A helper function to get the dynamically-defined test function.31 # Note that this also tests that the module is syntatically-valid,32 # AND free from undefined names, import problems, and so on.33 namespace = {}34 exec(source_code, namespace)35 tests = [36 v37 for k, v in namespace.items()38 if k.startswith(("test_", "Test")) and not isinstance(v, ModuleType)39 ]40 assert len(tests) == 1, tests41 return tests[0]42@pytest.mark.parametrize(43 "badness", ["not an exception", BaseException, [ValueError], (Exception, "bad")]44)45def test_invalid_exceptions(badness):46 with pytest.raises(InvalidArgument):47 ghostwriter._check_except(badness)48def test_style_validation():49 ghostwriter._check_style("pytest")50 ghostwriter._check_style("unittest")51 with pytest.raises(InvalidArgument):52 ghostwriter._check_style("not a valid style")53def test_strategies_with_invalid_syntax_repr_as_nothing():54 msg = "$$ this repr is not Python syntax $$"55 class NoRepr:56 def __repr__(self):57 return msg58 s = just(NoRepr())59 assert repr(s) == f"just({msg})"60 assert ghostwriter._valid_syntax_repr(s) == "nothing()"61class AnEnum(enum.Enum):62 a = "value of AnEnum.a"63 b = "value of AnEnum.b"64def takes_enum(foo=AnEnum.a):65 # This can only fail if we use the default argument to guess66 # that any instance of that enum type should be allowed.67 assert foo != AnEnum.b68def test_ghostwriter_exploits_arguments_with_enum_defaults():69 source_code = ghostwriter.fuzz(takes_enum)70 test = get_test_function(source_code)71 with pytest.raises(AssertionError):72 test()73def timsort(seq: Sequence[int]) -> List[int]:74 return sorted(seq)75def non_type_annotation(x: 3): # type: ignore76 pass77def annotated_any(x: Any):78 pass79space_in_name = type("a name", (type,), {"__init__": lambda self: None})80class NotResolvable:81 def __init__(self, unannotated_required):82 pass83def non_resolvable_arg(x: NotResolvable):84 pass85def test_flattens_one_of_repr():86 strat = from_type(Union[int, Sequence[int]])87 assert repr(strat).count("one_of(") > 188 assert ghostwriter._valid_syntax_repr(strat).count("one_of(") == 189@varied_excepts90@pytest.mark.parametrize(91 "func",92 [93 re.compile,94 json.loads,95 json.dump,96 timsort,97 ast.literal_eval,98 non_type_annotation,99 annotated_any,100 space_in_name,101 non_resolvable_arg,102 ],103)104def test_ghostwriter_fuzz(func, ex):105 source_code = ghostwriter.fuzz(func, except_=ex)106 get_test_function(source_code)107@varied_excepts108@pytest.mark.parametrize(109 "func", [re.compile, json.loads, json.dump, timsort, ast.literal_eval]110)111def test_ghostwriter_unittest_style(func, ex):112 source_code = ghostwriter.fuzz(func, except_=ex, style="unittest")113 assert issubclass(get_test_function(source_code), unittest.TestCase)114def no_annotations(foo=None, bar=False):115 pass116def test_inference_from_defaults_and_none_booleans_reprs_not_just_and_sampled_from():117 source_code = ghostwriter.fuzz(no_annotations)118 assert "@given(foo=st.none(), bar=st.booleans())" in source_code119def hopefully_hashable(foo: Set[Decimal]):120 pass121def test_no_hashability_filter():122 # In from_type, we ordinarily protect users from really weird cases like123 # `Decimal('snan')` - a unhashable value of a hashable type - but in the124 # ghostwriter we instead want to present this to the user for an explicit125 # decision. They can pass `allow_nan=False`, fix their custom type's126 # hashing logic, or whatever else; simply doing nothing will usually work.127 source_code = ghostwriter.fuzz(hopefully_hashable)128 assert "@given(foo=st.sets(st.decimals()))" in source_code129 assert "_can_hash" not in source_code130@pytest.mark.parametrize(131 "gw,args",132 [133 (ghostwriter.fuzz, ["not callable"]),134 (ghostwriter.idempotent, ["not callable"]),135 (ghostwriter.roundtrip, []),136 (ghostwriter.roundtrip, ["not callable"]),137 (ghostwriter.equivalent, [sorted]),138 (ghostwriter.equivalent, [sorted, "not callable"]),139 ],140)141def test_invalid_func_inputs(gw, args):142 with pytest.raises(InvalidArgument):143 gw(*args)144def test_run_ghostwriter_fuzz():145 # Our strategy-guessing code works for all the arguments to sorted,146 # and we handle positional-only arguments in calls correctly too.147 source_code = ghostwriter.fuzz(sorted)148 assert "st.nothing()" not in source_code149 get_test_function(source_code)()150class MyError(UnicodeDecodeError):151 pass152@pytest.mark.parametrize(153 "exceptions,output",154 [155 # Discard subclasses of other exceptions to catch, including non-builtins,156 # and replace OSError aliases with OSError.157 ((Exception, UnicodeError), "Exception"),158 ((UnicodeError, MyError), "UnicodeError"),159 ((IOError,), "OSError"),160 ((IOError, UnicodeError), "(OSError, UnicodeError)"),161 ],162)163def test_exception_deduplication(exceptions, output):164 _, body = ghostwriter._make_test_body(165 lambda: None, ghost="", test_body="pass", except_=exceptions, style="pytest"166 )167 assert f"except {output}:" in body168def test_run_ghostwriter_roundtrip():169 # This test covers the whole lifecycle: first, we get the default code.170 # The first argument is unknown, so we fail to draw from st.nothing()171 source_code = ghostwriter.roundtrip(json.dumps, json.loads)172 with pytest.raises(Unsatisfiable):173 get_test_function(source_code)()174 # Replacing that nothing() with a strategy for JSON allows us to discover175 # two possible failures: `nan` is not equal to itself, and if dumps is176 # passed allow_nan=False it is a ValueError to pass a non-finite float.177 source_code = source_code.replace(178 "st.nothing()",179 "st.recursive(st.one_of(st.none(), st.booleans(), st.floats(), st.text()), "180 "lambda v: st.lists(v, max_size=2) | st.dictionaries(st.text(), v, max_size=2)"181 ", max_leaves=2)",182 )183 try:184 get_test_function(source_code)()185 except (AssertionError, ValueError, MultipleFailures):186 pass187 # Finally, restricting ourselves to finite floats makes the test pass!188 source_code = source_code.replace(189 "st.floats()", "st.floats(allow_nan=False, allow_infinity=False)"190 )191 get_test_function(source_code)()192@varied_excepts193@pytest.mark.parametrize("func", [sorted, timsort])194def test_ghostwriter_idempotent(func, ex):195 source_code = ghostwriter.idempotent(func, except_=ex)196 test = get_test_function(source_code)197 if "=st.nothing()" in source_code:198 with pytest.raises(Unsatisfiable):199 test()200 else:201 test()202def test_overlapping_args_use_union_of_strategies():203 def f(arg: int) -> None:204 pass205 def g(arg: float) -> None:206 pass207 source_code = ghostwriter.equivalent(f, g)208 assert "arg=st.one_of(st.integers(), st.floats())" in source_code209def test_module_with_mock_does_not_break():210 # Before we added an explicit check for unspec'd mocks, they would pass...
test.py
Source:test.py
...53 """54 def __init__(self, test_method_name, fixture_store, fixture_namespace, variation):55 super(Test, self).__init__(fixture_store, fixture_namespace, variation)56 self._test_method_name = test_method_name57 def get_test_function(self):58 return getattr(self, self._test_method_name)59 def get_tags(self):60 test_tags = (get_tags(type(self))61 + get_tags(getattr(type(self), self._test_method_name))62 + self.get_variation().tags)63 if nofixtures.is_marked(self.get_test_function()):64 return test_tags65 return test_tags + self._get_fixture_tags()66 __slash_skipped__ = False67 __slash_skipped_reason__ = None68 __slash_needed_contexts__ = None69 @classmethod70 def skip_all(cls, reason=None):71 cls.__slash_skipped__ = True72 cls.__slash_skipped_reason__ = reason73 def get_required_fixture_objects(self):74 method = self.get_test_function()75 return self._fixture_store.get_required_fixture_objects(method, namespace=self._fixture_namespace)76 def get_address_in_factory(self):77 returned = ''78 if self._test_method_name is not None:79 returned += ".{}".format(self._test_method_name)80 return returned81 def _get_call_string(self, kwargs):82 if not kwargs:83 return ""84 return "({})".format(", ".join("{}={!r}".format(k, v) for k, v in kwargs.items()))85 def get_requirements(self):86 test_requirements = get_requirements(type(self)) + get_requirements(self.get_test_function())87 if nofixtures.is_marked(self.get_test_function()):88 return test_requirements89 return list(set(test_requirements + self._get_fixtures_requirements()))90 def run(self): # pylint: disable=E020291 """92 .. warning:: Not to be overriden93 """94 method = self.get_test_function()95 with bound_parametrizations_context(self._variation, self._fixture_store, self._fixture_namespace):96 _call_with_fixtures = functools.partial(self._fixture_store.call_with_fixtures, namespace=self._fixture_namespace)97 _call_with_fixtures(self.before)98 try:99 with handling_exceptions():100 result = _call_with_fixtures(method, trigger_test_start=True)101 if isinstance(result, GeneratorType):102 raise InvalidTest('{} is a generator. Running generators is not supported'.format(method))103 finally:104 with handling_exceptions():105 _call_with_fixtures(self.after, trigger_test_end=True)106 def before(self):107 """108 Gets called before each separate case generated from this test class...
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!!