How to use warning method in storybook-root

Best JavaScript code snippet using storybook-root

deprecation_test.py

Source:deprecation_test.py Github

copy

Full Screen

1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Deprecation tests."""16# pylint: disable=unused-import17from __future__ import absolute_import18from __future__ import division19from __future__ import print_function20from tensorflow.python.framework import test_util21from tensorflow.python.platform import test22from tensorflow.python.platform import tf_logging as logging23from tensorflow.python.util import deprecation24from tensorflow.python.util import tf_inspect25class DeprecatedAliasTest(test.TestCase):26 @test.mock.patch.object(logging, "warning", autospec=True)27 def test_function_alias(self, mock_warning):28 deprecated_func = deprecation.deprecated_alias("deprecated.func",29 "real.func",30 logging.error)31 logging.error("fake error logged")32 self.assertEqual(0, mock_warning.call_count)33 deprecated_func("FAKE ERROR!")34 self.assertEqual(1, mock_warning.call_count)35 # Make sure the error points to the right file.36 self.assertRegexpMatches(mock_warning.call_args[0][1],37 r"deprecation_test\.py:")38 deprecated_func("ANOTHER FAKE ERROR!")39 self.assertEqual(1, mock_warning.call_count)40 @test.mock.patch.object(logging, "warning", autospec=True)41 def test_class_alias(self, mock_warning):42 class MyClass(object):43 """My docstring."""44 init_args = []45 def __init__(self, arg):46 MyClass.init_args.append(arg)47 deprecated_cls = deprecation.deprecated_alias("deprecated.cls",48 "real.cls",49 MyClass)50 print(deprecated_cls.__name__)51 print(deprecated_cls.__module__)52 print(deprecated_cls.__doc__)53 MyClass("test")54 self.assertEqual(0, mock_warning.call_count)55 deprecated_cls("deprecated")56 self.assertEqual(1, mock_warning.call_count)57 # Make sure the error points to the right file.58 self.assertRegexpMatches(mock_warning.call_args[0][1],59 r"deprecation_test\.py:")60 deprecated_cls("deprecated again")61 self.assertEqual(1, mock_warning.call_count)62 self.assertEqual(["test", "deprecated", "deprecated again"],63 MyClass.init_args)64 # Check __init__ signature matches for doc generation.65 self.assertEqual(66 tf_inspect.getfullargspec(MyClass.__init__),67 tf_inspect.getfullargspec(deprecated_cls.__init__))68class DeprecationTest(test.TestCase):69 @test.mock.patch.object(logging, "warning", autospec=True)70 def test_deprecated_once(self, mock_warning):71 date = "2016-07-04"72 instructions = "This is how you update..."73 @deprecation.deprecated(date, instructions, warn_once=True)74 def _fn():75 pass76 _fn()77 self.assertEqual(1, mock_warning.call_count)78 _fn()79 self.assertEqual(1, mock_warning.call_count)80 @test.mock.patch.object(logging, "warning", autospec=True)81 def test_silence(self, mock_warning):82 date = "2016-07-04"83 instructions = "This is how you update..."84 @deprecation.deprecated(date, instructions, warn_once=False)85 def _fn():86 pass87 _fn()88 self.assertEqual(1, mock_warning.call_count)89 with deprecation.silence():90 _fn()91 self.assertEqual(1, mock_warning.call_count)92 _fn()93 self.assertEqual(2, mock_warning.call_count)94 def _assert_subset(self, expected_subset, actual_set):95 self.assertTrue(96 actual_set.issuperset(expected_subset),97 msg="%s is not a superset of %s." % (actual_set, expected_subset))98 def test_deprecated_illegal_args(self):99 instructions = "This is how you update..."100 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):101 deprecation.deprecated("", instructions)102 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):103 deprecation.deprecated("07-04-2016", instructions)104 date = "2016-07-04"105 with self.assertRaisesRegexp(ValueError, "instructions"):106 deprecation.deprecated(date, None)107 with self.assertRaisesRegexp(ValueError, "instructions"):108 deprecation.deprecated(date, "")109 @test.mock.patch.object(logging, "warning", autospec=True)110 def test_no_date(self, mock_warning):111 date = None112 instructions = "This is how you update..."113 @deprecation.deprecated(date, instructions)114 def _fn(arg0, arg1):115 """fn doc.116 Args:117 arg0: Arg 0.118 arg1: Arg 1.119 Returns:120 Sum of args.121 """122 return arg0 + arg1123 self.assertEqual(124 "fn doc. (deprecated)"125 "\n"126 "\nWarning: THIS FUNCTION IS DEPRECATED. "127 "It will be removed in a future version."128 "\nInstructions for updating:\n%s"129 "\n"130 "\nArgs:"131 "\n arg0: Arg 0."132 "\n arg1: Arg 1."133 "\n"134 "\nReturns:"135 "\n Sum of args." % instructions, _fn.__doc__)136 # Assert calling new fn issues log warning.137 self.assertEqual(3, _fn(1, 2))138 self.assertEqual(1, mock_warning.call_count)139 (args, _) = mock_warning.call_args140 self.assertRegexpMatches(141 args[0], r"deprecated and will be removed")142 self._assert_subset(set(["in a future version", instructions]),143 set(args[1:]))144 @test.mock.patch.object(logging, "warning", autospec=True)145 @test_util.run_deprecated_v1146 def test_static_fn_with_doc(self, mock_warning):147 date = "2016-07-04"148 instructions = "This is how you update..."149 @deprecation.deprecated(date, instructions)150 def _fn(arg0, arg1):151 """fn doc.152 Args:153 arg0: Arg 0.154 arg1: Arg 1.155 Returns:156 Sum of args.157 """158 return arg0 + arg1159 # Assert function docs are properly updated.160 self.assertEqual("_fn", _fn.__name__)161 self.assertEqual(162 "fn doc. (deprecated)"163 "\n"164 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."165 "\nInstructions for updating:\n%s"166 "\n"167 "\nArgs:"168 "\n arg0: Arg 0."169 "\n arg1: Arg 1."170 "\n"171 "\nReturns:"172 "\n Sum of args." % (date, instructions), _fn.__doc__)173 # Assert calling new fn issues log warning.174 self.assertEqual(3, _fn(1, 2))175 self.assertEqual(1, mock_warning.call_count)176 (args, _) = mock_warning.call_args177 self.assertRegexpMatches(args[0], r"deprecated and will be removed")178 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))179 @test.mock.patch.object(logging, "warning", autospec=True)180 @test_util.run_deprecated_v1181 def test_static_fn_with_one_line_doc(self, mock_warning):182 date = "2016-07-04"183 instructions = "This is how you update..."184 @deprecation.deprecated(date, instructions)185 def _fn(arg0, arg1):186 """fn doc."""187 return arg0 + arg1188 # Assert function docs are properly updated.189 self.assertEqual("_fn", _fn.__name__)190 self.assertEqual(191 "fn doc. (deprecated)"192 "\n"193 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."194 "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)195 # Assert calling new fn issues log warning.196 self.assertEqual(3, _fn(1, 2))197 self.assertEqual(1, mock_warning.call_count)198 (args, _) = mock_warning.call_args199 self.assertRegexpMatches(args[0], r"deprecated and will be removed")200 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))201 @test.mock.patch.object(logging, "warning", autospec=True)202 @test_util.run_deprecated_v1203 def test_static_fn_no_doc(self, mock_warning):204 date = "2016-07-04"205 instructions = "This is how you update..."206 @deprecation.deprecated(date, instructions)207 def _fn(arg0, arg1):208 return arg0 + arg1209 # Assert function docs are properly updated.210 self.assertEqual("_fn", _fn.__name__)211 self.assertEqual(212 "DEPRECATED FUNCTION"213 "\n"214 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."215 "\nInstructions for updating:"216 "\n%s" % (date, instructions), _fn.__doc__)217 # Assert calling new fn issues log warning.218 self.assertEqual(3, _fn(1, 2))219 self.assertEqual(1, mock_warning.call_count)220 (args, _) = mock_warning.call_args221 self.assertRegexpMatches(args[0], r"deprecated and will be removed")222 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))223 @test.mock.patch.object(logging, "warning", autospec=True)224 def test_instance_fn_with_doc(self, mock_warning):225 date = "2016-07-04"226 instructions = "This is how you update..."227 class _Object(object):228 def __init(self):229 pass230 @deprecation.deprecated(date, instructions)231 def _fn(self, arg0, arg1):232 """fn doc.233 Args:234 arg0: Arg 0.235 arg1: Arg 1.236 Returns:237 Sum of args.238 """239 return arg0 + arg1240 # Assert function docs are properly updated.241 self.assertEqual(242 "fn doc. (deprecated)"243 "\n"244 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."245 "\nInstructions for updating:\n%s"246 "\n"247 "\nArgs:"248 "\n arg0: Arg 0."249 "\n arg1: Arg 1."250 "\n"251 "\nReturns:"252 "\n Sum of args." % (date, instructions),253 getattr(_Object, "_fn").__doc__)254 # Assert calling new fn issues log warning.255 self.assertEqual(3, _Object()._fn(1, 2))256 self.assertEqual(1, mock_warning.call_count)257 (args, _) = mock_warning.call_args258 self.assertRegexpMatches(args[0], r"deprecated and will be removed")259 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))260 @test.mock.patch.object(logging, "warning", autospec=True)261 def test_instance_fn_with_one_line_doc(self, mock_warning):262 date = "2016-07-04"263 instructions = "This is how you update..."264 class _Object(object):265 def __init(self):266 pass267 @deprecation.deprecated(date, instructions)268 def _fn(self, arg0, arg1):269 """fn doc."""270 return arg0 + arg1271 # Assert function docs are properly updated.272 self.assertEqual(273 "fn doc. (deprecated)"274 "\n"275 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."276 "\nInstructions for updating:\n%s" % (date, instructions),277 getattr(_Object, "_fn").__doc__)278 # Assert calling new fn issues log warning.279 self.assertEqual(3, _Object()._fn(1, 2))280 self.assertEqual(1, mock_warning.call_count)281 (args, _) = mock_warning.call_args282 self.assertRegexpMatches(args[0], r"deprecated and will be removed")283 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))284 @test.mock.patch.object(logging, "warning", autospec=True)285 def test_instance_fn_no_doc(self, mock_warning):286 date = "2016-07-04"287 instructions = "This is how you update..."288 class _Object(object):289 def __init(self):290 pass291 @deprecation.deprecated(date, instructions)292 def _fn(self, arg0, arg1):293 return arg0 + arg1294 # Assert function docs are properly updated.295 self.assertEqual(296 "DEPRECATED FUNCTION"297 "\n"298 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."299 "\nInstructions for updating:"300 "\n%s" % (date, instructions),301 getattr(_Object, "_fn").__doc__)302 # Assert calling new fn issues log warning.303 self.assertEqual(3, _Object()._fn(1, 2))304 self.assertEqual(1, mock_warning.call_count)305 (args, _) = mock_warning.call_args306 self.assertRegexpMatches(args[0], r"deprecated and will be removed")307 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))308 def test_prop_wrong_order(self):309 with self.assertRaisesRegexp(310 ValueError,311 "make sure @property appears before @deprecated in your source code"):312 # pylint: disable=unused-variable313 class _Object(object):314 def __init(self):315 pass316 @deprecation.deprecated("2016-07-04", "Instructions.")317 @property318 def _prop(self):319 return "prop_wrong_order"320 @test.mock.patch.object(logging, "warning", autospec=True)321 def test_prop_with_doc(self, mock_warning):322 date = "2016-07-04"323 instructions = "This is how you update..."324 class _Object(object):325 def __init(self):326 pass327 @property328 @deprecation.deprecated(date, instructions)329 def _prop(self):330 """prop doc.331 Returns:332 String.333 """334 return "prop_with_doc"335 # Assert function docs are properly updated.336 self.assertEqual(337 "prop doc. (deprecated)"338 "\n"339 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."340 "\nInstructions for updating:"341 "\n%s"342 "\n"343 "\nReturns:"344 "\n String." % (date, instructions),345 getattr(_Object, "_prop").__doc__)346 # Assert calling new fn issues log warning.347 self.assertEqual("prop_with_doc", _Object()._prop)348 self.assertEqual(1, mock_warning.call_count)349 (args, _) = mock_warning.call_args350 self.assertRegexpMatches(args[0], r"deprecated and will be removed")351 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))352 @test.mock.patch.object(logging, "warning", autospec=True)353 def test_prop_no_doc(self, mock_warning):354 date = "2016-07-04"355 instructions = "This is how you update..."356 class _Object(object):357 def __init(self):358 pass359 @property360 @deprecation.deprecated(date, instructions)361 def _prop(self):362 return "prop_no_doc"363 # Assert function docs are properly updated.364 self.assertEqual(365 "DEPRECATED FUNCTION"366 "\n"367 "\nWarning: THIS FUNCTION IS DEPRECATED. It will be removed after %s."368 "\nInstructions for updating:"369 "\n%s" % (date, instructions),370 getattr(_Object, "_prop").__doc__)371 # Assert calling new fn issues log warning.372 self.assertEqual("prop_no_doc", _Object()._prop)373 self.assertEqual(1, mock_warning.call_count)374 (args, _) = mock_warning.call_args375 self.assertRegexpMatches(args[0], r"deprecated and will be removed")376 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))377class DeprecatedArgsTest(test.TestCase):378 def _assert_subset(self, expected_subset, actual_set):379 self.assertTrue(380 actual_set.issuperset(expected_subset),381 msg="%s is not a superset of %s." % (actual_set, expected_subset))382 def test_deprecated_illegal_args(self):383 instructions = "This is how you update..."384 date = "2016-07-04"385 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):386 deprecation.deprecated_args("", instructions, "deprecated")387 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):388 deprecation.deprecated_args("07-04-2016", instructions, "deprecated")389 with self.assertRaisesRegexp(ValueError, "instructions"):390 deprecation.deprecated_args(date, None, "deprecated")391 with self.assertRaisesRegexp(ValueError, "instructions"):392 deprecation.deprecated_args(date, "", "deprecated")393 with self.assertRaisesRegexp(ValueError, "argument"):394 deprecation.deprecated_args(date, instructions)395 def test_deprecated_missing_args(self):396 date = "2016-07-04"397 instructions = "This is how you update..."398 def _fn(arg0, arg1, deprecated=None):399 return arg0 + arg1 if deprecated else arg1 + arg0400 # Assert calls without the deprecated argument log nothing.401 with self.assertRaisesRegexp(ValueError, "not present.*\\['missing'\\]"):402 deprecation.deprecated_args(date, instructions, "missing")(_fn)403 @test.mock.patch.object(logging, "warning", autospec=True)404 @test_util.run_deprecated_v1405 def test_static_fn_with_doc(self, mock_warning):406 date = "2016-07-04"407 instructions = "This is how you update..."408 @deprecation.deprecated_args(date, instructions, "deprecated")409 def _fn(arg0, arg1, deprecated=True):410 """fn doc.411 Args:412 arg0: Arg 0.413 arg1: Arg 1.414 deprecated: Deprecated!415 Returns:416 Sum of args.417 """418 return arg0 + arg1 if deprecated else arg1 + arg0419 # Assert function docs are properly updated.420 self.assertEqual("_fn", _fn.__name__)421 self.assertEqual(422 "fn doc. (deprecated arguments)"423 "\n"424 "\nWarning: SOME ARGUMENTS ARE DEPRECATED: `(deprecated)`. "425 "They will be removed after %s."426 "\nInstructions for updating:\n%s"427 "\n"428 "\nArgs:"429 "\n arg0: Arg 0."430 "\n arg1: Arg 1."431 "\n deprecated: Deprecated!"432 "\n"433 "\nReturns:"434 "\n Sum of args." % (date, instructions), _fn.__doc__)435 # Assert calls without the deprecated argument log nothing.436 self.assertEqual(3, _fn(1, 2))437 self.assertEqual(0, mock_warning.call_count)438 # Assert calls with the deprecated argument log a warning.439 self.assertEqual(3, _fn(1, 2, True))440 self.assertEqual(1, mock_warning.call_count)441 (args, _) = mock_warning.call_args442 self.assertRegexpMatches(args[0], r"deprecated and will be removed")443 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))444 @test.mock.patch.object(logging, "warning", autospec=True)445 @test_util.run_deprecated_v1446 def test_static_fn_with_one_line_doc(self, mock_warning):447 date = "2016-07-04"448 instructions = "This is how you update..."449 @deprecation.deprecated_args(date, instructions, "deprecated")450 def _fn(arg0, arg1, deprecated=True):451 """fn doc."""452 return arg0 + arg1 if deprecated else arg1 + arg0453 # Assert function docs are properly updated.454 self.assertEqual("_fn", _fn.__name__)455 self.assertEqual(456 "fn doc. (deprecated arguments)"457 "\n"458 "\nWarning: SOME ARGUMENTS ARE DEPRECATED: `(deprecated)`. "459 "They will be removed after %s."460 "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)461 # Assert calls without the deprecated argument log nothing.462 self.assertEqual(3, _fn(1, 2))463 self.assertEqual(0, mock_warning.call_count)464 # Assert calls with the deprecated argument log a warning.465 self.assertEqual(3, _fn(1, 2, True))466 self.assertEqual(1, mock_warning.call_count)467 (args, _) = mock_warning.call_args468 self.assertRegexpMatches(args[0], r"deprecated and will be removed")469 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))470 @test.mock.patch.object(logging, "warning", autospec=True)471 @test_util.run_deprecated_v1472 def test_static_fn_no_doc(self, mock_warning):473 date = "2016-07-04"474 instructions = "This is how you update..."475 @deprecation.deprecated_args(date, instructions, "deprecated")476 def _fn(arg0, arg1, deprecated=True):477 return arg0 + arg1 if deprecated else arg1 + arg0478 # Assert function docs are properly updated.479 self.assertEqual("_fn", _fn.__name__)480 self.assertEqual(481 "DEPRECATED FUNCTION ARGUMENTS"482 "\n"483 "\nWarning: SOME ARGUMENTS ARE DEPRECATED: `(deprecated)`. "484 "They will be removed after %s."485 "\nInstructions for updating:"486 "\n%s" % (date, instructions), _fn.__doc__)487 # Assert calls without the deprecated argument log nothing.488 self.assertEqual(3, _fn(1, 2))489 self.assertEqual(0, mock_warning.call_count)490 # Assert calls with the deprecated argument log a warning.491 self.assertEqual(3, _fn(1, 2, True))492 self.assertEqual(1, mock_warning.call_count)493 (args, _) = mock_warning.call_args494 self.assertRegexpMatches(args[0], r"deprecated and will be removed")495 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))496 @test.mock.patch.object(logging, "warning", autospec=True)497 @test_util.run_deprecated_v1498 def test_varargs(self, mock_warning):499 date = "2016-07-04"500 instructions = "This is how you update..."501 @deprecation.deprecated_args(date, instructions, "deprecated")502 def _fn(arg0, arg1, *deprecated):503 return arg0 + arg1 if deprecated else arg1 + arg0504 # Assert calls without the deprecated argument log nothing.505 self.assertEqual(3, _fn(1, 2))506 self.assertEqual(0, mock_warning.call_count)507 # Assert calls with the deprecated argument log a warning.508 self.assertEqual(3, _fn(1, 2, True, False))509 self.assertEqual(1, mock_warning.call_count)510 (args, _) = mock_warning.call_args511 self.assertRegexpMatches(args[0], r"deprecated and will be removed")512 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))513 @test.mock.patch.object(logging, "warning", autospec=True)514 @test_util.run_deprecated_v1515 def test_kwargs(self, mock_warning):516 date = "2016-07-04"517 instructions = "This is how you update..."518 @deprecation.deprecated_args(date, instructions, "deprecated")519 def _fn(arg0, arg1, **deprecated):520 return arg0 + arg1 if deprecated else arg1 + arg0521 # Assert calls without the deprecated argument log nothing.522 self.assertEqual(3, _fn(1, 2))523 self.assertEqual(0, mock_warning.call_count)524 # Assert calls with the deprecated argument log a warning.525 self.assertEqual(3, _fn(1, 2, a=True, b=False))526 self.assertEqual(1, mock_warning.call_count)527 (args, _) = mock_warning.call_args528 self.assertRegexpMatches(args[0], r"deprecated and will be removed")529 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))530 @test.mock.patch.object(logging, "warning", autospec=True)531 @test_util.run_deprecated_v1532 def test_positional_and_named(self, mock_warning):533 date = "2016-07-04"534 instructions = "This is how you update..."535 @deprecation.deprecated_args(date, instructions, "d1", "d2")536 def _fn(arg0, d1=None, arg1=2, d2=None):537 return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1538 # Assert calls without the deprecated arguments log nothing.539 self.assertEqual(2, _fn(1, arg1=2))540 self.assertEqual(0, mock_warning.call_count)541 # Assert calls with the deprecated arguments log warnings.542 self.assertEqual(2, _fn(1, None, 2, d2=False))543 self.assertEqual(2, mock_warning.call_count)544 (args1, _) = mock_warning.call_args_list[0]545 self.assertRegexpMatches(args1[0], r"deprecated and will be removed")546 self._assert_subset(set(["after " + date, instructions, "d1"]),547 set(args1[1:]))548 (args2, _) = mock_warning.call_args_list[1]549 self.assertRegexpMatches(args2[0], r"deprecated and will be removed")550 self._assert_subset(set(["after " + date, instructions, "d2"]),551 set(args2[1:]))552 @test.mock.patch.object(logging, "warning", autospec=True)553 @test_util.run_deprecated_v1554 def test_positional_and_named_with_ok_vals(self, mock_warning):555 date = "2016-07-04"556 instructions = "This is how you update..."557 @deprecation.deprecated_args(date, instructions, ("d1", None),558 ("d2", "my_ok_val"))559 def _fn(arg0, d1=None, arg1=2, d2=None):560 return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1561 # Assert calls without the deprecated arguments log nothing.562 self.assertEqual(2, _fn(1, arg1=2))563 self.assertEqual(0, mock_warning.call_count)564 # Assert calls with the deprecated arguments log warnings.565 self.assertEqual(2, _fn(1, False, 2, d2=False))566 self.assertEqual(2, mock_warning.call_count)567 (args1, _) = mock_warning.call_args_list[0]568 self.assertRegexpMatches(args1[0], r"deprecated and will be removed")569 self._assert_subset(set(["after " + date, instructions, "d1"]),570 set(args1[1:]))571 (args2, _) = mock_warning.call_args_list[1]572 self.assertRegexpMatches(args2[0], r"deprecated and will be removed")573 self._assert_subset(set(["after " + date, instructions, "d2"]),574 set(args2[1:]))575 # Assert calls with the deprecated arguments don't log warnings if576 # the value matches the 'ok_val'.577 mock_warning.reset_mock()578 self.assertEqual(3, _fn(1, None, 2, d2="my_ok_val"))579 self.assertEqual(0, mock_warning.call_count)580 @test.mock.patch.object(logging, "warning", autospec=True)581 @test_util.run_deprecated_v1582 def test_deprecated_args_once(self, mock_warning):583 date = "2016-07-04"584 instructions = "This is how you update..."585 @deprecation.deprecated_args(date, instructions, "arg", warn_once=True)586 def _fn(arg=0): # pylint: disable=unused-argument587 pass588 _fn()589 self.assertEqual(0, mock_warning.call_count)590 _fn(arg=0)591 self.assertEqual(1, mock_warning.call_count)592 _fn(arg=1)593 self.assertEqual(1, mock_warning.call_count)594 @test.mock.patch.object(logging, "warning", autospec=True)595 @test_util.run_deprecated_v1596 def test_deprecated_multiple_args_once_each(self, mock_warning):597 date = "2016-07-04"598 instructions = "This is how you update..."599 @deprecation.deprecated_args(date, instructions, "arg0", "arg1",600 warn_once=True)601 def _fn(arg0=0, arg1=0): # pylint: disable=unused-argument602 pass603 _fn(arg0=0)604 self.assertEqual(1, mock_warning.call_count)605 _fn(arg0=0)606 self.assertEqual(1, mock_warning.call_count)607 _fn(arg1=0)608 self.assertEqual(2, mock_warning.call_count)609 _fn(arg0=0)610 self.assertEqual(2, mock_warning.call_count)611 _fn(arg1=0)612 self.assertEqual(2, mock_warning.call_count)613class DeprecatedArgValuesTest(test.TestCase):614 def _assert_subset(self, expected_subset, actual_set):615 self.assertTrue(616 actual_set.issuperset(expected_subset),617 msg="%s is not a superset of %s." % (actual_set, expected_subset))618 def test_deprecated_illegal_args(self):619 instructions = "This is how you update..."620 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):621 deprecation.deprecated_arg_values("", instructions, deprecated=True)622 with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):623 deprecation.deprecated_arg_values(624 "07-04-2016", instructions, deprecated=True)625 date = "2016-07-04"626 with self.assertRaisesRegexp(ValueError, "instructions"):627 deprecation.deprecated_arg_values(date, None, deprecated=True)628 with self.assertRaisesRegexp(ValueError, "instructions"):629 deprecation.deprecated_arg_values(date, "", deprecated=True)630 with self.assertRaisesRegexp(ValueError, "argument"):631 deprecation.deprecated_arg_values(date, instructions)632 @test.mock.patch.object(logging, "warning", autospec=True)633 @test_util.run_deprecated_v1634 def test_static_fn_with_doc(self, mock_warning):635 date = "2016-07-04"636 instructions = "This is how you update..."637 @deprecation.deprecated_arg_values(date, instructions, warn_once=False,638 deprecated=True)639 def _fn(arg0, arg1, deprecated=True):640 """fn doc.641 Args:642 arg0: Arg 0.643 arg1: Arg 1.644 deprecated: Deprecated!645 Returns:646 Sum of args.647 """648 return arg0 + arg1 if deprecated else arg1 + arg0649 # Assert function docs are properly updated.650 self.assertEqual("_fn", _fn.__name__)651 self.assertEqual(652 "fn doc. (deprecated argument values)"653 "\n"654 "\nWarning: SOME ARGUMENT VALUES ARE DEPRECATED: `(deprecated=True)`. "655 "They will be removed after %s."656 "\nInstructions for updating:\n%s"657 "\n"658 "\nArgs:"659 "\n arg0: Arg 0."660 "\n arg1: Arg 1."661 "\n deprecated: Deprecated!"662 "\n"663 "\nReturns:"664 "\n Sum of args." % (date, instructions), _fn.__doc__)665 # Assert calling new fn with non-deprecated value logs nothing.666 self.assertEqual(3, _fn(1, 2, deprecated=False))667 self.assertEqual(0, mock_warning.call_count)668 # Assert calling new fn with deprecated value issues log warning.669 self.assertEqual(3, _fn(1, 2, deprecated=True))670 self.assertEqual(1, mock_warning.call_count)671 (args, _) = mock_warning.call_args672 self.assertRegexpMatches(args[0], r"deprecated and will be removed")673 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))674 # Assert calling new fn with default deprecated value issues log warning.675 self.assertEqual(3, _fn(1, 2))676 self.assertEqual(2, mock_warning.call_count)677 @test.mock.patch.object(logging, "warning", autospec=True)678 @test_util.run_deprecated_v1679 def test_static_fn_with_one_line_doc(self, mock_warning):680 date = "2016-07-04"681 instructions = "This is how you update..."682 @deprecation.deprecated_arg_values(date, instructions, warn_once=False,683 deprecated=True)684 def _fn(arg0, arg1, deprecated=True):685 """fn doc."""686 return arg0 + arg1 if deprecated else arg1 + arg0687 # Assert function docs are properly updated.688 self.assertEqual("_fn", _fn.__name__)689 self.assertEqual(690 "fn doc. (deprecated argument values)"691 "\n"692 "\nWarning: SOME ARGUMENT VALUES ARE DEPRECATED: `(deprecated=True)`. "693 "They will be removed after %s."694 "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)695 # Assert calling new fn with non-deprecated value logs nothing.696 self.assertEqual(3, _fn(1, 2, deprecated=False))697 self.assertEqual(0, mock_warning.call_count)698 # Assert calling new fn with deprecated value issues log warning.699 self.assertEqual(3, _fn(1, 2, deprecated=True))700 self.assertEqual(1, mock_warning.call_count)701 (args, _) = mock_warning.call_args702 self.assertRegexpMatches(args[0], r"deprecated and will be removed")703 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))704 # Assert calling new fn with default deprecated value issues log warning.705 self.assertEqual(3, _fn(1, 2))706 self.assertEqual(2, mock_warning.call_count)707 @test.mock.patch.object(logging, "warning", autospec=True)708 @test_util.run_deprecated_v1709 def test_static_fn_no_doc(self, mock_warning):710 date = "2016-07-04"711 instructions = "This is how you update..."712 @deprecation.deprecated_arg_values(date, instructions, warn_once=False,713 deprecated=True)714 def _fn(arg0, arg1, deprecated=True):715 return arg0 + arg1 if deprecated else arg1 + arg0716 # Assert function docs are properly updated.717 self.assertEqual("_fn", _fn.__name__)718 self.assertEqual(719 "DEPRECATED FUNCTION ARGUMENT VALUES"720 "\n"721 "\nWarning: SOME ARGUMENT VALUES ARE DEPRECATED: `(deprecated=True)`. "722 "They will be removed after %s."723 "\nInstructions for updating:"724 "\n%s" % (date, instructions), _fn.__doc__)725 # Assert calling new fn with non-deprecated value logs nothing.726 self.assertEqual(3, _fn(1, 2, deprecated=False))727 self.assertEqual(0, mock_warning.call_count)728 # Assert calling new fn issues log warning.729 self.assertEqual(3, _fn(1, 2, deprecated=True))730 self.assertEqual(1, mock_warning.call_count)731 (args, _) = mock_warning.call_args732 self.assertRegexpMatches(args[0], r"deprecated and will be removed")733 self._assert_subset(set(["after " + date, instructions]), set(args[1:]))734 # Assert calling new fn with default deprecated value issues log warning.735 self.assertEqual(3, _fn(1, 2))736 self.assertEqual(2, mock_warning.call_count)737 @test.mock.patch.object(logging, "warning", autospec=True)738 def test_deprecated_arg_values_once(self, mock_warning):739 date = "2016-07-04"740 instructions = "This is how you update..."741 @deprecation.deprecated_arg_values(date, instructions, warn_once=True,742 deprecated=True)743 def _fn(deprecated): # pylint: disable=unused-argument744 pass745 _fn(deprecated=False)746 self.assertEqual(0, mock_warning.call_count)747 _fn(deprecated=True)748 self.assertEqual(1, mock_warning.call_count)749 _fn(deprecated=True)750 self.assertEqual(1, mock_warning.call_count)751 @test.mock.patch.object(logging, "warning", autospec=True)752 def test_deprecated_multiple_arg_values_once_each(self, mock_warning):753 date = "2016-07-04"754 instructions = "This is how you update..."755 @deprecation.deprecated_arg_values(date, instructions, warn_once=True,756 arg0="forbidden", arg1="disallowed")757 def _fn(arg0, arg1): # pylint: disable=unused-argument758 pass759 _fn(arg0="allowed", arg1="also allowed")760 self.assertEqual(0, mock_warning.call_count)761 _fn(arg0="forbidden", arg1="disallowed")762 self.assertEqual(2, mock_warning.call_count)763 _fn(arg0="forbidden", arg1="allowed")764 self.assertEqual(2, mock_warning.call_count)765 _fn(arg0="forbidden", arg1="disallowed")766 self.assertEqual(2, mock_warning.call_count)767class DeprecationArgumentsTest(test.TestCase):768 def testDeprecatedArgumentLookup(self):769 good_value = 3770 self.assertEqual(771 deprecation.deprecated_argument_lookup("val_new", good_value, "val_old",772 None), good_value)773 self.assertEqual(774 deprecation.deprecated_argument_lookup("val_new", None, "val_old",775 good_value), good_value)776 with self.assertRaisesRegexp(ValueError,777 "Cannot specify both 'val_old' and 'val_new'"):778 self.assertEqual(779 deprecation.deprecated_argument_lookup("val_new", good_value,780 "val_old", good_value),781 good_value)782 def testRewriteArgumentDocstring(self):783 docs = """Add `a` and `b`784 Args:785 a: first arg786 b: second arg787 """788 new_docs = deprecation.rewrite_argument_docstring(789 deprecation.rewrite_argument_docstring(docs, "a", "left"), "b", "right")790 new_docs_ref = """Add `left` and `right`791 Args:792 left: first arg793 right: second arg794 """795 self.assertEqual(new_docs, new_docs_ref)796class DeprecatedEndpointsTest(test.TestCase):797 def testSingleDeprecatedEndpoint(self):798 @deprecation.deprecated_endpoints("foo1")799 def foo():800 pass801 self.assertEqual(("foo1",), foo._tf_deprecated_api_names)802 def testMultipleDeprecatedEndpoint(self):803 @deprecation.deprecated_endpoints("foo1", "foo2")804 def foo():805 pass806 self.assertEqual(("foo1", "foo2"), foo._tf_deprecated_api_names)807 def testCannotSetDeprecatedEndpointsTwice(self):808 with self.assertRaises(deprecation.DeprecatedNamesAlreadySet):809 @deprecation.deprecated_endpoints("foo1")810 @deprecation.deprecated_endpoints("foo2")811 def foo(): # pylint: disable=unused-variable812 pass813if __name__ == "__main__":...

Full Screen

Full Screen

test_warnings.py

Source:test_warnings.py Github

copy

Full Screen

...425 self.assertEqual(len(w), 0)426 finally:427 self.module.defaultaction = original428 def test_showwarning_missing(self):429 # Test that showwarning() missing is okay.430 text = 'del showwarning test'431 with original_warnings.catch_warnings(module=self.module):432 self.module.filterwarnings("always", category=UserWarning)433 del self.module.showwarning434 with test_support.captured_output('stderr') as stream:435 self.module.warn(text)436 result = stream.getvalue()437 self.assertIn(text, result)438 def test_showwarning_not_callable(self):439 with original_warnings.catch_warnings(module=self.module):440 self.module.filterwarnings("always", category=UserWarning)441 old_showwarning = self.module.showwarning442 self.module.showwarning = 23443 try:444 self.assertRaises(TypeError, self.module.warn, "Warning!")445 finally:446 self.module.showwarning = old_showwarning447 def test_show_warning_output(self):448 # With showarning() missing, make sure that output is okay.449 text = 'test show_warning'450 with original_warnings.catch_warnings(module=self.module):451 self.module.filterwarnings("always", category=UserWarning)452 del self.module.showwarning453 with test_support.captured_output('stderr') as stream:454 warning_tests.inner(text)455 result = stream.getvalue()456 self.assertEqual(result.count('\n'), 2,457 "Too many newlines in %r" % result)458 first_line, second_line = result.split('\n', 1)459 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'460 first_line_parts = first_line.rsplit(':', 3)461 path, line, warning_class, message = first_line_parts462 line = int(line)463 self.assertEqual(expected_file, path)464 self.assertEqual(warning_class, ' ' + UserWarning.__name__)465 self.assertEqual(message, ' ' + text)466 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'467 assert expected_line468 self.assertEqual(second_line, expected_line)469class WarningsDisplayTests(unittest.TestCase):470 """Test the displaying of warnings and the ability to overload functions471 related to displaying warnings."""472 def test_formatwarning(self):473 message = "msg"474 category = Warning475 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'476 line_num = 3477 file_line = linecache.getline(file_name, line_num).strip()478 format = "%s:%s: %s: %s\n %s\n"479 expect = format % (file_name, line_num, category.__name__, message,480 file_line)481 self.assertEqual(expect, self.module.formatwarning(message,482 category, file_name, line_num))483 # Test the 'line' argument.484 file_line += " for the win!"485 expect = format % (file_name, line_num, category.__name__, message,486 file_line)487 self.assertEqual(expect, self.module.formatwarning(message,488 category, file_name, line_num, file_line))489 def test_showwarning(self):490 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'491 line_num = 3492 expected_file_line = linecache.getline(file_name, line_num).strip()493 message = 'msg'494 category = Warning495 file_object = StringIO.StringIO()496 expect = self.module.formatwarning(message, category, file_name,497 line_num)498 self.module.showwarning(message, category, file_name, line_num,499 file_object)500 self.assertEqual(file_object.getvalue(), expect)501 # Test 'line' argument.502 expected_file_line += "for the win!"503 expect = self.module.formatwarning(message, category, file_name,504 line_num, expected_file_line)505 file_object = StringIO.StringIO()506 self.module.showwarning(message, category, file_name, line_num,507 file_object, expected_file_line)508 self.assertEqual(expect, file_object.getvalue())509class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):510 module = c_warnings511class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):512 module = py_warnings513class CatchWarningTests(BaseTest):514 """Test catch_warnings()."""515 def test_catch_warnings_restore(self):516 wmod = self.module517 orig_filters = wmod.filters518 orig_showwarning = wmod.showwarning519 # Ensure both showwarning and filters are restored when recording520 with wmod.catch_warnings(module=wmod, record=True):521 wmod.filters = wmod.showwarning = object()522 self.assertTrue(wmod.filters is orig_filters)523 self.assertTrue(wmod.showwarning is orig_showwarning)524 # Same test, but with recording disabled525 with wmod.catch_warnings(module=wmod, record=False):526 wmod.filters = wmod.showwarning = object()527 self.assertTrue(wmod.filters is orig_filters)528 self.assertTrue(wmod.showwarning is orig_showwarning)529 def test_catch_warnings_recording(self):530 wmod = self.module531 # Ensure warnings are recorded when requested532 with wmod.catch_warnings(module=wmod, record=True) as w:533 self.assertEqual(w, [])534 self.assertTrue(type(w) is list)535 wmod.simplefilter("always")536 wmod.warn("foo")537 self.assertEqual(str(w[-1].message), "foo")538 wmod.warn("bar")539 self.assertEqual(str(w[-1].message), "bar")540 self.assertEqual(str(w[0].message), "foo")541 self.assertEqual(str(w[1].message), "bar")542 del w[:]543 self.assertEqual(w, [])544 # Ensure warnings are not recorded when not requested545 orig_showwarning = wmod.showwarning546 with wmod.catch_warnings(module=wmod, record=False) as w:547 self.assertTrue(w is None)548 self.assertTrue(wmod.showwarning is orig_showwarning)549 def test_catch_warnings_reentry_guard(self):550 wmod = self.module551 # Ensure catch_warnings is protected against incorrect usage552 x = wmod.catch_warnings(module=wmod, record=True)553 self.assertRaises(RuntimeError, x.__exit__)554 with x:555 self.assertRaises(RuntimeError, x.__enter__)556 # Same test, but with recording disabled557 x = wmod.catch_warnings(module=wmod, record=False)558 self.assertRaises(RuntimeError, x.__exit__)559 with x:560 self.assertRaises(RuntimeError, x.__enter__)561 def test_catch_warnings_defaults(self):562 wmod = self.module563 orig_filters = wmod.filters564 orig_showwarning = wmod.showwarning565 # Ensure default behaviour is not to record warnings566 with wmod.catch_warnings(module=wmod) as w:567 self.assertTrue(w is None)568 self.assertTrue(wmod.showwarning is orig_showwarning)569 self.assertTrue(wmod.filters is not orig_filters)570 self.assertTrue(wmod.filters is orig_filters)571 if wmod is sys.modules['warnings']:572 # Ensure the default module is this one573 with wmod.catch_warnings() as w:574 self.assertTrue(w is None)575 self.assertTrue(wmod.showwarning is orig_showwarning)576 self.assertTrue(wmod.filters is not orig_filters)577 self.assertTrue(wmod.filters is orig_filters)578 def test_check_warnings(self):579 # Explicit tests for the test_support convenience wrapper580 wmod = self.module581 if wmod is not sys.modules['warnings']:582 return583 with test_support.check_warnings(quiet=False) as w:584 self.assertEqual(w.warnings, [])585 wmod.simplefilter("always")586 wmod.warn("foo")587 self.assertEqual(str(w.message), "foo")588 wmod.warn("bar")589 self.assertEqual(str(w.message), "bar")590 self.assertEqual(str(w.warnings[0].message), "foo")591 self.assertEqual(str(w.warnings[1].message), "bar")592 w.reset()593 self.assertEqual(w.warnings, [])594 with test_support.check_warnings():595 # defaults to quiet=True without argument596 pass597 with test_support.check_warnings(('foo', UserWarning)):598 wmod.warn("foo")599 with self.assertRaises(AssertionError):600 with test_support.check_warnings(('', RuntimeWarning)):601 # defaults to quiet=False with argument602 pass603 with self.assertRaises(AssertionError):604 with test_support.check_warnings(('foo', RuntimeWarning)):605 wmod.warn("foo")606class CCatchWarningTests(CatchWarningTests):607 module = c_warnings608class PyCatchWarningTests(CatchWarningTests):609 module = py_warnings610class EnvironmentVariableTests(BaseTest):611 def test_single_warning(self):612 newenv = os.environ.copy()613 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"614 p = subprocess.Popen([sys.executable,615 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],616 stdout=subprocess.PIPE, env=newenv)617 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")618 self.assertEqual(p.wait(), 0)619 def test_comma_separated_warnings(self):620 newenv = os.environ.copy()621 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"622 "ignore::UnicodeWarning")623 p = subprocess.Popen([sys.executable,624 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],625 stdout=subprocess.PIPE, env=newenv)...

Full Screen

Full Screen

reg.js

Source:reg.js Github

copy

Full Screen

1// JavaScript Document2$(document).ready(function(e) {3 $(".form-control").attr("data-placement","right").attr("data-toggle","popover").attr("data-html","true").attr("data-container","body").attr("data-trigger","manual").focus(function(e) {4 $(this).popover("hide");5 });;6 7 8 $("#username").blur(function(e) {9 warning_a = "<span style='color:#F60;'><span class='glyphicon glyphicon-remove-circle' style='color:#f00;'></span> <strong>";10 warning_b = "</strong></span>";11 username = $(this).val();12 username = username.replace(/(^\s*)|(\s*$)/g, "");13 if(username == ""){14 content = "用户名不能为空!";15 $(this).attr("data-content",warning_a+content+warning_b).popover("show");16 $("#tj").val(1);17 return false;18 }else{19 if(username.length < 4 || username.length >15){20 content = "用户名长度不能小于4个字符或大于15个字符!";21 $(this).attr("data-content",warning_a+content+warning_b).popover("show");22 $("#tj").val(1);23 return false;24 }else{25 var reg = /^(\w|[\u4E00-\u9FA5])*$/;26 arr=username.match(reg);27 if(!arr){28 content = "用户名只能是中文/英文/数字/下划线的组合";29 $(this).attr("data-content",warning_a+content+warning_b).popover("show");30 $("#tj").val(1);31 return false;32 }else{33 urlstr = $(this).attr("checkurl");34 datastr = "username="+username;35 ////////////////////////////////////////////////////////////////////////////////////36 $.ajax({37 type:'POST',38 url:urlstr,39 data:datastr,40 dataType:'text',41 success:function(str){42 ///////////////////////////////////43 if(str == "no"){44 content = "用户名已存在!";45 $("#username").attr("data-content",warning_a+content+warning_b).popover("show");46 $("#tj").val(1);47 return false;48 }else{49 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";50 $("#username").attr("data-content",success).popover("show");51 return false;52 }53 ///////////////////////////////////54 },55 error:function(XMLHttpRequest, textStatus, errorThrown) {56 //content = "判断用户名重复失败,请稍后再试!";57 // $("#username").attr("data-content",warning_a+content+warning_b).popover("show");58 $("#tj").val(1);59 return false;60 //////////////////////////61 } 62 });63 ///////////////////////////////////////////////////////////////////////////////////64 65 }66 }67 }68 });69 70 71 $("#password").blur(function(e) {72 warning_a = "<span style='color:#F60;'><span class='glyphicon glyphicon-remove-circle' style='color:#f00;'></span> <strong>";73 warning_b = "</strong></span>";74 password = $(this).val();75 password = password.replace(/(^\s*)|(\s*$)/g, "");76 if(password == ""){77 content = "密码不能为空!";78 $(this).attr("data-content",warning_a+content+warning_b).popover("show");79 $("#tj").val(1);80 return false;81 }else{82 if(password.length < 5){83 content = "密码不能小于5个字符!";84 $(this).attr("data-content",warning_a+content+warning_b).popover("show");85 $("#tj").val(1);86 return false;87 }else{88 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";89 $(this).attr("data-content",success).popover("show");90 return false;91 }92 }93 });94 95 96 $("#confirmpassword").blur(function(e) {97 warning_a = "<span style='color:#F60;'><span class='glyphicon glyphicon-remove-circle' style='color:#f00;'></span> <strong>";98 warning_b = "</strong></span>";99 confirmpassword = $(this).val();100 confirmpassword = confirmpassword.replace(/(^\s*)|(\s*$)/g, "");101 if(confirmpassword == ""){102 content = "密码不能为空!";103 $(this).attr("data-content",warning_a+content+warning_b).popover("show");104 $("#tj").val(1);105 return false;106 }else{107 if(confirmpassword.length < 5){108 content = "密码不能小于5个字符!";109 $(this).attr("data-content",warning_a+content+warning_b).popover("show");110 $("#tj").val(1);111 return false;112 }else{113 password = $("#password").val();114 password = password.replace(/(^\s*)|(\s*$)/g, "");115 if(confirmpassword != password){116 content = "两次密码输入不一致!";117 $(this).attr("data-content",warning_a+content+warning_b).popover("show");118 $("#tj").val(1);119 return false;120 }else{121 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";122 $(this).attr("data-content",success).popover("show");123 return false;124 }125 }126 }127 });128 129 130 $("#email").blur(function(e) {131 warning_a = "<span style='color:#F60;'><span class='glyphicon glyphicon-remove-circle' style='color:#f00;'></span> <strong>";132 warning_b = "</strong></span>";133 email = $(this).val();134 email = email.replace(/(^\s*)|(\s*$)/g, ""); 135 if(email == ""){136 content = "邮箱不能为空!";137 $(this).attr("data-content",warning_a+content+warning_b).popover("show");138 $("#tj").val(1);139 return false;140 }else{141 if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)){142 content = "邮箱格式错误 !";143 $(this).attr("data-content",warning_a+content+warning_b).popover("show");144 $("#tj").val(1);145 return false;146 }else{147 urlstr = $(this).attr("checkurl");148 //alert(urlstr);149 datastr = "email="+email;150 // alert(datastr);151 ////////////////////////////////////////////////////////////////////////////////////152 $.ajax({153 type:'POST',154 url:urlstr,155 data:datastr,156 dataType:'text',157 success:function(str){158 ///////////////////////////////////159 if(str == "no"){160 content = "邮箱已存在!";161 $("#email").attr("data-content",warning_a+content+warning_b).popover("show");162 $("#tj").val(1);163 return false;164 }else{165 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";166 $("#email").attr("data-content",success).popover("show");167 return false;168 }169 ///////////////////////////////////170 },171 error:function(XMLHttpRequest, textStatus, errorThrown) {172 // alert(XMLHttpRequest+"---"+textStatus+"---"+errorThrown);173 //content = "判断邮箱重复失败,请稍后再试!";174 // $("#email").attr("data-content",warning_a+content+warning_b).popover("show");175 $("#tj").val(1);176 return false;177 //////////////////////////178 } 179 });180 ///////////////////////////////////////////////////////////////////////////////////181 182 }183 }184 });185 186 $("#invitecode").blur(function(e) {187 warning_a = "<span style='color:#F60;'><span class='glyphicon glyphicon-remove-circle' style='color:#f00;'></span> <strong>";188 warning_b = "</strong></span>";189 invitecode = $(this).val();190 invitecode = invitecode.replace(/(^\s*)|(\s*$)/g, ""); 191 if(invitecode == ""){192 content = "邀请码不能为空!";193 $(this).attr("data-content",warning_a+content+warning_b).popover("show");194 $("#tj").val(1);195 return false;196 }else{197 urlstr = $(this).attr("checkurl");198 datastr = "invitecode="+invitecode;199 ////////////////////////////////////////////////////////////////////////////////////200 $.ajax({201 type:'POST',202 url:urlstr,203 data:datastr,204 dataType:'text',205 success:function(str){206 ///////////////////////////////////207 if(str == "no"){208 content = "邀请码不存在或不可用!";209 $("#invitecode").attr("data-content",warning_a+content+warning_b).popover("show");210 $("#tj").val(1);211 return false;212 }else{213 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";214 $("#invitecode").attr("data-content",success).popover("show");215 return false;216 }217 ///////////////////////////////////218 },219 error:function(XMLHttpRequest, textStatus, errorThrown) {220 //content = "系统加载失败,请稍后再试!";221 // $("#invitecode").attr("data-content",warning_a+content+warning_b).popover("show");222 $("#tj").val(1);223 return false;224 //////////////////////////225 } 226 });227 ///////////////////////////////////////////////////////////////////////////////////228 success = "<span class='glyphicon glyphicon-ok-circle' style='color:#0c0;'></span>";229 $(this).attr("data-content",success).popover("show");230 return false;231 }232 });233 234 235});236function check(mythis){237 $(mythis).button("loading");238 $("#username").blur();239 $("#password").blur();240 $("#confirmpassword").blur();241 $("#email").blur();242 $("#invitecode").blur();243 244 if($("#tj").val() == 1){245 $("#tj").val(0);246 // return false;247 }else{248 $("#Formreg").submit();249 }250 $(mythis).button("reset");...

Full Screen

Full Screen

registerVerify.js

Source:registerVerify.js Github

copy

Full Screen

1/*$(document).ready(function(){2 /**3 * 注册初级校验以及通过json向后台传数据 登录成功后跳转index.jsp界面4 * 注册失败在提示区域提示错误5 * @author 聂乐 2013-9-22 nele0716@1636 */7 /*$("#registerOK").click(function(){8 var tuserNameNode=$("#tuserNameRegister");9 var tpasswordNode=$("#tpasswordRegister");10 var tconfirmNode=$("#verifyCodeRegister");11 var userKindNode=$("#userKindRegister");12 var emailNode=$("#email");13 var majorNode=$("#major");14 15 var tuserName=tuserNameNode.val();16 var tpassword=tpasswordNode.val();17 var tconfirm=tconfirmNode.val();18 var userKind=userKindNode.val();19 var email=emailNode.val();20 var major=majorNode.val();21 22 23 var emailReg=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;24 25 if(tuserName==""){26 $("#warningRegister").text("用户名不能为空!请输入用户名!");27 return;28 }29 if(tpassword==""){30 $("#warningRegister").text("密码不能为空!请输入密码!");31 return;32 }33 if(tconfirm==""){34 $("#warningRegister").text("密码重复不能为空!请输入密码!");35 return;36 }37 if(email==""){38 $("#warningRegister").text("邮箱不能为空");39 return;40 }41 if(tpassword!=tconfirm){42 $("#warningRegister").text("两次输入密码不一致!");43 return;44 }45 46 if(!emailReg.test(email)){47 $("#warningRegister").text("邮箱格式不正确!");48 return;49 }50 51 $.ajax({52 type:"post",53 url:"register",54 dataType:"json",55 cache:false,56 data:{57 "teacher.tuserName":tuserName,58 "teacher.tpassword":tpassword,59 "teacher.email":email,60 "majorId":major,61 },62 success:function(data){63 window.location.href="index.jsp";64 },65 error:function(data){66 alert(data);67 }68 });69 });70 71 72 73 var xyNode=$("#xy");//得到major节点74 $.ajax({75 type:"post",76 url:"regissterShowXy",77 dataType:"json",78 cache:false,79 success:function(data){80 var result=eval("("+data+")");81 var options="";82 options+="<option value='0'>==请选择类型==</option>";83 for(var i=0;i<result.length;i++){84 options+="<option value="+result[i].xyId+">"+result[i].xyName+"</options>";85 }86 xyNode.html(options);87 },88 error:function(data){89 alert(data);90 },91 });*/92 93/*});*/94jQuery(function ($) {95 96 $("#suserName").blur(function(){97 var user_name_node=$("#suserName");98 if(user_name_node.val()==""){99 if( $("#input_user_warning").hasClass("input_or_select_correct")){100 $("#input_user_warning").removeClass("input_or_select_correct").addClass("input_error").text("请输入用户名"); 101 }102 else{103 $("#input_user_warning").removeClass("input_user_warning").addClass("input_error");104 }}105 else{106 $("#input_user_warning").removeClass("input_user_warning").addClass("input_or_select_correct");107 $("#input_user_warning").text("用户名正确!");108 suserNameIsRight=true;109 }110 });111 $("#register_tpassword").blur(function(){112 var password_node=$("#register_tpassword");113 if(password_node.val()==""){114 if($("#input_password_warning").hasClass("input_or_select_correct")){115 $("#input_password_warning").removeClass("input_or_select_correct").addClass("input_error").text("请输入密码");116 }117 else{118 $("#input_password_warning").removeClass("input_password_warning").addClass("input_error");119 }120 }else{121 $("#input_password_warning").removeClass("input_password_warning").addClass("input_or_select_correct");122 $("#input_password_warning").text("密码正确!");123 register_tpassword_isRight=true;124 }125 }); 126 127 128 $("#tpasswordConfirm").blur(function(){129 var password_node=$("#register_tpassword");130 var password_again_node=$("#tpasswordConfirm");131 if(password_again_node.val()==""){132 if($("#input_password_again_warning").hasClass("input_or_select_correct")){133 $("#input_password_again_warning").removeClass("input_or_select_correct").addClass("input_error").text("请再次输入密码");134 }135 else{136 $("#input_password_again_warning").removeClass("input_password_again_warning").addClass("input_error");137 }138 }139 else if(password_again_node.val()!=password_node.val()){140 if($("#input_password_again_warning").hasClass("input_or_select_correct")){141 $("#input_password_again_warning").removeClass("input_or_select_correct").addClass("input_error").text("两次密码不一致");142 }143 else if($("#input_password_again_warning").hasClass("input_password_again_warning")){144 $("#input_password_again_warning").removeClass("input_password_again_warning").addClass("input_error").text("两次密码不一致"); addClass("input_error").text("邮箱格式错");145 }146 else{147 $("#input_password_again_warning").text("两次密码不一致");148 } 149 150 }151 152 else {153 $("#input_password_again_warning").removeClass("input_password_again_warning").addClass("input_or_select_correct");154 $("#input_password_again_warning").text("密码重复正确!");155 tpasswordConfirm_isRight=true;156 }157 }); 158 159 160 $("#email").blur(function(){161 var email_node=$("#email");162 var email=email_node.val();163 var emailReg=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;164 165 if(email_node.val()==""){166 if($("#input_email_warning").hasClass("input_or_select_correct")){167 $("#input_email_warning").removeClass("input_or_select_correct").addClass("input_error").text("请输入邮箱");168 }169 else{170 $("#input_email_warning").removeClass("input_email_warning").addClass("input_error");171 }172 } 173 else if(!emailReg.test(email)){174 if($("#input_email_warning").hasClass("input_or_select_correct")){175 $("#input_email_warning").removeClass("input_or_select_correct").addClass("input_error").text("邮箱格式错");176 }177 else if($("#input_email_warning").hasClass("input_email_warning")){178 $("#input_email_warning").removeClass("input_email_warning").addClass("input_error").text("邮箱格式错"); addClass("input_error").text("邮箱格式错");179 }180 else{181 $("#input_email_warning").text("邮箱格式错");182 } 183 }184 185 else{186 $("#input_email_warning").removeClass("input_email_warning").addClass("input_or_select_correct");187 $("#input_email_warning").text("邮箱正确!");188 email_isRight=true;189 }190 });191 192 193 $("#register_verifyCode").blur(function() {194 var register_verify_code_node=$("#register_verifyCode");195 if(register_verify_code_node.val()==""){196 if($("#input_verifycode_warning").hasClass("input_verifycode_warning")){197 $("#input_verifycode_warning").removeClass("input_verifycode_warning").addClass("input_error");198 }199 }else{200 var verifyCode=register_verify_code_node.val();201 $.ajax({202 type:"post",203 url:"verifyCode",204 dataType:"json",205 cache:false,206 data:{207 "verifyCode":verifyCode208 },209 success:function(data){210 if(data=="验证码错误"){211 $("#input_verifycode_warning").html("验证码错误!");212 $("#input_verifycode_warning").removeClass().addClass("input_error"); 213 }else if(data=="验证码正确"){214 $("#input_verifycode_warning").html("验证码正确!");215 $("#input_verifycode_warning").removeClass().addClass("input_or_select_correct"); 216 register_verifyCode=true;217 }218 }219 });220 }221 222 });223 224 $("#register_submit_button").click(function(){225 var user_name_node=$("#suserName");226 var password_node=$("#register_tpassword");227 var password_node=$("#register_tpassword");228 var email_node=$("#email");229 var register_verify_code_node=$("#register_verifyCode");230 231 var user_name=user_name_node.val();232 });233});234 235 236/*237$("#cilickToRegister").click(function (e) {238 e.preventDefault();239 // example of calling the confirm function240 // you must use a callback function to perform the "yes" action241 confirm(function () {242 window.location.href = 'register.html';243 });244 });245});246function confirm(callback) {247 $('#confirm').modal({248 closeHTML: "<a href='#' title='Close' class='modal-close'>X</a>",249 position: ["20%",],250 overlayId: 'confirm-overlay',251 containerId: 'confirm-container', 252 onShow: function (dialog) {253 var modal = this;254 //$('.message', dialog.data[0]).append(message);255 // if the user clicks "yes"256 $('.yes', dialog.data[0]).click(function () {257 // call the callback258 if ($.isFunction(callback)) {259 callback.apply();260 }261 // close the dialog262 modal.close(); // or $.modal.close();263 });264 }265 });...

Full Screen

Full Screen

sensor.py

Source:sensor.py Github

copy

Full Screen

1"""2Support for getting statistical data from a DWD Weather Warnings.3Data is fetched from DWD:4https://rcccm.dwd.de/DE/wetter/warnungen_aktuell/objekt_einbindung/objekteinbindung.html5Warnungen vor extremem Unwetter (Stufe 4)6Unwetterwarnungen (Stufe 3)7Warnungen vor markantem Wetter (Stufe 2)8Wetterwarnungen (Stufe 1)9"""10from __future__ import annotations11from datetime import timedelta12import logging13from dwdwfsapi import DwdWeatherWarningsAPI14import voluptuous as vol15from homeassistant.components.sensor import (16 PLATFORM_SCHEMA,17 SensorEntity,18 SensorEntityDescription,19)20from homeassistant.const import ATTR_ATTRIBUTION, CONF_MONITORED_CONDITIONS, CONF_NAME21from homeassistant.core import HomeAssistant22import homeassistant.helpers.config_validation as cv23from homeassistant.helpers.entity_platform import AddEntitiesCallback24from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType25from homeassistant.util import Throttle26_LOGGER = logging.getLogger(__name__)27ATTRIBUTION = "Data provided by DWD"28ATTR_REGION_NAME = "region_name"29ATTR_REGION_ID = "region_id"30ATTR_LAST_UPDATE = "last_update"31ATTR_WARNING_COUNT = "warning_count"32API_ATTR_WARNING_NAME = "event"33API_ATTR_WARNING_TYPE = "event_code"34API_ATTR_WARNING_LEVEL = "level"35API_ATTR_WARNING_HEADLINE = "headline"36API_ATTR_WARNING_DESCRIPTION = "description"37API_ATTR_WARNING_INSTRUCTION = "instruction"38API_ATTR_WARNING_START = "start_time"39API_ATTR_WARNING_END = "end_time"40API_ATTR_WARNING_PARAMETERS = "parameters"41API_ATTR_WARNING_COLOR = "color"42DEFAULT_NAME = "DWD-Weather-Warnings"43CONF_REGION_NAME = "region_name"44CURRENT_WARNING_SENSOR = "current_warning_level"45ADVANCE_WARNING_SENSOR = "advance_warning_level"46SCAN_INTERVAL = timedelta(minutes=15)47SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (48 SensorEntityDescription(49 key=CURRENT_WARNING_SENSOR,50 name="Current Warning Level",51 icon="mdi:close-octagon-outline",52 ),53 SensorEntityDescription(54 key=ADVANCE_WARNING_SENSOR,55 name="Advance Warning Level",56 icon="mdi:close-octagon-outline",57 ),58)59MONITORED_CONDITIONS: list[str] = [desc.key for desc in SENSOR_TYPES]60PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(61 {62 vol.Required(CONF_REGION_NAME): cv.string,63 vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,64 vol.Optional(65 CONF_MONITORED_CONDITIONS, default=list(MONITORED_CONDITIONS)66 ): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]),67 }68)69def setup_platform(70 hass: HomeAssistant,71 config: ConfigType,72 add_entities: AddEntitiesCallback,73 discovery_info: DiscoveryInfoType | None = None,74) -> None:75 """Set up the DWD-Weather-Warnings sensor."""76 name = config.get(CONF_NAME)77 region_name = config.get(CONF_REGION_NAME)78 api = WrappedDwDWWAPI(DwdWeatherWarningsAPI(region_name))79 sensors = [80 DwdWeatherWarningsSensor(api, name, description)81 for description in SENSOR_TYPES82 if description.key in config[CONF_MONITORED_CONDITIONS]83 ]84 add_entities(sensors, True)85class DwdWeatherWarningsSensor(SensorEntity):86 """Representation of a DWD-Weather-Warnings sensor."""87 def __init__(88 self,89 api,90 name,91 description: SensorEntityDescription,92 ):93 """Initialize a DWD-Weather-Warnings sensor."""94 self._api = api95 self.entity_description = description96 self._attr_name = f"{name} {description.name}"97 @property98 def native_value(self):99 """Return the state of the device."""100 if self.entity_description.key == CURRENT_WARNING_SENSOR:101 return self._api.api.current_warning_level102 return self._api.api.expected_warning_level103 @property104 def extra_state_attributes(self):105 """Return the state attributes of the DWD-Weather-Warnings."""106 data = {107 ATTR_ATTRIBUTION: ATTRIBUTION,108 ATTR_REGION_NAME: self._api.api.warncell_name,109 ATTR_REGION_ID: self._api.api.warncell_id,110 ATTR_LAST_UPDATE: self._api.api.last_update,111 }112 if self.entity_description.key == CURRENT_WARNING_SENSOR:113 searched_warnings = self._api.api.current_warnings114 else:115 searched_warnings = self._api.api.expected_warnings116 data[ATTR_WARNING_COUNT] = len(searched_warnings)117 for i, warning in enumerate(searched_warnings, 1):118 data[f"warning_{i}_name"] = warning[API_ATTR_WARNING_NAME]119 data[f"warning_{i}_type"] = warning[API_ATTR_WARNING_TYPE]120 data[f"warning_{i}_level"] = warning[API_ATTR_WARNING_LEVEL]121 data[f"warning_{i}_headline"] = warning[API_ATTR_WARNING_HEADLINE]122 data[f"warning_{i}_description"] = warning[API_ATTR_WARNING_DESCRIPTION]123 data[f"warning_{i}_instruction"] = warning[API_ATTR_WARNING_INSTRUCTION]124 data[f"warning_{i}_start"] = warning[API_ATTR_WARNING_START]125 data[f"warning_{i}_end"] = warning[API_ATTR_WARNING_END]126 data[f"warning_{i}_parameters"] = warning[API_ATTR_WARNING_PARAMETERS]127 data[f"warning_{i}_color"] = warning[API_ATTR_WARNING_COLOR]128 # Dictionary for the attribute containing the complete warning129 warning_copy = warning.copy()130 warning_copy[API_ATTR_WARNING_START] = data[f"warning_{i}_start"]131 warning_copy[API_ATTR_WARNING_END] = data[f"warning_{i}_end"]132 data[f"warning_{i}"] = warning_copy133 return data134 @property135 def available(self):136 """Could the device be accessed during the last update call."""137 return self._api.api.data_valid138 def update(self):139 """Get the latest data from the DWD-Weather-Warnings API."""140 _LOGGER.debug(141 "Update requested for %s (%s) by %s",142 self._api.api.warncell_name,143 self._api.api.warncell_id,144 self.entity_description.key,145 )146 self._api.update()147class WrappedDwDWWAPI:148 """Wrapper for the DWD-Weather-Warnings api."""149 def __init__(self, api):150 """Initialize a DWD-Weather-Warnings wrapper."""151 self.api = api152 @Throttle(SCAN_INTERVAL)153 def update(self):154 """Get the latest data from the DWD-Weather-Warnings API."""155 self.api.update()...

Full Screen

Full Screen

warning.d.ts

Source:warning.d.ts Github

copy

Full Screen

1import Node from './node.js'2export interface WarningOptions {3 /**4 * CSS node that caused the warning.5 */6 node?: Node7 /**8 * Word in CSS source that caused the warning.9 */10 word?: string11 /**12 * Index in CSS node string that caused the warning.13 */14 index?: number15 /**16 * Name of the plugin that created this warning. `Result#warn` fills17 * this property automatically.18 */19 plugin?: string20}21/**22 * Represents a plugin’s warning. It can be created using `Node#warn`.23 *24 * ```js25 * if (decl.important) {26 * decl.warn(result, 'Avoid !important', { word: '!important' })27 * }28 * ```29 */30export default class Warning {31 /**32 * Type to filter warnings from `Result#messages`.33 * Always equal to `"warning"`.34 */35 type: 'warning'36 /**37 * The warning message.38 *39 * ```js40 * warning.text //=> 'Try to avoid !important'41 * ```42 */43 text: string44 /**45 * The name of the plugin that created this warning.46 * When you call `Node#warn` it will fill this property automatically.47 *48 * ```js49 * warning.plugin //=> 'postcss-important'50 * ```51 */52 plugin: string53 /**54 * Contains the CSS node that caused the warning.55 *56 * ```js57 * warning.node.toString() //=> 'color: white !important'58 * ```59 */60 node: Node61 /**62 * Line in the input file with this warning’s source.63 *64 * ```js65 * warning.line //=> 566 * ```67 */68 line: number69 /**70 * Column in the input file with this warning’s source.71 *72 * ```js73 * warning.column //=> 674 * ```75 */76 column: number77 /**78 * @param text Warning message.79 * @param opts Warning options.80 */81 constructor(text: string, opts?: WarningOptions)82 /**83 * Returns a warning position and message.84 *85 * ```js86 * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'87 * ```88 *89 * @return Warning position and message.90 */91 toString(): string...

Full Screen

Full Screen

ModuleWarning.js

Source:ModuleWarning.js Github

copy

Full Screen

1/*2 MIT License http://www.opensource.org/licenses/mit-license.php3 Author Tobias Koppers @sokra4*/5"use strict";6const { cleanUp } = require("./ErrorHelpers");7const WebpackError = require("./WebpackError");8const makeSerializable = require("./util/makeSerializable");9class ModuleWarning extends WebpackError {10 /**11 * @param {Error} warning error thrown12 * @param {{from?: string|null}} info additional info13 */14 constructor(warning, { from = null } = {}) {15 let message = "Module Warning";16 if (from) {17 message += ` (from ${from}):\n`;18 } else {19 message += ": ";20 }21 if (warning && typeof warning === "object" && warning.message) {22 message += warning.message;23 } else if (warning) {24 message += String(warning);25 }26 super(message);27 this.name = "ModuleWarning";28 this.warning = warning;29 this.details =30 warning && typeof warning === "object" && warning.stack31 ? cleanUp(warning.stack, this.message)32 : undefined;33 }34 serialize(context) {35 const { write } = context;36 write(this.warning);37 super.serialize(context);38 }39 deserialize(context) {40 const { read } = context;41 this.warning = read();42 super.deserialize(context);43 }44}45makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning");...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { warning } from 'storybook-root-decorator';2import { error } from 'storybook-root-decorator';3import { info } from 'storybook-root-decorator';4import { success } from 'storybook-root-decorator';5import { warn } from 'storybook-root-decorator';6import { log } from 'storybook-root-decorator';7import { debug } from 'storybook-root-decorator';8import { trace } from 'storybook-root-decorator';9import { clear } from 'storybook-root-decorator';10import { dir } from 'storybook-root-decorator';11import { table } from 'storybook-root-decorator';12import { group } from 'storybook-root-decorator';13import { groupCollapsed } from 'storybook-root-decorator';14import { groupEnd } from 'storybook-root-decorator';15import { time } from 'storybook-root-decorator';16import { timeEnd } from 'storybook-root-decorator';17import { count } from 'storybook-root-decorator';18import { countReset } from 'storybook-root-decorator';19import { assert } from 'storybook-root-decorator';

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { withInfo } from '@storybook/addon-info';4import { withWarning } from 'storybook-root-decorator';5storiesOf('Button', module)6 .addDecorator(withInfo)7 .addDecorator(withWarning)8 .add('with text', () => <button>Click me</button>);9import { configure } from '@storybook/react';10import { setOptions } from '@storybook/addon-options';11import { setDefaults } from 'storybook-root-decorator';12setOptions({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { warning } from 'storybook-root-decorator';2import { warning } from 'storybook-addon-root-decorator';3import { addDecorator, configure } from '@storybook/react';4import { withRootDecorator } from 'storybook-root-decorator';5import { withRootDecorator } from 'storybook-addon-root-decorator';6addDecorator(withRootDecorator);7configure(require.context('../src', true, /\.stories\.js$/), module);8import 'storybook-root-decorator/register';9import 'storybook-addon-root-decorator/register';10import React from 'react';11import { storiesOf } from '@storybook/react';12import Button from '../src/components/Button';13storiesOf('Button', module)14 .add('with text', () => (15 <Button onClick={() => {}}>Hello Button</Button>16 .add('with some emoji', () => (17 <Button onClick={() => {}}>😀 😎 👍 💯</Button>18 ));19MIT © [Rajeshwar Patlolla](

Full Screen

Using AI Code Generation

copy

Full Screen

1import { warning } from 'storybook-root-decorator';2warning('This is a warning');3import { configure } from '@storybook/react';4import { addDecorator, addParameters } from '@storybook/react';5import { withRootDecorator } from 'storybook-root-decorator';6import { withInfo } from '@storybook/addon-info';7import { withKnobs } from '@storybook/addon-knobs';8import { withA11y } from '@storybook/addon-a11y';9addDecorator(withRootDecorator);10addDecorator(withInfo);11addDecorator(withKnobs);12addDecorator(withA11y);13addParameters({14 info: {15 },16});17configure(require.context('../src', true, /\.stories\.js$/), module);18export const parameters = {19 actions: { argTypesRegex: "^on[A-Z].*" },20};21import { addons } from '@storybook/addons';22import { themes } from '@storybook/theming';23addons.setConfig({24});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { warning } from 'storybook-root-decorator';2warning('This is a warning');3import 'storybook-root-decorator';4import 'storybook-root-decorator/register';5import 'storybook-root-decorator/preview';6import 'storybook-root-decorator/manager';7import 'storybook-root-decorator/webpack';8import 'storybook-root-decorator/babel';9import 'storybook-root-decorator/tsconfig';10import 'storybook-root-decorator/typings';11import { warning } from 'storybook-root-decorator';12warning('This is a warning');13import { preview } from 'storybook-root-decorator';14preview((storyFn, context) => {15 return <div className="custom-decorator">{storyFn(context)}</div>;16});17import { manager } from 'storybook-root-decorator';18manager((storyFn, context) => {19 return <div className="custom-decorator">{storyFn(context)}</div>;20});21import { webpack } from 'storybook-root-decorator';22webpack((config) => {23 return {24 module: {25 {26 },27 },28 };29});30import { babel } from 'storybook-root-decorator';31babel((config) => {32 return {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { warning } from 'storybook-root-decorator';2const Component = ({ name }) => {3 warning('This is a warning');4 return <div>Hello {name}</div>;5};6export default Component;7import { addDecorator } from '@storybook/react';8import withRootDecorator from 'storybook-root-decorator';9import { withInfo } from '@storybook/addon-info';10addDecorator(withInfo);11addDecorator(withRootDecorator);

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 storybook-root 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