Best Python code snippet using autotest_python
control_flow_test.py
Source:control_flow_test.py
...54 def test_tensor(self):55 def body(i):56 nonlocal s57 s = s * 10 + i58 def set_state(loop_vars):59 nonlocal s60 s, = loop_vars61 s = 062 control_flow.for_stmt(63 constant_op.constant([1, 2, 3, 4]),64 extra_test=lambda: True,65 body=body,66 get_state=lambda: (s,),67 set_state=set_state,68 symbol_names=('s',),69 opts={})70 self.assertEqual(s, (1234,))71 def test_range_tensor(self):72 def body(i):73 nonlocal s74 s = s * 10 + i75 def set_state(loop_vars):76 nonlocal s77 s, = loop_vars78 s = 079 control_flow.for_stmt(80 math_ops.range(5),81 extra_test=lambda: True,82 body=body,83 get_state=lambda: (s,),84 set_state=set_state,85 symbol_names=('s',),86 opts={'iterate_names': 'i'})87 self.assertEqual(s, (1234,))88 self.assertOpCreated('StatelessWhile')89 def test_range_tensor_explicit_limit_delta(self):90 def body(i):91 nonlocal s92 s = s * 100 + i93 def set_state(loop_vars):94 nonlocal s95 s, = loop_vars96 s = 097 control_flow.for_stmt(98 math_ops.range(-17, -3, 5),99 extra_test=lambda: True,100 body=body,101 get_state=lambda: (s,),102 set_state=set_state,103 symbol_names=('s',),104 opts={'iterate_names': 'i'})105 self.assertEqual(s, (-171207,))106 self.assertOpCreated('StatelessWhile')107 def test_range_tensor_explicit_limit_negative_delta(self):108 def body(i):109 nonlocal s110 s = s * 100 + i111 def set_state(loop_vars):112 nonlocal s113 s, = loop_vars114 s = 0115 control_flow.for_stmt(116 math_ops.range(17, 3, -5),117 extra_test=lambda: True,118 body=body,119 get_state=lambda: (s,),120 set_state=set_state,121 symbol_names=('s',),122 opts={'iterate_names': 'i'})123 self.assertEqual(s, (171207,))124 self.assertOpCreated('StatelessWhile')125 def test_range_tensor_random_delta(self):126 def body(i):127 nonlocal s128 s = s * 10 + i129 def set_state(loop_vars):130 nonlocal s131 s, = loop_vars132 s = 0133 random_one = random_ops.random_uniform((), 1, 2, dtype=dtypes.int32)134 control_flow.for_stmt(135 math_ops.range(0, 5, random_one),136 extra_test=lambda: True,137 body=body,138 get_state=lambda: (s,),139 set_state=set_state,140 symbol_names=('s',),141 opts={'iterate_names': 'i'})142 self.assertEqual(s, (1234,))143 self.assertOpCreated('StatelessWhile')144 def test_range_tensor_random_negative_delta(self):145 def body(i):146 nonlocal s147 s = s * 100 + i148 def set_state(loop_vars):149 nonlocal s150 s, = loop_vars151 s = 0152 random_neg_five = random_ops.random_uniform((), -5, -4, dtype=dtypes.int32)153 control_flow.for_stmt(154 math_ops.range(17, 3, random_neg_five),155 extra_test=lambda: True,156 body=body,157 get_state=lambda: (s,),158 set_state=set_state,159 symbol_names=('s',),160 opts={'iterate_names': 'i'})161 self.assertEqual(s, (171207,))162 self.assertOpCreated('StatelessWhile')163 def test_tensor_with_extra_test_object_vars(self):164 class MutableObject(object):165 field_1 = constant_op.constant(0, dtype=dtypes.int32)166 field_2 = constant_op.constant(1, dtype=dtypes.int32)167 state = MutableObject()168 def body(i):169 state.field_1 += i170 state.field_2 *= i171 def get_state():172 return state.field_1, state.field_2173 def set_state(loop_vars):174 state.field_1, state.field_2 = loop_vars175 control_flow.for_stmt(176 iter_=constant_op.constant([1, 2, 3, 4]),177 body=body,178 extra_test=lambda: state.field_1 < 6,179 get_state=get_state,180 set_state=set_state,181 symbol_names=('state.field_1', 'state.field_2'),182 opts={})183 self.assertEqual((state.field_1, state.field_2), (6, 6))184 self.assertOpCreated('StatelessWhile')185 def test_python(self):186 def body(i):187 nonlocal s188 s = s * 10 + i189 def set_state(loop_vars):190 nonlocal s191 s, = loop_vars192 s = 0193 control_flow.for_stmt(194 range(5),195 extra_test=lambda: True,196 body=body,197 get_state=lambda: (s,),198 set_state=set_state,199 symbol_names=('s',),200 opts={})201 self.assertEqual(s, 1234)202 self.assertNoOpsCreated()203 def test_python_generator_with_extra_test(self):204 def new_generator():205 for i in range(1, 5):206 yield i207 gen = new_generator()208 def run_loop():209 s = 0210 c = 0211 def body(i):212 nonlocal s, c213 s = s * 10 + i214 c += 1215 control_flow.for_stmt(216 gen,217 extra_test=lambda: c == 0, # Break after first iteration218 body=body,219 get_state=None,220 set_state=None,221 symbol_names=('s', 'c'),222 opts={})223 return s, c224 self.assertEqual(run_loop(), (1, 1))225 self.assertEqual(run_loop(), (2, 1))226 self.assertEqual(run_loop(), (3, 1))227 self.assertEqual(next(gen), 4)228 self.assertNoOpsCreated()229 def test_python_generator_with_extra_test_no_iterations(self):230 def new_generator():231 for i in range(5):232 yield i233 gen = new_generator()234 def run_loop():235 s = 0236 def body(i):237 nonlocal s238 s = s * 10 + i239 control_flow.for_stmt(240 gen,241 extra_test=lambda: False, # Break before loop242 body=body,243 get_state=None,244 set_state=None,245 symbol_names=('s',),246 opts={})247 return s248 self.assertEqual(run_loop(), 0)249 self.assertEqual(run_loop(), 0)250 self.assertEqual(next(gen), 0)251 self.assertNoOpsCreated()252 def test_tf_dataset(self):253 def body(i):254 nonlocal s255 s = s * 10 + i256 def set_state(loop_vars):257 nonlocal s258 s, = loop_vars259 s = constant_op.constant(0, dtype=dtypes.int64)260 control_flow.for_stmt(261 dataset_ops.Dataset.range(5),262 extra_test=None,263 body=body,264 get_state=lambda: (s,),265 set_state=set_state,266 symbol_names=('s',),267 opts={})268 self.assertEqual(s, (1234,))269 self.assertOpCreated('ScanDataset')270 def test_dataset_with_extra_test(self):271 def body(i):272 nonlocal s273 s = s * 10 + i274 def set_state(loop_vars):275 nonlocal s276 s, = loop_vars277 s = constant_op.constant(0, dtype=dtypes.int64)278 control_flow.for_stmt(279 dataset_ops.Dataset.range(5),280 extra_test=lambda: s < 3,281 body=body,282 get_state=lambda: (s,),283 set_state=set_state,284 symbol_names=('s',),285 opts={})286 self.assertEqual(s, (12,))287 self.assertOpCreated('ScanDataset')288 def test_dataset_with_extra_test_collection_vars(self):289 def body(i):290 nonlocal s291 l[0] += i292 s += i293 def set_state(loop_vars):294 nonlocal s295 l[0], s = loop_vars296 s = constant_op.constant(0, dtype=dtypes.int64)297 l = [constant_op.constant(0, dtype=dtypes.int64)]298 control_flow.for_stmt(299 dataset_ops.Dataset.range(5),300 extra_test=lambda: s < 3,301 body=body,302 get_state=lambda: (l[0], s),303 set_state=set_state,304 symbol_names=('l[0]', 's'),305 opts={})306 self.assertEqual((l[0], s), (3, 3))307 self.assertOpCreated('ScanDataset')308 def test_dataset_with_extra_test_iteration_limiting(self):309 def body(it):310 nonlocal i311 with ops.control_dependencies((control_flow_ops.Assert(i < 3, (i,)),)):312 i = it313 def set_state(loop_vars):314 nonlocal i315 i, = loop_vars316 i = constant_op.constant(0, dtype=dtypes.int64)317 control_flow.for_stmt(318 dataset_ops.Dataset.range(5),319 extra_test=lambda: i < 3,320 body=body,321 get_state=lambda: (i,),322 set_state=set_state,323 symbol_names=('i',),324 opts={})325 self.assertEqual(i, (3,))326 self.assertOpCreated('ScanDataset')327 def test_tf_dataset_no_loop_vars(self):328 def body(i):329 v.assign(v.read_value() * 10 + i)330 v = self.variable('v', 0, dtypes.int64)331 control_flow.for_stmt(332 dataset_ops.Dataset.range(5),333 extra_test=None,334 body=body,335 get_state=lambda: (),336 set_state=lambda _: None,337 symbol_names=(),338 opts={})339 self.assertEqual(v.read_value(), 1234)340 self.assertOpCreated('ScanDataset')341 def test_tf_iterator(self):342 def body(i):343 nonlocal s344 s = s * 10 + i345 def set_state(loop_vars):346 nonlocal s347 s, = loop_vars348 s = constant_op.constant(0, dtype=dtypes.int64)349 control_flow.for_stmt(350 iter(dataset_ops.Dataset.range(5)),351 extra_test=None,352 body=body,353 get_state=lambda: (s,),354 set_state=set_state,355 symbol_names=('s',),356 opts={})357 self.assertEqual(s, 1234)358 self.assertOpCreated('IteratorGetNextAsOptional')359 def test_tf_iterator_shape_invariants(self):360 def body(i):361 nonlocal s362 s = array_ops.concat([s, [i]], 0)363 def set_state(loop_vars):364 nonlocal s365 s, = loop_vars366 s = constant_op.constant([], dtype=dtypes.int64)367 control_flow.for_stmt(368 iter(dataset_ops.Dataset.range(5)),369 extra_test=None,370 body=body,371 get_state=lambda: (s,),372 set_state=set_state,373 symbol_names=('s',),374 opts={'shape_invariants': [(s, tensor_shape.TensorShape([None]))]})375 self.assertAllEqual(s, [0, 1, 2, 3, 4])376 self.assertOpCreated('IteratorGetNextAsOptional')377 def test_tf_iterator_no_loop_vars(self):378 def body(i):379 v.assign(v.read_value() * 10 + i)380 v = self.variable('v', 0, dtypes.int64)381 control_flow.for_stmt(382 iter(dataset_ops.Dataset.range(5)),383 extra_test=None,384 body=body,385 get_state=lambda: (),386 set_state=lambda _: None,387 symbol_names=(),388 opts={})389 self.assertEqual(v.read_value(), 1234)390 self.assertOpCreated('IteratorGetNextAsOptional')391 def test_tf_ragged_tensor(self):392 def body(i):393 nonlocal s394 s = s * 10 + i[0]395 def set_state(loop_vars):396 nonlocal s397 s, = loop_vars398 s = 0399 control_flow.for_stmt(400 ragged_factory_ops.constant([[1], [2, 4], [3]]),401 extra_test=None,402 body=body,403 get_state=lambda: (s,),404 set_state=set_state,405 symbol_names=('s',),406 opts={})407 self.assertEqual(s, (123,))408 self.assertOpCreated('StatelessWhile')409 def test_tf_ragged_tensor_higher_dimensional(self):410 def body(i):411 nonlocal s412 s = s * 10 + i[0][0]413 def set_state(loop_vars):414 nonlocal s415 s, = loop_vars416 s = 0417 ragged_3d = [418 [[1], [1, 1], [1]],419 [[2], [2]],420 ]421 control_flow.for_stmt(422 ragged_factory_ops.constant(ragged_3d),423 extra_test=None,424 body=body,425 get_state=lambda: (s,),426 set_state=set_state,427 symbol_names=('s',),428 opts={})429 self.assertEqual(s, (12,))430 self.assertOpCreated('StatelessWhile')431 def test_tf_ragged_tensor_no_loop_vars(self):432 v = self.variable('v', 0, dtypes.int32)433 def body(i):434 v.assign(v.read_value() * 10 + i[0])435 control_flow.for_stmt(436 ragged_factory_ops.constant([[1], [2, 4], [3]]),437 extra_test=None,438 body=body,439 get_state=lambda: (),440 set_state=lambda _: None,441 symbol_names=(),442 opts={})443 # Note: 123 = ((0*10 + 1)*10+2)*10+3 (first element of each row).444 self.assertEqual(v.read_value(), 123)445 self.assertOpCreated('While')446 def _basic_loop(self, init_value, body_fn):447 def body(i):448 nonlocal s449 s = body_fn(i, s)450 def set_state(loop_vars):451 nonlocal s452 s, = loop_vars453 s = init_value454 control_flow.for_stmt(455 constant_op.constant([1, 2, 3, 4]),456 extra_test=lambda: True,457 body=body,458 get_state=lambda: (s,),459 set_state=set_state,460 symbol_names=('s',),461 opts={})462 return s463 def test_tensor_illegal_input(self):464 with self.assertRaisesRegex(ValueError, '\'s\' may not be None'):465 self._basic_loop(None, lambda i, s: s)466 with self.assertRaisesRegex(ValueError, '\'s\' must be defined'):467 self._basic_loop(variable_operators.Undefined(''), lambda i, s: s)468 def test_tensor_none_output(self):469 with self.assertRaisesRegex(ValueError, '\'s\' is None at the end'):470 self._basic_loop(0, lambda i, s: None)471 def test_tensor_dtype_change(self):472 with self.assertRaisesRegex(TypeError, '\'s\'.* dtype float32 after'):473 self._basic_loop(0, lambda i, s: 1.0)474 def test_tensor_shape_change(self):475 with self.assertRaisesRegex(ValueError, r'\'s\'.* shape \(1,\) after'):476 self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32))477class WhileLoopTest(testing.AutoGraphTestCase):478 def test_tensor(self):479 def body():480 nonlocal i, s481 s = s * 10 + i482 i += 1483 def set_state(loop_vars):484 nonlocal i, s485 i, s = loop_vars486 i = 0487 n = constant_op.constant(5)488 s = 0489 control_flow.while_stmt(490 test=lambda: i < n,491 body=body,492 get_state=lambda: (i, s),493 set_state=set_state,494 symbol_names=('i', 's'),495 opts={})496 self.assertEqual(i, 5)497 self.assertEqual(s, 1234)498 self.assertOpCreated('StatelessWhile')499 def test_tensor_creating_variable(self):500 def body():501 nonlocal i, s502 i = constant_op.constant(2)503 s = i ** 5504 def set_state(loop_vars):505 nonlocal i, s506 i, s = loop_vars507 i = variable_operators.Undefined('i')508 s = constant_op.constant(0)509 control_flow.while_stmt(510 test=lambda: math_ops.equal(s, 0),511 body=body,512 get_state=lambda: (i, s),513 set_state=set_state,514 symbol_names=('i', 's'),515 opts={})516 self.assertEqual(i, 2)517 self.assertEqual(s, 32)518 self.assertOpCreated('StatelessWhile')519 # Check that the temporary staging of the body did not create extra ops.520 # Node naming is inconsistent between V1 and V2.521 self.assertGraphContains(r'(while/)?pow$', 1)522 def test_tensor_creating_complex_variable(self):523 def body():524 nonlocal i, s525 i = {'a': constant_op.constant(2), 'b': {'c': constant_op.constant(1)}}526 s = i['a'] ** 5527 def set_state(loop_vars):528 nonlocal i, s529 i, s = loop_vars530 i = variable_operators.Undefined('i')531 s = constant_op.constant(0)532 control_flow.while_stmt(533 test=lambda: math_ops.equal(s, 0),534 body=body,535 get_state=lambda: (i, s),536 set_state=set_state,537 symbol_names=('i', 's'),538 opts={})539 self.assertDictEqual(i, {'a': 2, 'b': {'c': 1}})540 self.assertEqual(s, 32)541 self.assertOpCreated('StatelessWhile')542 # Check that the temporary staging of the body did not create extra ops.543 # Node naming is inconsistent between V1 and V2.544 self.assertGraphContains(r'(while/)?pow$', 1)545 def test_tensor_with_side_effecting_condition(self):546 v = self.variable('v', 0, dtypes.int32)547 def cond():548 v.assign(v.read_value() * 10 + i)549 return i < n550 def body():551 nonlocal i552 i += 1553 def set_state(loop_vars):554 nonlocal i555 i, = loop_vars556 i = 0557 n = constant_op.constant(5)558 control_flow.while_stmt(559 test=cond,560 body=body,561 get_state=lambda: (i,),562 set_state=set_state,563 symbol_names=('i',),564 opts={})565 self.assertEqual(i, (5,))566 self.assertEqual(v, (12345,))567 self.assertOpCreated('While')568 def test_tensor_with_python_state(self):569 class MutableObject(object):570 field = constant_op.constant(0, dtype=dtypes.int32)571 state = MutableObject()572 def body():573 nonlocal i574 state.field = state.field * 10 + i575 i += 1576 def set_state(loop_vars):577 nonlocal i578 i, state.field = loop_vars579 i = 0580 n = constant_op.constant(5)581 control_flow.while_stmt(582 test=lambda: i < n,583 body=body,584 get_state=lambda: (i, state.field),585 set_state=set_state,586 symbol_names=('i', 'state.field'),587 opts={})588 self.assertEqual(i, 5)589 self.assertEqual(state.field, 1234)590 self.assertOpCreated('StatelessWhile')591 def test_python(self):592 def body():593 nonlocal i, s594 s = s * 10 + i595 i += 1596 i = 0597 s = 0598 n = 5599 control_flow.while_stmt(600 test=lambda: i < n,601 body=body,602 get_state=None,603 set_state=None,604 symbol_names=('i', 's'),605 opts={})606 self.assertEqual(s, 1234)607 self.assertNoOpsCreated()608 def test_python_with_tensor_state(self):609 def body():610 nonlocal i, s611 s = s * 10 + i612 i += 1613 i = 0614 s = constant_op.constant(0)615 n = 5616 control_flow.while_stmt(617 test=lambda: i < n,618 body=body,619 get_state=None,620 set_state=None,621 symbol_names=('i', 's'),622 opts={})623 self.assertEqual(i, 5)624 self.assertEqual(s, 1234)625 self.assertOpsNotCreated(('While', 'StatelessWhile'))626 def test_python_while_infinite(self):627 if not __debug__:628 self.skipTest('Feature disabled in optimized mode.')629 with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100):630 with self.assertRaisesRegex(ValueError, 'iteration limit'):631 control_flow.while_stmt(632 test=lambda: True,633 body=lambda: None,634 get_state=None,635 set_state=None,636 symbol_names=(),637 opts={})638 def test_python_for_infinite(self):639 if not __debug__:640 self.skipTest('Feature disabled in optimized mode.')641 with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100):642 with self.assertRaisesRegex(ValueError, 'iteration limit'):643 control_flow.for_stmt(644 iter_=range(101),645 extra_test=None,646 body=lambda i: None,647 get_state=None,648 set_state=None,649 symbol_names=(),650 opts={})651 def test_python_while_large_unroll_warning(self):652 if not __debug__:653 self.skipTest('Feature disabled in optimized mode.')654 with test.mock.patch.object(655 control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10):656 with ops.Graph().as_default():657 out_capturer = six.StringIO()658 with test.mock.patch.object(sys, 'stdout', out_capturer):659 with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True):660 def custom_iterator():661 for i in range(11):662 c = constant_op.constant(i)663 yield c664 i = 0665 control_flow.for_stmt(666 iter_=custom_iterator(),667 extra_test=None,668 body=lambda i: None,669 get_state=None,670 set_state=None,671 symbol_names=(),672 opts={})673 self.assertTrue(re.match(674 r'.* Large unrolled loop.*Const.*', out_capturer.getvalue()))675 def test_python_for_large_unroll_warning(self):676 if not __debug__:677 self.skipTest('Feature disabled in optimized mode.')678 with test.mock.patch.object(679 control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10):680 with ops.Graph().as_default():681 out_capturer = six.StringIO()682 with test.mock.patch.object(sys, 'stdout', out_capturer):683 with test.mock.patch.object(ag_logging, 'echo_log_to_stdout', True):684 def body():685 nonlocal i686 gen_math_ops.add(i, 1)687 i += 1688 i = 0689 control_flow.while_stmt(690 test=lambda: i < 100,691 body=body,692 get_state=None,693 set_state=None,694 symbol_names=('i',),695 opts={})696 self.assertTrue(re.match(697 r'.* Large unrolled loop.*Add.*', out_capturer.getvalue()))698 def _basic_loop(self, init_value, body_fn):699 def body():700 nonlocal i, s701 s = body_fn(i, s)702 i += 1703 def set_state(loop_vars):704 nonlocal i, s705 i, s = loop_vars706 i = 0707 n = constant_op.constant(5)708 s = init_value709 control_flow.while_stmt(710 test=lambda: i < n,711 body=body,712 get_state=lambda: (i, s),713 set_state=set_state,714 symbol_names=('i', 's'),715 opts={})716 return s717 def test_tensor_illegal_input(self):718 with self.assertRaisesRegex(ValueError, "'s' may not be None"):719 self._basic_loop(None, lambda i, s: s)720 with self.assertRaisesRegex(ValueError, "'s' must be defined"):721 self._basic_loop(variable_operators.Undefined(''), lambda i, s: s)722 def test_tensor_none_output(self):723 with self.assertRaisesRegex(ValueError, "'s' is None at the end"):724 self._basic_loop(0, lambda i, s: None)725 def test_tensor_dtype_change(self):726 with self.assertRaisesRegex(TypeError, "'s'.* dtype float32 after"):727 self._basic_loop(0, lambda i, s: 1.0)728 def test_tensor_shape_change(self):729 with self.assertRaisesRegex(ValueError, r"'s'.* shape \(1,\) after"):730 self._basic_loop(0, lambda i, s: np.array([1], dtype=np.int32))731 def _fixed_while_loop(self, cond_fn):732 def test_():733 return cond_fn(s)734 def body():735 nonlocal s736 s += 1737 def set_state(loop_vars):738 nonlocal s739 s, = loop_vars740 s = constant_op.constant(0)741 control_flow.while_stmt(742 test=test_,743 body=body,744 get_state=lambda: (s,),745 set_state=set_state,746 symbol_names=('s',),747 opts={})748 return s749 def _assertFixedLoopResult(self, cond, expected):750 def test_fn():751 return self._fixed_while_loop(cond)752 self.assertEqual(test_fn(), expected)753 def test_tensor_legal_cond_scalar(self):754 self._assertFixedLoopResult(lambda s: constant_op.constant(False), 0)755 self._assertFixedLoopResult(lambda s: s < 2, 2)756 def test_tensor_legal_cond_single_element_nd(self):757 self._assertFixedLoopResult(lambda s: constant_op.constant([[False]]), 0)758 self._assertFixedLoopResult(lambda s: _unranked_item(False), 0)759 def _assertCondCheckFails(self, cond):760 with self.assertRaisesRegex(761 ValueError, 'condition of while loop expected to be `tf.bool`'):762 self._fixed_while_loop(cond)763 def test_tensor_illegal_cond_not_bool(self):764 self._assertCondCheckFails(lambda s: constant_op.constant(1))765 self._assertCondCheckFails(lambda s: s)766 def test_tensor_illegal_cond_not_single_element(self):767 self._assertCondCheckFails(lambda s: constant_op.constant([1, 2, 3]))768 self._assertCondCheckFails(lambda s: constant_op.constant([True, False]))769 def test_tensor_illegal_cond_not_single_element_dynamic_shape(self):770 self._fixed_while_loop(lambda s: _partial_shaped_bools())771 # TODO(mdan): This error is quite bad. Measure the cost of an assertion.772 self.assertRaisesRuntime(773 errors_impl.InvalidArgumentError, 'requested shape has 1')774class IfStmtTest(testing.AutoGraphTestCase):775 def test_tensor(self):776 def test_fn(cond):777 def body():778 nonlocal i779 i = constant_op.constant(1)780 def orelse():781 nonlocal i782 i = constant_op.constant(-1)783 def set_state(cond_vars):784 nonlocal i785 i, = cond_vars786 i = None787 control_flow.if_stmt(788 cond=cond,789 body=body,790 orelse=orelse,791 get_state=lambda: (i,),792 set_state=set_state,793 symbol_names=('i',),794 nouts=1)795 return i796 self.assertEqual(test_fn(constant_op.constant(True)), 1)797 self.assertEqual(test_fn(constant_op.constant(False)), -1)798 self.assertOpCreated('StatelessIf')799 def test_tensor_no_outputs(self):800 def test_fn(cond):801 def body():802 nonlocal i803 i = constant_op.constant(1)804 def orelse():805 nonlocal i806 i = constant_op.constant(-1.0)807 def set_state(cond_vars):808 nonlocal i809 i, = cond_vars810 i = None811 control_flow.if_stmt(812 cond=cond,813 body=body,814 orelse=orelse,815 get_state=lambda: (i,),816 set_state=set_state,817 symbol_names=('i',),818 nouts=0)819 return i820 self.assertIsNone(test_fn(constant_op.constant(True)))821 self.assertIsNone(test_fn(constant_op.constant(False)))822 self.assertOpCreated('StatelessIf')823 def test_tensor_multiple_returns(self):824 def test_fn(cond):825 def body():826 nonlocal i, j827 i = constant_op.constant(1)828 j = constant_op.constant(2)829 def orelse():830 nonlocal i, j831 i = constant_op.constant(-1)832 j = constant_op.constant(-2)833 def set_state(cond_vars):834 nonlocal i, j835 i, j = cond_vars836 i, j = None, None837 control_flow.if_stmt(838 cond=cond,839 body=body,840 orelse=orelse,841 get_state=lambda: (i, j),842 set_state=set_state,843 symbol_names=('i', 'j'),844 nouts=2)845 return i, j846 self.assertEqual(test_fn(constant_op.constant(True)), (1, 2))847 self.assertEqual(test_fn(constant_op.constant(False)), (-1, -2))848 self.assertOpCreated('StatelessIf')849 def test_python(self):850 def test_fn(cond):851 def body():852 nonlocal i853 i = 1854 def orelse():855 nonlocal i856 i = -1857 i = None858 control_flow.if_stmt(859 cond=cond,860 body=body,861 orelse=orelse,862 get_state=None,863 set_state=None,864 symbol_names=('i',),865 nouts=1)866 return i867 self.assertEqual(test_fn(True), 1)868 self.assertEqual(test_fn(False), -1)869 self.assertNoOpsCreated()870 def test_python_multiple_returns(self):871 def test_fn(cond):872 def body():873 nonlocal i, j874 i = 1875 j = 2876 def orelse():877 nonlocal i, j878 i = -1879 j = -2880 i, j = None, None881 control_flow.if_stmt(882 cond=cond,883 body=body,884 orelse=orelse,885 get_state=None,886 set_state=None,887 symbol_names=('i', 'j'),888 nouts=2)889 return i, j890 self.assertEqual(test_fn(True), (1, 2))891 self.assertEqual(test_fn(False), (-1, -2))892 self.assertNoOpsCreated()893 def _basic_cond(self, body_fn, else_fn):894 def body():895 nonlocal x896 x = body_fn()897 def orelse():898 nonlocal x899 x = else_fn()900 def set_state(cond_vars):901 nonlocal x902 x, = cond_vars903 x = 0904 control_flow.if_stmt(905 cond=constant_op.constant(True),906 body=body,907 orelse=orelse,908 get_state=lambda: (x,),909 set_state=set_state,910 symbol_names=('x',),911 nouts=1)912 return x913 def test_tensor_none_output(self):914 with self.assertRaisesRegex(915 ValueError, "'x' is None at the end of the main branch"):916 self._basic_cond(lambda: None, lambda: 1)917 with self.assertRaisesRegex(918 ValueError, "'x' is None at the end of the else branch"):919 self._basic_cond(lambda: 1, lambda: None)920 def test_tensor_undefined_output(self):921 with self.assertRaisesRegex(922 ValueError, "'x' must also be initialized in the main branch"):923 self._basic_cond(lambda: variable_operators.Undefined('x'), lambda: 1)924 with self.assertRaisesRegex(925 ValueError, "'x' must also be initialized in the else branch"):926 self._basic_cond(lambda: 1, lambda: variable_operators.Undefined('s'))927 def test_tensor_dtype_change(self):928 with self.assertRaisesRegex(929 TypeError, "'x' has dtype int32.*but.*float32"):930 self._basic_cond(lambda: 1, lambda: 1.0)931 def _fixed_cond(self, cond_val):932 def body():933 nonlocal x934 x = 1935 def orelse():936 nonlocal x937 x = -1938 def set_state(cond_vars):939 nonlocal x940 x, = cond_vars941 x = 0942 control_flow.if_stmt(943 cond=cond_val,944 body=body,945 orelse=orelse,946 get_state=lambda: (x,),947 set_state=set_state,948 symbol_names=('x',),949 nouts=1)950 return x951 def _assertFixedCondResult(self, cond, expected):952 def test_fn():...
my_devices.py
Source:my_devices.py
...7# REFER TO :- https://developer-preview.smartthings.com/docs/devices/cloud-connected/device-handler-types8# REFER TO :- https://developer-preview.smartthings.com/docs/devices/capabilities/capabilities-reference/9# room_name, groups, categories10# REFER TO :- https://developer-preview.smartthings.com/docs/devices/device-profiles [CATEGORIES]11# def set_state(self, capability, attribute, value, unit=None, component="main")12# SET STATE : REFER TO :- https://developer-preview.smartthings.com/docs/devices/capabilities/capabilities-reference/13#Official c2c-arrival-2 Device14d1_c2c_arrival_2 = SchemaDevice(15 'd1_c2c_arrival_2',16 'd1_c2c_arrival_2',17 'c2c-arrival-2',18 '001')19d1_c2c_arrival_2.set_mn(20 'C2C Arrival 2 type - Presence, Battery, Tone',21 'Model D001')22d1_c2c_arrival_2.set_context(23 'Living',24 ['Presence Sensors'],25 ['presence-sensor'])26d1_c2c_arrival_2.set_state(27 'st.presenceSensor',28 'presence',29 'not present')30d1_c2c_arrival_2.set_state(31 'st.battery',32 'battery',33 100)34# The capability TONE has no state attributes. It has only one command -> BEEP35# d1_c2c_arrival_2.set_state(36# 'st.tone',37# 'switch',38# 'on')39#Official c2c-button-4 Device40d2_c2c_button_4 = SchemaDevice(41 'd2_c2c_button_4',42 'd2_c2c_button_4',43 'c2c-button-4',44 '002')45d2_c2c_button_4.set_mn(46 'C2C Button 4 type - Button, Holdable Button, Battery',47 'Model D002')48d2_c2c_button_4.set_context(49 'Living',50 ['Buttons'],51 ['switch'])52d2_c2c_button_4.set_state(53 'st.button',54 'button',55 'held')56#Button is holdable57d2_c2c_button_4.set_state(58 'st.battery',59 'battery',60 100)61#Official c2c-camera-2 Device62d3_c2c_camera_2 = SchemaDevice(63 'd3_c2c_camera_2',64 'd3_c2c_camera_2',65 'c2c-camera-2',66 '003')67d3_c2c_camera_2.set_mn(68 'C2C Camera 2 type - Image Capture',69 'Model D003')70d3_c2c_camera_2.set_context(71 'Living',72 ['Cameras'],73 ['camera'])74d3_c2c_camera_2.set_state(75 'st.imageCapture',76 'captureTime',77 '19700101T020000-0500')78d3_c2c_camera_2.set_state(79 'st.imageCapture',80 'encrypted',81 False)82d3_c2c_camera_2.set_state(83 'st.imageCapture',84 'image',85 'https://pixabay.com/photos/tree-sunset-clouds-sky-silhouette-736885/')86#Official c2c-carbon-monoxide-2 Device87d4_c2c_carbon_monoxide_2 = SchemaDevice(88 'd4_c2c_carbon_monoxide_2',89 'd4_c2c_carbon_monoxide_2',90 'c2c-carbon-monoxide-2',91 '004')92d4_c2c_carbon_monoxide_2.set_mn(93 'C2C Carbon Monoxide 2 type - Carbon Monoxide Detector, Battery, Tamper Alert',94 'Model D004')95d4_c2c_carbon_monoxide_2.set_context(96 'Living',97 ['Carbon Monoxide Sensors'],98 ['generic-sensor'])99d4_c2c_carbon_monoxide_2.set_state(100 'st.carbonMonoxideDetector',101 'carbonMonoxide',102 'clear')103d4_c2c_carbon_monoxide_2.set_state(104 'st.battery',105 'battery',106 100)107d4_c2c_carbon_monoxide_2.set_state(108 'st.tamperAlert',109 'tamper',110 'clear')111#Official c2c-color-temperature-bulb Device112d5_c2c_color_temperature_bulb = SchemaDevice(113 'd5_c2c_color_temperature_bulb',114 'd5_c2c_color_temperature_bulb',115 'c2c-color-temperature-bulb',116 '005')117d5_c2c_color_temperature_bulb.set_mn(118 'C2C Color Temperature Bulb type - Switch, Switch Level, Color Temperature',119 'Model D005')120d5_c2c_color_temperature_bulb.set_context(121 'Living',122 ['light'],123 ['light'])124d5_c2c_color_temperature_bulb.set_state(125 'st.switch',126 'switch',127 'on')128d5_c2c_color_temperature_bulb.set_state(129 'st.switchLevel',130 'level',131 50)132d5_c2c_color_temperature_bulb.set_state(133 'st.colorTemperature',134 'colorTemperature',135 6500)136#Official c2c-contact-2 Device137d6_c2c_contact_2 = SchemaDevice(138 'd6_c2c_contact_2',139 'd6_c2c_contact_2',140 'c2c-contact-2',141 '006')142d6_c2c_contact_2.set_mn(143 'C2C Contact 2 type - Contact Sensor, Battery, Temperature Measurement, Acceleration Sensor',144 'Model D006')145d6_c2c_contact_2.set_context(146 'Living',147 ['contact-sensor'],148 ['contact-sensor'])149d6_c2c_contact_2.set_state(150 'st.contactSensor',151 'contact',152 'closed')153d6_c2c_contact_2.set_state(154 'st.battery',155 'battery',156 50)157d6_c2c_contact_2.set_state(158 'st.temperatureMeasurement',159 'temperature',160 70,161 'C')162d6_c2c_contact_2.set_state(163 'st.accelerationSensor',164 'acceleration',165 'active')166#Official c2c-contact-4 Device167d7_c2c_contact_4 = SchemaDevice(168 'd7_c2c_contact_4',169 'd7_c2c_contact_4',170 'c2c-contact-4',171 '007')172d7_c2c_contact_4.set_mn(173 'C2C Contact 4 type - Contact Sensor, Door Control, Garage Door Control',174 'Model D007')175d7_c2c_contact_4.set_context(176 'Living',177 ['contact-sensor'],178 ['contact-sensor'])179d7_c2c_contact_4.set_state(180 'st.contactSensor',181 'contact',182 'closed')183d7_c2c_contact_4.set_state(184 'st.doorControl', # doorControl capability has commands185 'door',186 'closed')187d7_c2c_contact_4.set_state(188 'st.garageDoorControl', # doorControl capability has commands189 'door',190 'closed')191#Official c2c-dimmer-power-energy Device192d8_c2c_dimmer_power_energy = SchemaDevice(193 'd8_c2c_dimmer_power_energy',194 'd8_c2c_dimmer_power_energy',195 'c2c-dimmer-power-energy',196 '008')197d8_c2c_dimmer_power_energy.set_mn(198 'C2C Dimmer Power Energy type - Switch, Switch Level, Power Meter, Energy Meter',199 'Model D008')200d8_c2c_dimmer_power_energy.set_context(201 'Living',202 ['energy-meter'],203 ['energy-meter'])204d8_c2c_dimmer_power_energy.set_state(205 'st.switch',206 'switch',207 'on')208d8_c2c_dimmer_power_energy.set_state(209 'st.switchLevel',210 'level',211 50)212d8_c2c_dimmer_power_energy.set_state(213 'st.powerMeter',214 'power',215 90)216d8_c2c_dimmer_power_energy.set_state(217 'st.energyMeter',218 'energy',219 80)220#Official c2c-doorbell-2 Device221d9_c2c_doorbell_2 = SchemaDevice(222 'd9_c2c_doorbell_2',223 'd9_c2c_doorbell_2',224 'c2c-doorbell-2',225 '009')226d9_c2c_doorbell_2.set_mn(227 'C2C Doorbell 2 type - Button, Motion Sensor, Switch, Image Capture',228 'Model D009')229d9_c2c_doorbell_2.set_context(230 'Living',231 ['door-bell'],232 ['door-bell'])233d9_c2c_doorbell_2.set_state(234 'st.button',235 'button',236 'pushed')237d9_c2c_doorbell_2.set_state(238 'st.button',239 'numberOfButtons',240 500)241# d9_c2c_doorbell_2.set_state(242# 'st.button',243# 'supportedButtonValues',244# [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]) # asks for array of enum, not sure what array should it be.245d9_c2c_doorbell_2.set_state(246 'st.motionSensor',247 'motion',248 'active')249d9_c2c_doorbell_2.set_state(250 'st.switch',251 'switch',252 'on')253d9_c2c_doorbell_2.set_state( # imageCapture has commands254 'st.imageCapture',255 'captureTime',256 '19700101T020000-0500')257d9_c2c_doorbell_2.set_state(258 'st.imageCapture',259 'encrypted',260 False)261d9_c2c_doorbell_2.set_state(262 'st.imageCapture',263 'image',264 'https://pixabay.com/photos/tree-sunset-clouds-sky-silhouette-736885/')265#Official c2c-fan-controller-4speed Device266d10_c2c_fan_controller_4speed = SchemaDevice(267 'd10_c2c_fan_controller_4speed',268 'd10_c2c_fan_controller_4speed',269 'c2c-fan-controller-4speed',270 '0010')271d10_c2c_fan_controller_4speed.set_mn(272 'C2C Fan Controller 4Speed type - Switch, Fan Speed[1,2,3,4]',273 'Model D0010')274d10_c2c_fan_controller_4speed.set_context(275 'Living',276 ['fan'],277 ['fan'])278d10_c2c_fan_controller_4speed.set_state(279 'st.switch',280 'switch',281 'on')282d10_c2c_fan_controller_4speed.set_state(283 'st.fanSpeed',284 'fanSpeed',285 6700) # Fan speed has commands.286#Official c2c-humidity Device287d11_c2c_humidity = SchemaDevice(288 'd11_c2c_humidity',289 'd11_c2c_humidity',290 'c2c-humidity',291 '0011')292d11_c2c_humidity.set_mn(293 'C2C Humidity type - Relative Humidity Measurement, Battery, Temperature Measurement',294 'Model D0011')295d11_c2c_humidity.set_context(296 'Living',297 ['air-conditioner'],298 ['air-conditioner'])299d11_c2c_humidity.set_state(300 'st.relativeHumidityMeasurement',301 'humidity',302 50)303d11_c2c_humidity.set_state(304 'st.battery',305 'battery',306 50)307d11_c2c_humidity.set_state(308 'st.temperatureMeasurement',309 'temperature',310 70,311 'C')312#Official c2c-leak-3 Device313d12_c2c_leak_3 = SchemaDevice(314 'd12_c2c_leak_3',315 'd12_c2c_leak_3',316 'c2c-leak-3',317 '0012')318d12_c2c_leak_3.set_mn(319 'C2C Leak 3 type - Water Sensor, Battery, Temperature Measurement, Tamper Alert',320 'Model D0012')321d12_c2c_leak_3.set_context(322 'Living',323 ['leak-sensor'],324 ['leak-sensor'])325d12_c2c_leak_3.set_state(326 'st.waterSensor',327 'water',328 'dry')329d12_c2c_leak_3.set_state(330 'st.battery',331 'battery',332 50)333d12_c2c_leak_3.set_state(334 'st.temperatureMeasurement',335 'temperature',336 70,337 'C')338d12_c2c_leak_3.set_state(339 'st.tamperAlert',340 'tamper',341 'clear')342#Official c2c-lock-3 Device343d13_c2c_lock_3 = SchemaDevice(344 'd13_c2c_lock_3',345 'd13_c2c_lock_3',346 'c2c-lock-3',347 '0013')348d13_c2c_lock_3.set_mn(349 'C2C Lock 3 type - Lock, Battery, Temperature Measurement',350 'Model D0013')351d13_c2c_lock_3.set_context(352 'Living',353 ['smart-lock'],354 ['smart-lock'])355d13_c2c_lock_3.set_state(356 'st.lock',357 'lock',358 'unlocked')359d13_c2c_lock_3.set_state(360 'st.battery',361 'battery',362 50)363d13_c2c_lock_3.set_state(364 'st.temperatureMeasurement',365 'temperature',366 70,367 'C')368#Official c2c-motion-7 Device369d14_c2c_motion_7 = SchemaDevice(370 'd14_c2c_motion_7',371 'd14_c2c_motion_7',372 'c2c-motion-7',373 '0014')374d14_c2c_motion_7.set_mn(375 'C2C Motion 7 type - Motion Sensor, Battery, Temperature Measurement, Relative Humidity Measurement, Illuminance Measurement, Ultraviolet Index, Power Source, Tamper Alert',376 'Model D0014')377d14_c2c_motion_7.set_context(378 'Living',379 ['motion-sensor'],380 ['motion-sensor'])381d14_c2c_motion_7.set_state(382 'st.motionSensor',383 'motion',384 'active')385d14_c2c_motion_7.set_state(386 'st.battery',387 'battery',388 50)389d14_c2c_motion_7.set_state(390 'st.temperatureMeasurement',391 'temperature',392 70,393 'C')394d14_c2c_motion_7.set_state(395 'st.relativeHumidityMeasurement',396 'humidity',397 50)398d14_c2c_motion_7.set_state(399 'st.illuminanceMeasurement',400 'illuminance',401 30000)402d14_c2c_motion_7.set_state(403 'st.ultravioletIndex',404 'ultravioletIndex',405 150)406d14_c2c_motion_7.set_state(407 'st.powerSource',408 'powerSource',409 'battery')410d14_c2c_motion_7.set_state(411 'st.tamperAlert',412 'tamper',413 'clear')414#Official c2c-music-player-2 Device415d15_c2c_music_player_2 = SchemaDevice(416 'd15_c2c_music_player_2',417 'd15_c2c_music_player_2',418 'c2c-music-player-2',419 '0015')420d15_c2c_music_player_2.set_mn(421 'C2C Music Player 2 type - Music Player, Switch, Audio Notification',422 'Model D0015')423d15_c2c_music_player_2.set_context(424 'Living',425 ['network-audio'],426 ['network-audio'])427# d15_c2c_music_player_2.set_state( # No capability found for Music Player428# 'st.tamperAlert',429# 'tamper',430# 'clear')431d15_c2c_music_player_2.set_state(432 'st.switch',433 'switch',434 'on')435# d15_c2c_music_player_2.set_state( # No attributes found for Audio Notification436# 'st.audioNotification', # Commands found for audio notification437# 'tamper',438# 'clear')439#Official c2c-rgbw-color-bulb Device440d16_c2c_rgbw_color_bulb = SchemaDevice(441 'd16_c2c_rgbw_color_bulb',442 'd16_c2c_rgbw_color_bulb',443 'c2c-rgbw-color-bulb',444 '0016')445d16_c2c_rgbw_color_bulb.set_mn(446 'C2C RGBW Color Bulb type - Switch, Switch Level, Color Control, Color Temperature',447 'Model D0016')448d16_c2c_rgbw_color_bulb.set_context(449 'Living',450 ['light'],451 ['light'])452d16_c2c_rgbw_color_bulb.set_state(453 'st.switch',454 'switch',455 'on')456d16_c2c_rgbw_color_bulb.set_state(457 'st.switchLevel',458 'level',459 50)460# d16_c2c_rgbw_color_bulb.set_state(461# 'st.colorControl',462# 'color',463# '{"hue":"50", "saturation":"50"}') # Not sure of syntax.464d16_c2c_rgbw_color_bulb.set_state(465 'st.colorControl',466 'hue',467 50)468d16_c2c_rgbw_color_bulb.set_state(469 'st.colorControl',470 'saturation',471 50)472d16_c2c_rgbw_color_bulb.set_state(473 'st.colorTemperature',474 'colorTemperature',475 15000)476#Switch 1 has only switch capability477d101_switch_1 = SchemaDevice( # Device info478 'd101_switch_1',479 'd101_switch_1',480 'c2c-switch',481 '101')482d101_switch_1.set_mn( # Manufacturer info483 'Switch Mn Example',484 'Model X1')485d101_switch_1.set_context(486 'Living',487 ['All Lights'],488 ['switch'])489d101_switch_1.set_state(490 'st.switch',491 'switch',492 'on')493 494#Switch 2 has only switch capability495d102_switch_2 = SchemaDevice( # Device info496 'd102_switch_2',497 'd102_switch_2',498 'c2c-switch',499 '102')500d102_switch_2.set_mn( # Manufacturer info501 'Switch Mn Example',502 'Model X1')503d102_switch_2.set_context(504 'Living',505 ['All Lights'],506 ['switch'])507d102_switch_2.set_state(508 'st.switch',509 'switch',510 'on')511#Temp Sensor 1 can provide readings for Temperature Measurement, Contact Sensing and Battery level.512d103_temp_sensor_1 = SchemaDevice(513 'd103_temp_sensor_1',514 'd103_temp_sensor_1',515 'c2c-contact',516 '103')517d103_temp_sensor_1.set_mn(518 'Temp-Contact Sensor Manufacturer',519 'Model T1')520d103_temp_sensor_1.set_context(521 'Living',522 ['Temperature Sensors'],523 ['thermostat'])524d103_temp_sensor_1.set_state(525 'st.contactSensor',526 'contact',527 'open')528d103_temp_sensor_1.set_state(529 'st.temperatureMeasurement',530 'temperature',531 35,532 'C')533d103_temp_sensor_1.set_state(534 'st.battery',535 'battery',536 100)537#Color bulb 1 has a switch, a color control and a dimmer level setting.538d104_color_bulb_1 = SchemaDevice(539 'd104_color_bulb_1',540 'd104_color_bulb_1',541 'c2c-rgb-color-bulb',542 '104')543d104_color_bulb_1.set_mn(544 'Color Bulb Manufacturer',545 'Model C1')546d104_color_bulb_1.set_context(547 'Living',548 ['All Color Lights'],549 ['light'])550d104_color_bulb_1.set_state(551 'st.switch',552 'switch',553 'on')554d104_color_bulb_1.set_state(555 'st.switchLevel',556 'level',557 100)558# color_bulb_1.set_state(559# 'st.colorControl',560# 'color',561# '{"hue": "75", "saturation": "65"}')562d104_color_bulb_1.set_state(563 'st.colorControl',564 'hue',565 75)566d104_color_bulb_1.set_state(567 'st.colorControl',568 'saturation',569 65)570#Fan Control 1 has a switch capability and a fanSpeed setting for controlling the speed of a virtual fan.571d105_fan_control_1 = SchemaDevice(572 'd105_fan_control_1',573 'd105_fan_control_1',574 'c2c-fan-controller-4speed',575 '105')576d105_fan_control_1.set_mn(577 'Fan Control Manufacturer',578 'Model F1')579d105_fan_control_1.set_context(580 'Living',581 ['All Fans'],582 ['fan'])583d105_fan_control_1.set_state(584 'st.switch',585 'switch',586 'on')587d105_fan_control_1.set_state(588 'st.fanSpeed',589 'fanSpeed',590 4)591#Exporting all the devices in a variable for in-memory operations...
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!!