How to use test_yaml method in avocado

Best Python code snippet using avocado_python

test_structure_parse.py

Source:test_structure_parse.py Github

copy

Full Screen

1#!/usr/bin/env python32import unittest3from pathlib import Path4import numpy as np5import yaml6from icecream import ic7from numpy.testing import assert_allclose8import figure_comp.coordinate_tracking as ct9import figure_comp.structure_comp as sc10import figure_comp.structure_parse as sp11from figure_comp.load_image import Label12from figure_comp.tests.test_coordinate_tracking import get_coords13project_dir = Path(__file__).resolve().parent14test_im_dir = project_dir / "test_im/"15paths = [16 test_im_dir / "square-im-1.png",17 test_im_dir / "square-im-2.png",18 test_im_dir / "square-im-3.png",19 test_im_dir / "square-im-4.png",20 test_im_dir / "square-im-5.png",21 test_im_dir / "rect-im-1.png",22 test_im_dir / "rect-im-2.png",23 test_im_dir / "rect-im-3.png",24]25im_paths = [Path(p) for p in paths]26class TestYamlParsing(unittest.TestCase):27 def test_manual_simple_parse(self):28 """ Experiment with a simple yaml structure. """29 test_yaml = """30 - Row:31 - /path/one32 - /path/two33 - options:34 max_size: 2035 new_size: 4536 """37 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)[0]38 self.assertTrue("Row" in test_config)39 # Any strings are presumed to be file paths40 row_info = test_config["Row"]41 paths_test = [r for r in row_info if isinstance(r, str)]42 paths_expected = ["/path/one", "/path/two"]43 self.assertEqual(paths_test, paths_expected)44 # Now read the options45 for row in row_info:46 if not isinstance(row, str) and "options" in row:47 options_test = row["options"]48 break49 else:50 raise AssertionError("Unable to read options from test yaml")51 options_expected = dict(max_size=20, new_size=45)52 self.assertEqual(options_test, options_expected)53 def test_simple_parse(self):54 """ Experiment with a simple yaml structure. """55 test_yaml = """56 - Row:57 - /path/one58 - /path/two59 """60 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)61 figure_test = sp.parse_yaml(test_config, dry=True)62 leaf_expected = (63 "Row",64 [ct.Pos("/path/one"), ct.Pos("/path/two")],65 )66 self.assertEqual(figure_test, leaf_expected)67 def test_nested_parse(self):68 """ A structure with a column within a row. """69 test_yaml = """70 - Row:71 - /path/one72 - /path/two73 - Col:74 - /path/three75 - /path/four76 """77 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)78 figure_test = sp.parse_yaml(test_config, dry=True)79 nested_leaf = ("Col", [ct.Pos("/path/three"), ct.Pos("/path/four")])80 leaf_expected = (81 "Row",82 [ct.Pos("/path/one"), ct.Pos("/path/two"), nested_leaf],83 )84 self.assertEqual(figure_test, leaf_expected)85 def test_nested_double_parse(self):86 """ A structure with two columns within a row. """87 test_yaml = """88 - Row:89 - Col:90 - /path/one91 - /path/two92 - /path/five93 - Col:94 - /path/three95 - /path/four96 """97 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)98 figure_test = sp.parse_yaml(test_config, dry=True)99 first_col = ("Col", [ct.Pos("/path/one"), ct.Pos("/path/two")])100 second_col = ("Col", [ct.Pos("/path/three"), ct.Pos("/path/four")])101 leaf_expected = (102 "Row",103 [first_col, ct.Pos("/path/five"), second_col],104 )105 self.assertEqual(figure_test, leaf_expected)106class TestAssembleStruct(unittest.TestCase):107 def test_simple_parse(self):108 """ Assemble an image from a simple structure. """109 im_one = Path("tests/test_im/square-im-1.png").resolve()110 im_two = Path("tests/test_im/square-im-2.png").resolve()111 test_yaml = f"""112 - Row:113 - {im_one}114 - {im_two}115 """116 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)117 pos_test = sp.parse_yaml(test_config)118 pos_expected = [ct.Pos(path=p.resolve()) for p in [im_one, im_two]]119 # Test outer layer120 self.assertTrue(isinstance(pos_test, sc.Row))121 # Test that arrays are the same122 for im_test, im_expected in zip(pos_test.cont, pos_expected):123 self.assertEqual(im_test, im_expected)124 self.assertEqual(len(pos_test.cont), len(pos_expected))125 def test_nested_parse(self):126 """ Assemble an image from a nested structure. """127 paths = [128 "tests/test_im/square-im-1.png",129 "tests/test_im/square-im-2.png",130 "tests/test_im/square-im-3.png",131 "tests/test_im/square-im-4.png",132 ]133 im_paths = [Path(p).resolve() for p in paths]134 test_yaml = f"""135 - Row:136 - {im_paths[0]}137 - {im_paths[1]}138 - Col:139 - {im_paths[2]}140 - {im_paths[3]}141 """142 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)143 figure_test = sp.parse_yaml(test_config, dry=True)144 ims = [ct.Pos(path=p.resolve()) for p in im_paths]145 # Test outer layer146 header_test = figure_test[0]147 header_expected = "Row"148 self.assertEqual(header_test, header_expected)149 body = figure_test[1]150 self.assertEqual(body[0], ims[0])151 self.assertEqual(body[1], ims[1])152 inner_col = body[2][1]153 self.assertEqual(inner_col[0], ims[2])154 self.assertEqual(inner_col[1], ims[3])155 def test_nested_double_parse(self):156 """ Assemble a structure with two columns within a row. """157 paths = [158 "tests/test_im/square-im-1.png",159 "tests/test_im/square-im-2.png",160 "tests/test_im/square-im-3.png",161 "tests/test_im/square-im-4.png",162 "tests/test_im/square-im-5.png",163 ]164 im_paths = [Path(p).resolve() for p in paths]165 ims = [ct.Pos(path=p) for p in im_paths]166 test_yaml = f"""167 - Row:168 - Col:169 - {im_paths[0]}170 - {im_paths[1]}171 - {im_paths[4]}172 - Col:173 - {im_paths[2]}174 - {im_paths[3]}175 """176 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)177 figure_test = sp.parse_yaml(test_config, dry=True)178 # Middle column with single image179 main_body = figure_test[1]180 self.assertEqual(main_body[1], ims[4])181 # First column182 col_one = main_body[0][1]183 self.assertEqual(col_one[0], ims[0])184 self.assertEqual(col_one[1], ims[1])185 # Final column186 col_two = main_body[2][1]187 self.assertEqual(col_two[0], ims[2])188 self.assertEqual(col_two[1], ims[3])189 def test_nested_double_short(self):190 """ Assemble a structure with two columns within a row using shortened notation. """191 paths = [192 "tests/test_im/square-im-1.png",193 "tests/test_im/square-im-2.png",194 "tests/test_im/square-im-3.png",195 "tests/test_im/square-im-4.png",196 "tests/test_im/square-im-5.png",197 ]198 im_paths = [Path(p).resolve() for p in paths]199 ims = [ct.Pos(path=p) for p in im_paths]200 test_yaml = f"""201 - Row:202 - Col: [{im_paths[0]}, {im_paths[1]}]203 - {im_paths[4]}204 - Col: [{im_paths[2]}, {im_paths[3]}]205 """206 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)207 figure_test = sp.parse_yaml(test_config, dry=True)208 # Middle column with single image209 main_body = figure_test[1]210 self.assertEqual(main_body[1], ims[4])211 # First column212 col_one = main_body[0][1]213 self.assertEqual(col_one[0], ims[0])214 self.assertEqual(col_one[1], ims[1])215 # Final column216 col_two = main_body[2][1]217 self.assertEqual(col_two[0], ims[2])218 self.assertEqual(col_two[1], ims[3])219 def test_nested_four_level(self):220 """ Read options in a nested element. """221 paths = [222 "tests/test_im/rect-im-1.png",223 "tests/test_im/rect-im-2.png",224 "tests/test_im/rect-im-3.png",225 "tests/test_im/square-im-3.png",226 "tests/test_im/square-im-4.png",227 "tests/test_im/square-im-5.png",228 "tests/test_im/rect-im-3.png",229 ]230 im_paths = [Path(p) for p in paths]231 test_yaml = f"""232 - Row:233 - Col:234 - {im_paths[0]}235 - Row:236 - {im_paths[3]}237 - Col:238 - {im_paths[0]}239 - {im_paths[2]}240 - {im_paths[4]}241 """242 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)243 figure_test = sp.parse_yaml(test_config)244 def test_simple_parse_flow(self):245 """ Read options in the simplest case with the space saving format. """246 im_one = Path("tests/test_im/square-im-1.png")247 im_two = Path("tests/test_im/square-im-2.png")248 test_yaml = f"""249 - Row:250 - {im_one}: {{text: "test-label"}}251 - {im_two}252 """253 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)254 figure_test = sp.parse_yaml(test_config)255 label_expected = "test-label"256 label_test = figure_test[0].label.text257 self.assertEqual(label_test, label_expected)258 def test_tri_array_merge(self):259 """ Investigate rescaling of PosArray """260 test_yaml = """261 - Row:262 - 1.png263 - Col:264 - 2.png265 - Row:266 - 3.png267 - 4.png268 """269 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)270 pos_arr = sp.parse_yaml(test_config).run()271 # Widths of the squares in decreasing size272 full_width = 50273 med_width = 50 * (2 / 3)274 sma_width = med_width / 2275 x_test = get_coords(pos_arr, "x")276 x_expected = [0, full_width, full_width, full_width + sma_width]277 assert_allclose(x_test, x_expected)278 y_test = get_coords(pos_arr, "y")279 y_expected = [0, 0, med_width, med_width]280 assert_allclose(y_test, y_expected)281 dx_test = get_coords(pos_arr, "dx")282 dx_expected = [full_width, med_width, sma_width, sma_width]283 assert_allclose(dx_test, dx_expected)284 dy_test = get_coords(pos_arr, "dy")285 dy_expected = [full_width, med_width, sma_width, sma_width]286 assert_allclose(dy_test, dy_expected)287class TestAssembleOptions(unittest.TestCase):288 """ Test parsing of options and figure labels. """289 def test_simple_parse_options(self):290 """ Read options in the simplest case. """291 test_yaml = f"""292 - Row:293 - {paths[0]}:294 text: "a."295 pos: (0.1, 0.1)296 - Col:297 - {paths[1]}298 - {paths[2]}299 - Row:300 - {paths[3]}301 - {paths[4]}302 """303 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)[0]304 def _parse_complex_path(leaf):305 """ Parse a path with labels: """306 for path, labels in leaf.items():307 if "pos" in labels:308 pos_str = labels["pos"].strip("()")309 pos = np.fromstring(pos_str, sep=", ")310 labels.pop("pos")311 else:312 pos = None313 label = Label(**labels, pos=pos)314 return ct.Pos(path, label)315 def _parse_path(leaf):316 """ Parse a simple path into a path. """317 return ct.Pos(leaf)318 def _is_subbranch(leaf):319 return "Col" in leaf or "Row" in leaf320 def read_branch(branch, dry=False):321 struct = []322 header = "Row" if "Row" in branch else "Col"323 header_struct = sc.Row if header == "Row" else sc.Col324 for entry in branch[header]:325 if isinstance(entry, str):326 struct.append(_parse_path(entry))327 elif _is_subbranch(entry):328 struct.append(read_branch(entry, dry=dry))329 elif isinstance(entry, dict):330 struct.append(_parse_complex_path(entry))331 else:332 raise ValueError("Unable to parse branch")333 if dry:334 return (header, struct)335 return header_struct(struct)336 struct = read_branch(test_config).run()337 struct.populate("/tmp/new_parse.png")338 def test_parse_global_opts(self):339 """ Test that we can read global options. """340 test_yaml = f"""341 - Row:342 - {paths[0]}343 - Col:344 - {paths[1]}345 - {paths[2]}346 - Row:347 - {paths[3]}348 - {paths[4]}349 - Options:350 - size: 45351 """352 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)353 pos_arr = sp.parse_yaml(test_config).run()354 labels = get_coords(pos_arr, "label")355 sizes_test = [l.size for l in labels]356 sizes_expected = np.ones(5) * 45357 assert_allclose(sizes_test, sizes_expected)358 def test_parse_global_override(self):359 """ Test that we can override a global options. """360 test_yaml = f"""361 - Row:362 - {paths[0]}363 - Col:364 - {paths[1]}: {{size: 10}}365 - {paths[2]}366 - Row:367 - {paths[3]}368 - {paths[4]}369 - Options:370 - size: 45371 """372 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)373 pos_arr = sp.parse_yaml(test_config).run()374 labels = get_coords(pos_arr, "label")375 sizes_test = [l.size for l in labels]376 sizes_expected = np.ones(5) * 45377 sizes_expected[1] = 10378 assert_allclose(sizes_test, sizes_expected)379 def test_parse_global_labels(self):380 """ Test that we parse the default label gen. """381 test_yaml = f"""382 - Row:383 - {paths[0]}384 - Col:385 - {paths[1]}386 - {paths[2]}387 - Row:388 - {paths[3]}389 - {paths[4]}390 - Options:391 - default_label: "{{index+1}}."392 - size: 18393 """394 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)395 pos_arr = sp.parse_yaml(test_config).run()396 labels = get_coords(pos_arr, "label")397 text_test = [l.text for l in labels]398 text_expected = [f"{i+1}." for i in range(5)]399 self.assertEqual(text_test, text_expected)400 sizes_test = [l.size for l in labels]401 sizes_expected = np.ones(5) * 18402 assert_allclose(sizes_test, sizes_expected)403 def test_parse_global_label_override(self):404 """ Test that we parse the default label gen with an override. """405 test_yaml = f"""406 - Row:407 - {paths[0]}408 - Col:409 - {paths[1]}410 - {paths[2]}:411 text: "A"412 - Row:413 - {paths[3]}414 - {paths[4]}415 - Options:416 - default_label: "{{index+1}}."417 """418 test_config = yaml.load(test_yaml, Loader=yaml.FullLoader)419 pos_arr = sp.parse_yaml(test_config).run()420 labels = get_coords(pos_arr, "label")421 text_test = [l.text for l in labels]422 text_expected = [f"{i+1}." for i in range(5)]423 text_expected[2] = "A"424 self.assertEqual(text_test, text_expected)425if __name__ == "__main__":...

Full Screen

Full Screen

test_reds.py

Source:test_reds.py Github

copy

Full Screen

1import imp2import yaml3import datetime4import pytz5from freezegun import freeze_time6reds = imp.load_source('reds', './reds/reds.py')7a = reds.reds()8#details9unsupported_multi_az_available = {10 "MultiAZ": True,11 "DBInstanceStatus": "available",12 "DBInstanceClass": "db.r3.large",13 }14micro_single_az_available = {15 "MultiAZ": False,16 "DBInstanceStatus": "available",17 "DBInstanceClass": "db.t2.micro",18 }19micro_multi_az_available = {20 "MultiAZ": True,21 "DBInstanceStatus": "available",22 "DBInstanceClass": "db.t2.micro",23 }24micro_multi_az_modifying = {25 "MultiAZ": True,26 "DBInstanceStatus": "modifying",27 "DBInstanceClass": "db.t2.micro",28 }29medium_multi_az_available = {30 "MultiAZ": True,31 "DBInstanceStatus": "available",32 "DBInstanceClass": "db.m3.medium",33 }34m4xl_multi_az_available = {35 "MultiAZ": True,36 "DBInstanceStatus": "available",37 "DBInstanceClass": "db.m4.xlarge",38 }39#alarm_status40high_cpu = {41 "MetricAlarms": [{42 "AlarmDescription": "CPU High Alarm",43 "StateValue": "ALARM",44 }, {45 "AlarmDescription": "CPU Low Alarm",46 "StateValue": "OK",47 }, {48 "AlarmDescription": "CPU Credits Exhausted Alarm",49 "StateValue": "OK",50 }]51}52low_cpu = {53 "MetricAlarms": [{54 "AlarmDescription": "CPU High Alarm",55 "StateValue": "OK",56 }, {57 "AlarmDescription": "CPU Low Alarm",58 "StateValue": "ALARM",59 }, {60 "AlarmDescription": "CPU Credits Exhausted Alarm",61 "StateValue": "OK",62 }]63}64credits_low = {65 "MetricAlarms": [{66 "AlarmDescription": "CPU High Alarm",67 "StateValue": "OK",68 }, {69 "AlarmDescription": "CPU Low Alarm",70 "StateValue": "OK",71 }, {72 "AlarmDescription": "CPU Credits Exhausted Alarm",73 "StateValue": "ALARM",74 }]75}76high_cpu_credits_low = {77 "MetricAlarms": [{78 "AlarmDescription": "CPU High Alarm",79 "StateValue": "ALARM",80 }, {81 "AlarmDescription": "CPU Low Alarm",82 "StateValue": "OK",83 }, {84 "AlarmDescription": "CPU Credits Exhausted Alarm",85 "StateValue": "ALARM",86 }]87}88no_alarm = {89 "MetricAlarms": [{90 "AlarmDescription": "CPU High Alarm",91 "StateValue": "OK",92 }, {93 "AlarmDescription": "CPU Low Alarm",94 "StateValue": "OK",95 }, {96 "AlarmDescription": "CPU Credits Exhausted Alarm",97 "StateValue": "OK",98 }]99}100#events101friday_midday_update = {102 "Events": [{103 "Date": datetime.datetime(2016, 1, 1, 18, 0, 0, 0, tzinfo=pytz.utc),104 "Message": "Applying modification to database instance class",105 "SourceIdentifier": "mixhop-rds-master",106 "EventCategories": ["configuration change"],107 "SourceType": "db-instance"108 },109 {110 "Date": datetime.datetime(2016, 1, 1, 18, 30, 0, 0, tzinfo=pytz.utc),111 "Message": "Finished applying modification to DB instance class",112 "SourceIdentifier": "mixhop-rds-master",113 "EventCategories": ["configuration change"],114 "SourceType": "db-instance"115 }]116}117saturday_midday_update = {118 "Events": [{119 "Date": datetime.datetime(2016, 1, 2, 18, 0, 0, 0, tzinfo=pytz.utc),120 "Message": "Applying modification to database instance class",121 "SourceIdentifier": "mixhop-rds-master",122 "EventCategories": ["configuration change"],123 "SourceType": "db-instance"124 },125 {126 "Date": datetime.datetime(2016, 1, 2, 18, 30, 0, 0, tzinfo=pytz.utc),127 "Message": "Finished applying modification to DB instance class",128 "SourceIdentifier": "mixhop-rds-master",129 "EventCategories": ["configuration change"],130 "SourceType": "db-instance"131 }]132}133no_update = {134 "Events": []135}136def get_vars(extra=None):137 suffix = extra if extra else ""138 return [yaml.load(file("./tests/test_vars{}.yaml".format(suffix))),yaml.load(file('./tests/test_alarms.yaml'))]139@freeze_time("2016-01-01 19:30:00", tz_offset=0)140def test_noop_on_single_az():141 test_yaml = get_vars()142 a.testing_startup(test_yaml[0], test_yaml[1],143 micro_single_az_available, high_cpu, friday_midday_update)144 assert(a.result['Action'] == 'NO_ACTION')145 assert(a.result['Message'] == 'Unable to work on singleAZ RDS!')146@freeze_time("2016-01-02 19:30:00", tz_offset=0)147def test_increase_on_high_alarm():148 test_yaml = get_vars()149 a.testing_startup(test_yaml[0], test_yaml[1],150 micro_multi_az_available, high_cpu, friday_midday_update)151 assert(a.result['Action'] == 'RESIZE')152 assert(a.result['Message'] == 'db.t2.small')153@freeze_time("2016-01-02 19:30:00", tz_offset=0)154def test_decrease_on_low_alarm():155 test_yaml = get_vars()156 a.testing_startup(test_yaml[0], test_yaml[1],157 medium_multi_az_available, low_cpu, friday_midday_update)158 assert(a.result['Action'] == 'RESIZE')159 assert(a.result['Message'] == 'db.t2.small')160@freeze_time("2016-01-02 19:30:00", tz_offset=0)161def test_noop_on_low_alarm_at_bottom():162 test_yaml = get_vars()163 a.testing_startup(test_yaml[0], test_yaml[1],164 micro_multi_az_available, low_cpu, friday_midday_update)165 assert(a.result['Action'] == 'NO_ACTION')166 assert(a.result['Message'] == 'Unable to scale - invalid to_index: -1')167@freeze_time("2016-01-02 19:30:00", tz_offset=0)168def test_noop_on_high_alarm_at_top():169 test_yaml = get_vars()170 a.testing_startup(test_yaml[0], test_yaml[1],171 m4xl_multi_az_available, high_cpu, friday_midday_update)172 assert(a.result['Action'] == 'NO_ACTION')173 assert(a.result['Message'] == 'Unable to scale - invalid to_index: 5')174@freeze_time("2016-01-02 19:30:00", tz_offset=0)175def test_credits_processed_before_low_and_multiple_index_up_jump():176 test_yaml = get_vars()177 a.testing_startup(test_yaml[0], test_yaml[1],178 micro_multi_az_available, high_cpu_credits_low, friday_midday_update)179 assert(a.result['Action'] == 'RESIZE')180 assert(a.result['Message'] == 'db.m3.medium')181@freeze_time("2016-01-01 19:30:00", tz_offset=0)182def test_in_scheduled_scale_out_micro_to_medium_no_alarm():183 test_yaml = get_vars()184 a.testing_startup(test_yaml[0], test_yaml[1],185 micro_multi_az_available, no_alarm, no_update)186 assert(a.result['Action'] == 'RESIZE')187 assert(a.result['Message'] == 'db.m3.medium')188@freeze_time("2016-01-01 19:30:00", tz_offset=0)189def test_in_scheduled_scale_out_medium_to_large_high_alarm():190 test_yaml = get_vars()191 a.testing_startup(test_yaml[0], test_yaml[1],192 medium_multi_az_available, high_cpu, no_update)193 assert(a.result['Action'] == 'RESIZE')194 assert(a.result['Message'] == 'db.m4.large')195@freeze_time("2016-01-02 19:30:00", tz_offset=0)196def test_out_scheduled_scale_down_medium_to_small_low_alarm():197 test_yaml = get_vars()198 a.testing_startup(test_yaml[0], test_yaml[1],199 medium_multi_az_available, low_cpu, no_update)200 assert(a.result['Action'] == 'RESIZE')201 assert(a.result['Message'] == 'db.t2.small')202@freeze_time("2016-01-02 18:45:00", tz_offset=0)203def test_blocked_recent_down():204 test_yaml = get_vars()205 a.testing_startup(test_yaml[0], test_yaml[1],206 medium_multi_az_available, low_cpu, saturday_midday_update)207 assert(a.result['Action'] == 'NO_ACTION')208 assert(a.result['Message'] == 'scale_down Cooldown threshold not reached')209@freeze_time("2016-01-02 18:35:00", tz_offset=0)210def test_blocked_recent_up():211 test_yaml = get_vars()212 a.testing_startup(test_yaml[0], test_yaml[1],213 medium_multi_az_available, high_cpu, saturday_midday_update)214 assert(a.result['Action'] == 'NO_ACTION')215 assert(a.result['Message'] == 'scale_up Cooldown threshold not reached')216@freeze_time("2016-01-02 18:55:00", tz_offset=0)217def test_allow_recent_up():218 test_yaml = get_vars()219 a.testing_startup(test_yaml[0], test_yaml[1],220 medium_multi_az_available, high_cpu, saturday_midday_update)221 assert(a.result['Action'] == 'RESIZE')222 assert(a.result['Message'] == 'db.m4.large')223@freeze_time("2016-01-02 18:45:00", tz_offset=0)224def test_blocked_busy():225 test_yaml = get_vars()226 a.testing_startup(test_yaml[0], test_yaml[1],227 micro_multi_az_modifying, {}, {})228 assert(a.result['Action'] == 'NO_ACTION')229 assert(a.result['Message'] == 'In middle of an operation already!')230@freeze_time("2016-01-02 18:45:00", tz_offset=0)231def test_blocked_unsupported():232 test_yaml = get_vars()233 a.testing_startup(test_yaml[0], test_yaml[1],234 unsupported_multi_az_available, {}, {})235 assert(a.result['Action'] == 'NO_ACTION')236 assert(a.result['Message'] == 'Instance size not in list!')237@freeze_time("2016-01-02 18:45:00", tz_offset=0)238def test_scale_up_on_credit_low():239 test_yaml = get_vars()240 a.testing_startup(test_yaml[0], test_yaml[1],241 micro_multi_az_available, credits_low, friday_midday_update)242 assert(a.result['Action'] == 'RESIZE')243 assert(a.result['Message'] == 'db.m3.medium')244@freeze_time("2016-01-02 18:45:00", tz_offset=0)245def test_nothing_to_do():246 test_yaml = get_vars()247 a.testing_startup(test_yaml[0], test_yaml[1],248 micro_multi_az_available, no_alarm, no_update)249 assert(a.result['Action'] == 'NO_ACTION')250 assert(a.result['Message'] == 'Nothing to do')251@freeze_time("2016-01-02 18:45:00", tz_offset=0)252def test_scaling_disabled_scale_up():253 test_yaml = get_vars('_disabled')254 a.testing_startup(test_yaml[0], test_yaml[1],255 micro_multi_az_available, high_cpu, no_update)256 assert(a.result['Action'] == 'NO_ACTION')257 assert(a.result['Message'] == 'Resizing disabled')258@freeze_time("2016-01-02 18:45:00", tz_offset=0)259def test_scaling_disabled_scale_down():260 test_yaml = get_vars('_disabled')261 a.testing_startup(test_yaml[0], test_yaml[1],262 medium_multi_az_available, low_cpu, no_update)263 assert(a.result['Action'] == 'NO_ACTION')264 assert(a.result['Message'] == 'Resizing disabled')265@freeze_time("2016-01-01 18:45:00", tz_offset=0)266def test_prevent_scale_down_during_scheduled():267 test_yaml = get_vars()268 a.testing_startup(test_yaml[0], test_yaml[1],269 medium_multi_az_available, low_cpu, no_update)270 assert(a.result['Action'] == 'NO_ACTION')271 assert(a.result['Message'] == 'Already at bottom for size during scheduled scale up')272@freeze_time("2016-01-01 19:30:00", tz_offset=0)273def test_invalid_index():274 test_yaml = get_vars('_invalid_index')275 a.testing_startup(test_yaml[0], test_yaml[1],276 medium_multi_az_available, high_cpu, no_update)277 assert(a.result['Action'] == 'NO_ACTION')...

Full Screen

Full Screen

test_dataset_iterators.py

Source:test_dataset_iterators.py Github

copy

Full Screen

1"""2Test cross-validation dataset iterators.3"""4from pylearn2.config import yaml_parse5from pylearn2.testing.skip import skip_if_no_sklearn6def test_dataset_k_fold():7 """Test DatasetKFold."""8 skip_if_no_sklearn()9 mapping = {'dataset_iterator': 'DatasetKFold'}10 test_yaml = test_yaml_dataset_iterator % mapping11 trainer = yaml_parse.load(test_yaml)12 trainer.main_loop()13def test_stratified_dataset_k_fold():14 """Test StratifiedDatasetKFold."""15 skip_if_no_sklearn()16 mapping = {'dataset_iterator': 'StratifiedDatasetKFold'}17 test_yaml = test_yaml_dataset_iterator % mapping18 trainer = yaml_parse.load(test_yaml)19 trainer.main_loop()20def test_dataset_shuffle_split():21 """Test DatasetShuffleSplit."""22 skip_if_no_sklearn()23 mapping = {'dataset_iterator': 'DatasetShuffleSplit'}24 test_yaml = test_yaml_dataset_iterator % mapping25 trainer = yaml_parse.load(test_yaml)26 trainer.main_loop()27def test_stratified_dataset_shuffle_split():28 """Test StratifiedDatasetShuffleSplit."""29 skip_if_no_sklearn()30 mapping = {'dataset_iterator': 'StratifiedDatasetShuffleSplit'}31 test_yaml = test_yaml_dataset_iterator % mapping32 trainer = yaml_parse.load(test_yaml)33 trainer.main_loop()34def test_dataset_validation_k_fold():35 """Test DatasetValidKFold."""36 skip_if_no_sklearn()37 mapping = {'dataset_iterator': 'DatasetValidationKFold'}38 test_yaml = test_yaml_dataset_iterator % mapping39 trainer = yaml_parse.load(test_yaml)40 trainer.main_loop()41def test_stratified_dataset_validation_k_fold():42 """Test StratifiedDatasetValidKFold."""43 skip_if_no_sklearn()44 mapping = {'dataset_iterator': 'StratifiedDatasetValidationKFold'}45 test_yaml = test_yaml_dataset_iterator % mapping46 trainer = yaml_parse.load(test_yaml)47 trainer.main_loop()48def test_dataset_validation_shuffle_split():49 """Test DatasetValidShuffleSplit."""50 skip_if_no_sklearn()51 mapping = {'dataset_iterator': 'DatasetValidationShuffleSplit'}52 test_yaml = test_yaml_dataset_iterator % mapping53 trainer = yaml_parse.load(test_yaml)54 trainer.main_loop()55def test_stratified_dataset_validation_shuffle_split():56 """Test StratifiedDatasetValidShuffleSplit."""57 skip_if_no_sklearn()58 mapping = {'dataset_iterator': 'StratifiedDatasetValidationShuffleSplit'}59 test_yaml = test_yaml_dataset_iterator % mapping60 trainer = yaml_parse.load(test_yaml)61 trainer.main_loop()62def test_which_set():63 """Test which_set selector."""64 skip_if_no_sklearn()65 # one label66 this_yaml = test_yaml_which_set % {'which_set': 'train'}67 trainer = yaml_parse.load(this_yaml)68 trainer.main_loop()69 # multiple labels70 this_yaml = test_yaml_which_set % {'which_set': ['train', 'test']}71 trainer = yaml_parse.load(this_yaml)72 trainer.main_loop()73 # improper label (iterator only returns 'train' and 'test' subsets)74 this_yaml = test_yaml_which_set % {'which_set': 'valid'}75 try:76 trainer = yaml_parse.load(this_yaml)77 trainer.main_loop()78 raise AssertionError79 except ValueError:80 pass81 # bogus label (not in approved list)82 this_yaml = test_yaml_which_set % {'which_set': 'bogus'}83 try:84 yaml_parse.load(this_yaml)85 raise AssertionError86 except ValueError:87 pass88def test_no_targets():89 """Test cross-validation without targets."""90 skip_if_no_sklearn()91 trainer = yaml_parse.load(test_yaml_no_targets)92 trainer.main_loop()93test_yaml_dataset_iterator = """94!obj:pylearn2.cross_validation.TrainCV {95 dataset_iterator:96 !obj:pylearn2.cross_validation.dataset_iterators.%(dataset_iterator)s {97 dataset:98 !obj:pylearn2.testing.datasets.random_one_hot_dense_design_matrix99 {100 rng: !obj:numpy.random.RandomState { seed: 1 },101 num_examples: 100,102 dim: 10,103 num_classes: 2,104 },105 },106 model: !obj:pylearn2.models.autoencoder.Autoencoder {107 nvis: 10,108 nhid: 8,109 act_enc: 'sigmoid',110 act_dec: 'linear'111 },112 algorithm: !obj:pylearn2.training_algorithms.bgd.BGD {113 batch_size: 50,114 line_search_mode: 'exhaustive',115 conjugate: 1,116 termination_criterion:117 !obj:pylearn2.termination_criteria.EpochCounter {118 max_epochs: 1,119 },120 cost: !obj:pylearn2.costs.autoencoder.MeanSquaredReconstructionError {121 },122 },123}124"""125test_yaml_which_set = """126!obj:pylearn2.cross_validation.TrainCV {127 dataset_iterator:128 !obj:pylearn2.cross_validation.dataset_iterators.DatasetKFold {129 dataset:130 !obj:pylearn2.testing.datasets.random_one_hot_dense_design_matrix131 {132 rng: !obj:numpy.random.RandomState { seed: 1 },133 num_examples: 100,134 dim: 10,135 num_classes: 2,136 },137 which_set: %(which_set)s,138 },139 model: !obj:pylearn2.models.autoencoder.Autoencoder {140 nvis: 10,141 nhid: 8,142 act_enc: 'sigmoid',143 act_dec: 'linear'144 },145 algorithm: !obj:pylearn2.training_algorithms.bgd.BGD {146 batch_size: 50,147 line_search_mode: 'exhaustive',148 conjugate: 1,149 termination_criterion:150 !obj:pylearn2.termination_criteria.EpochCounter {151 max_epochs: 1,152 },153 cost: !obj:pylearn2.costs.autoencoder.MeanSquaredReconstructionError {154 },155 },156}157"""158test_yaml_no_targets = """159!obj:pylearn2.cross_validation.TrainCV {160 dataset_iterator:161 !obj:pylearn2.cross_validation.dataset_iterators.DatasetKFold {162 dataset:163 !obj:pylearn2.testing.datasets.random_dense_design_matrix164 {165 rng: !obj:numpy.random.RandomState { seed: 1 },166 num_examples: 100,167 dim: 10,168 num_classes: 0,169 },170 },171 model: !obj:pylearn2.models.autoencoder.Autoencoder {172 nvis: 10,173 nhid: 8,174 act_enc: 'sigmoid',175 act_dec: 'linear'176 },177 algorithm: !obj:pylearn2.training_algorithms.bgd.BGD {178 batch_size: 50,179 line_search_mode: 'exhaustive',180 conjugate: 1,181 termination_criterion:182 !obj:pylearn2.termination_criteria.EpochCounter {183 max_epochs: 1,184 },185 cost: !obj:pylearn2.costs.autoencoder.MeanSquaredReconstructionError {186 },187 },188}...

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 avocado 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