Best Python code snippet using hypothesis
test_LivePlot.py
Source:test_LivePlot.py
...27 lambda x: len(set(x)) != len(x)28 )29 ),30 dict(31 metrics=cst.everything_except((str, Sequence))32 | st.lists(cst.everything_except(str))33 ),34 dict(35 nrows=cst.everything_except((Integral, type(None)))36 | st.integers(max_value=0)37 ),38 dict(39 ncols=cst.everything_except((Integral, type(None)))40 | st.integers(max_value=0)41 ),42 dict(43 max_fraction_spent_plotting=cst.everything_except((float, int))44 | st.floats().filter(lambda x: not 0 <= x <= 1)45 ),46 dict(47 last_n_batches=cst.everything_except((int, type(None)))48 | st.integers(max_value=0)49 ),50 ],51)52@given(data=st.data())53def test_input_validation(bad_input: dict, data: st.DataObject):54 defaults = dict(metrics=["a"])55 defaults.update(56 {k: cst.draw_if_strategy(data, v, label=k) for k, v in bad_input.items()}57 )58 with pytest.raises((ValueError, TypeError)):59 LivePlot(**defaults)60@pytest.mark.parametrize(61 ("num_metrics", "fig_layout", "outer_type", "shape"),62 [63 (1, dict(), Axes, tuple()),64 (1, dict(nrows=1), Axes, tuple()),65 (1, dict(ncols=1), Axes, tuple()),66 (3, dict(nrows=2, ncols=2), ndarray, (2, 2)),67 (3, dict(), ndarray, (3,)),68 (3, dict(nrows=3), ndarray, (3,)),69 (3, dict(ncols=3), ndarray, (3,)),70 ],71)72@pytest.mark.usefixtures("killplots")73def test_plot_grid(num_metrics, fig_layout, outer_type, shape):74 """Ensure that axes have the right type/shape for a given grid spec"""75 metric_names = list(ascii_letters[:num_metrics])76 fig, ax = LivePlot(metric_names, **fig_layout).plot_objects77 assert isinstance(fig, Figure)78 assert isinstance(ax, outer_type)79 if shape:80 assert ax.shape == shape81@pytest.mark.usefixtures("killplots")82def test_adaptive_plot_grid():83 plotter = LivePlot(list(ascii_letters[:5]), ncols=2)84 assert plotter._pltkwargs["nrows"] == 385 assert plotter._pltkwargs["ncols"] == 286@pytest.mark.usefixtures("killplots")87@given(88 num_metrics=st.integers(1, 12), nrows=st.integers(1, 12), ncols=st.integers(1, 12)89)90def test_fuzz_plot_grid(num_metrics: int, nrows: int, ncols: int):91 plotter = LivePlot(list(ascii_letters[:num_metrics]), nrows=nrows, ncols=ncols)92 assert plotter._pltkwargs["nrows"] * plotter._pltkwargs["ncols"] >= num_metrics93def test_unregister_metric_warns():94 plotter = LivePlot(metrics=["a"])95 with pytest.warns(UserWarning):96 plotter.set_train_batch(dict(a=1, b=1), batch_size=1)97 with pytest.warns(UserWarning):98 plotter.set_test_batch(dict(a=1, c=1), batch_size=1)99def test_trivial_case():100 """ Perform a trivial sanity check on live plotter"""101 plotter = LivePlot("a")102 plotter.set_train_batch(dict(a=1.0), batch_size=1, plot=False)103 plotter.set_train_batch(dict(a=3.0), batch_size=1, plot=False)104 plotter.set_train_epoch()105 assert_array_equal(plotter.train_metrics["a"]["batch_data"], np.array([1.0, 3.0]))106 assert_array_equal(plotter.train_metrics["a"]["epoch_domain"], np.array([2]))107 assert_array_equal(108 plotter.train_metrics["a"]["epoch_data"], np.array([1.0 / 2.0 + 3.0 / 2.0])109 )110@given(111 plotter=cst.plotters(),112 bad_size=(113 cst.everything_except(Sequence)114 | st.tuples(*[cst.everything_except(Real)] * 2)115 | st.lists(st.floats(max_value=10)).filter(116 lambda x: len(x) != 2 or any(i <= 0 for i in x)117 )118 ),119)120def test_bad_figsize(plotter: LivePlot, bad_size):121 with pytest.raises(ValueError):122 plotter.figsize = bad_size123@given(colors=st.lists(cst.matplotlib_colors(), min_size=1, max_size=4))124def test_flat_color_syntax(colors: list):125 metric_names = ascii_letters[: len(colors)]126 p = LivePlot({n: c for n, c in zip(metric_names, colors)})127 assert p.metric_colors == {n: dict(train=c) for n, c in zip(metric_names, colors)}128@settings(deadline=None)129@given(plotter=cst.plotters(), data=st.data())130def test_setting_color_for_non_metric_is_silent(plotter: LivePlot, data: st.DataObject):131 color = {132 data.draw(st.text(), label="non_metric"): data.draw(133 cst.matplotlib_colors(), label="color"134 )135 }136 original_colors = plotter.metric_colors137 plotter.metric_colors = color138 assert plotter.metric_colors == original_colors139@settings(deadline=None)140@given(plotter=cst.plotters(), bad_colors=cst.everything_except(dict))141def test_color_setter_validation(plotter: LivePlot, bad_colors):142 with pytest.raises(TypeError):143 plotter.metric_colors = bad_colors144@settings(deadline=None)145@given(146 plotter=cst.plotters(),147 colors=st.fixed_dictionaries(148 {"train": cst.matplotlib_colors(), "test": cst.matplotlib_colors()}149 ),150 data=st.data(),151)152def test_set_color(plotter: LivePlot, colors: dict, data: st.DataObject):153 metric = data.draw(st.sampled_from(plotter.metrics), label="metric")154 plotter.metric_colors = {metric: colors}...
test_LiveMetric.py
Source:test_LiveMetric.py
...36 getattr(metric, name),37 err_msg=name + " does not map to the correct value in the metric-dict",38 )39@pytest.mark.parametrize(40 "bad_input", [cst.everything_except(dict), st.just(dict(a_bad_key=1))]41)42@settings(suppress_health_check=[HealthCheck.too_slow])43@given(data=st.data())44def test_from_dict_input_validation(bad_input: st.SearchStrategy, data: st.DataObject):45 bad_input = data.draw(bad_input, label="bad_input")46 with pytest.raises((ValueError, TypeError)):47 LiveMetric.from_dict(bad_input)48static_logger_dict = cst.live_metrics(min_num_metrics=1).example() # type: dict49@pytest.mark.parametrize(50 "bad_input",51 [52 dict(batch_data=np.arange(9).reshape(3, 3)),53 dict(epoch_data=np.arange(9).reshape(3, 3)),54 dict(cnt_since_epoch=-1),55 dict(epoch_domain=np.arange(9).reshape(3, 3)),56 dict(batch_data=cst.everything_except(np.ndarray)),57 dict(epoch_data=cst.everything_except(np.ndarray)),58 dict(epoch_domain=cst.everything_except(np.ndarray)),59 dict(cnt_since_epoch=cst.everything_except(Real)),60 dict(total_weighting=cst.everything_except(Real)),61 dict(running_weighted_sum=cst.everything_except(Real)),62 dict(name=cst.everything_except(str)),63 ],64)65@settings(suppress_health_check=[HealthCheck.too_slow])66@given(data=st.data())67def test_from_dict_input_validation2(bad_input: dict, data: st.DataObject):68 input_dict = {}69 bad_input = {70 k: data.draw(v, label=k) if isinstance(v, st.SearchStrategy) else v71 for k, v in bad_input.items()72 }73 for name, metrics in static_logger_dict.items():74 input_dict = metrics.copy()75 input_dict.update(bad_input)76 break...
test_field.py
Source:test_field.py
...10 actual = Field.empty(name=name)11 _, ok = actual.default12 assert actual.name == name13 assert ok == False14@given(everything_except(str, type(None)))15@settings(max_examples=settings().max_examples * 50)16def test_empty_failure(name):17 with pytest.raises(ValueError):18 actual = Field.empty(name=name)19@given(20 st.text(printable),21 everything_except(type(None)),22 st.functions(like=(lambda: None), returns=everything_except()),23)24@settings(max_examples=settings().max_examples * 25)25def test_bad_defaults(name, default, factory):26 with pytest.raises(ValueError):...
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!!