How to use ordered method in storybook-root

Best JavaScript code snippet using storybook-root

test_ordered_dict.py

Source:test_ordered_dict.py Github

copy

Full Screen

1import builtins2import contextlib3import copy4import gc5import pickle6from random import randrange, shuffle7import struct8import sys9import unittest10import weakref11from collections.abc import MutableMapping12from test import mapping_tests, support13py_coll = support.import_fresh_module('collections', blocked=['_collections'])14c_coll = support.import_fresh_module('collections', fresh=['_collections'])15@contextlib.contextmanager16def replaced_module(name, replacement):17 original_module = sys.modules[name]18 sys.modules[name] = replacement19 try:20 yield21 finally:22 sys.modules[name] = original_module23class OrderedDictTests:24 def test_init(self):25 OrderedDict = self.OrderedDict26 with self.assertRaises(TypeError):27 OrderedDict([('a', 1), ('b', 2)], None) # too many args28 pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]29 self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input30 self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input31 self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input32 self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)],33 c=3, e=5).items()), pairs) # mixed input34 # make sure no positional args conflict with possible kwdargs35 self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])36 self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])37 self.assertRaises(TypeError, OrderedDict, 42)38 self.assertRaises(TypeError, OrderedDict, (), ())39 self.assertRaises(TypeError, OrderedDict.__init__)40 # Make sure that direct calls to __init__ do not clear previous contents41 d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])42 d.__init__([('e', 5), ('f', 6)], g=7, d=4)43 self.assertEqual(list(d.items()),44 [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])45 def test_468(self):46 OrderedDict = self.OrderedDict47 items = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]48 shuffle(items)49 argdict = OrderedDict(items)50 d = OrderedDict(**argdict)51 self.assertEqual(list(d.items()), items)52 def test_update(self):53 OrderedDict = self.OrderedDict54 with self.assertRaises(TypeError):55 OrderedDict().update([('a', 1), ('b', 2)], None) # too many args56 pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]57 od = OrderedDict()58 od.update(dict(pairs))59 self.assertEqual(sorted(od.items()), pairs) # dict input60 od = OrderedDict()61 od.update(**dict(pairs))62 self.assertEqual(sorted(od.items()), pairs) # kwds input63 od = OrderedDict()64 od.update(pairs)65 self.assertEqual(list(od.items()), pairs) # pairs input66 od = OrderedDict()67 od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5)68 self.assertEqual(list(od.items()), pairs) # mixed input69 # Issue 9137: Named argument called 'other' or 'self'70 # shouldn't be treated specially.71 od = OrderedDict()72 od.update(self=23)73 self.assertEqual(list(od.items()), [('self', 23)])74 od = OrderedDict()75 od.update(other={})76 self.assertEqual(list(od.items()), [('other', {})])77 od = OrderedDict()78 od.update(red=5, blue=6, other=7, self=8)79 self.assertEqual(sorted(list(od.items())),80 [('blue', 6), ('other', 7), ('red', 5), ('self', 8)])81 # Make sure that direct calls to update do not clear previous contents82 # add that updates items are not moved to the end83 d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])84 d.update([('e', 5), ('f', 6)], g=7, d=4)85 self.assertEqual(list(d.items()),86 [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])87 self.assertRaises(TypeError, OrderedDict().update, 42)88 self.assertRaises(TypeError, OrderedDict().update, (), ())89 self.assertRaises(TypeError, OrderedDict.update)90 self.assertRaises(TypeError, OrderedDict().update, 42)91 self.assertRaises(TypeError, OrderedDict().update, (), ())92 self.assertRaises(TypeError, OrderedDict.update)93 def test_init_calls(self):94 calls = []95 class Spam:96 def keys(self):97 calls.append('keys')98 return ()99 def items(self):100 calls.append('items')101 return ()102 self.OrderedDict(Spam())103 self.assertEqual(calls, ['keys'])104 def test_fromkeys(self):105 OrderedDict = self.OrderedDict106 od = OrderedDict.fromkeys('abc')107 self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])108 od = OrderedDict.fromkeys('abc', value=None)109 self.assertEqual(list(od.items()), [(c, None) for c in 'abc'])110 od = OrderedDict.fromkeys('abc', value=0)111 self.assertEqual(list(od.items()), [(c, 0) for c in 'abc'])112 def test_abc(self):113 OrderedDict = self.OrderedDict114 self.assertIsInstance(OrderedDict(), MutableMapping)115 self.assertTrue(issubclass(OrderedDict, MutableMapping))116 def test_clear(self):117 OrderedDict = self.OrderedDict118 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]119 shuffle(pairs)120 od = OrderedDict(pairs)121 self.assertEqual(len(od), len(pairs))122 od.clear()123 self.assertEqual(len(od), 0)124 def test_delitem(self):125 OrderedDict = self.OrderedDict126 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]127 od = OrderedDict(pairs)128 del od['a']129 self.assertNotIn('a', od)130 with self.assertRaises(KeyError):131 del od['a']132 self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])133 def test_setitem(self):134 OrderedDict = self.OrderedDict135 od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)])136 od['c'] = 10 # existing element137 od['f'] = 20 # new element138 self.assertEqual(list(od.items()),139 [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)])140 def test_iterators(self):141 OrderedDict = self.OrderedDict142 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]143 shuffle(pairs)144 od = OrderedDict(pairs)145 self.assertEqual(list(od), [t[0] for t in pairs])146 self.assertEqual(list(od.keys()), [t[0] for t in pairs])147 self.assertEqual(list(od.values()), [t[1] for t in pairs])148 self.assertEqual(list(od.items()), pairs)149 self.assertEqual(list(reversed(od)),150 [t[0] for t in reversed(pairs)])151 self.assertEqual(list(reversed(od.keys())),152 [t[0] for t in reversed(pairs)])153 self.assertEqual(list(reversed(od.values())),154 [t[1] for t in reversed(pairs)])155 self.assertEqual(list(reversed(od.items())), list(reversed(pairs)))156 def test_detect_deletion_during_iteration(self):157 OrderedDict = self.OrderedDict158 od = OrderedDict.fromkeys('abc')159 it = iter(od)160 key = next(it)161 del od[key]162 with self.assertRaises(Exception):163 # Note, the exact exception raised is not guaranteed164 # The only guarantee that the next() will not succeed165 next(it)166 def test_sorted_iterators(self):167 OrderedDict = self.OrderedDict168 with self.assertRaises(TypeError):169 OrderedDict([('a', 1), ('b', 2)], None)170 pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]171 od = OrderedDict(pairs)172 self.assertEqual(sorted(od), [t[0] for t in pairs])173 self.assertEqual(sorted(od.keys()), [t[0] for t in pairs])174 self.assertEqual(sorted(od.values()), [t[1] for t in pairs])175 self.assertEqual(sorted(od.items()), pairs)176 self.assertEqual(sorted(reversed(od)),177 sorted([t[0] for t in reversed(pairs)]))178 def test_iterators_empty(self):179 OrderedDict = self.OrderedDict180 od = OrderedDict()181 empty = []182 self.assertEqual(list(od), empty)183 self.assertEqual(list(od.keys()), empty)184 self.assertEqual(list(od.values()), empty)185 self.assertEqual(list(od.items()), empty)186 self.assertEqual(list(reversed(od)), empty)187 self.assertEqual(list(reversed(od.keys())), empty)188 self.assertEqual(list(reversed(od.values())), empty)189 self.assertEqual(list(reversed(od.items())), empty)190 def test_popitem(self):191 OrderedDict = self.OrderedDict192 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]193 shuffle(pairs)194 od = OrderedDict(pairs)195 while pairs:196 self.assertEqual(od.popitem(), pairs.pop())197 with self.assertRaises(KeyError):198 od.popitem()199 self.assertEqual(len(od), 0)200 def test_popitem_last(self):201 OrderedDict = self.OrderedDict202 pairs = [(i, i) for i in range(30)]203 obj = OrderedDict(pairs)204 for i in range(8):205 obj.popitem(True)206 obj.popitem(True)207 obj.popitem(last=True)208 self.assertEqual(len(obj), 20)209 def test_pop(self):210 OrderedDict = self.OrderedDict211 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]212 shuffle(pairs)213 od = OrderedDict(pairs)214 shuffle(pairs)215 while pairs:216 k, v = pairs.pop()217 self.assertEqual(od.pop(k), v)218 with self.assertRaises(KeyError):219 od.pop('xyz')220 self.assertEqual(len(od), 0)221 self.assertEqual(od.pop(k, 12345), 12345)222 # make sure pop still works when __missing__ is defined223 class Missing(OrderedDict):224 def __missing__(self, key):225 return 0226 m = Missing(a=1)227 self.assertEqual(m.pop('b', 5), 5)228 self.assertEqual(m.pop('a', 6), 1)229 self.assertEqual(m.pop('a', 6), 6)230 self.assertEqual(m.pop('a', default=6), 6)231 with self.assertRaises(KeyError):232 m.pop('a')233 def test_equality(self):234 OrderedDict = self.OrderedDict235 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]236 shuffle(pairs)237 od1 = OrderedDict(pairs)238 od2 = OrderedDict(pairs)239 self.assertEqual(od1, od2) # same order implies equality240 pairs = pairs[2:] + pairs[:2]241 od2 = OrderedDict(pairs)242 self.assertNotEqual(od1, od2) # different order implies inequality243 # comparison to regular dict is not order sensitive244 self.assertEqual(od1, dict(od2))245 self.assertEqual(dict(od2), od1)246 # different length implied inequality247 self.assertNotEqual(od1, OrderedDict(pairs[:-1]))248 def test_copying(self):249 OrderedDict = self.OrderedDict250 # Check that ordered dicts are copyable, deepcopyable, picklable,251 # and have a repr/eval round-trip252 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]253 od = OrderedDict(pairs)254 def check(dup):255 msg = "\ncopy: %s\nod: %s" % (dup, od)256 self.assertIsNot(dup, od, msg)257 self.assertEqual(dup, od)258 self.assertEqual(list(dup.items()), list(od.items()))259 self.assertEqual(len(dup), len(od))260 self.assertEqual(type(dup), type(od))261 check(od.copy())262 check(copy.copy(od))263 check(copy.deepcopy(od))264 # pickle directly pulls the module, so we have to fake it265 with replaced_module('collections', self.module):266 for proto in range(pickle.HIGHEST_PROTOCOL + 1):267 with self.subTest(proto=proto):268 check(pickle.loads(pickle.dumps(od, proto)))269 check(eval(repr(od)))270 update_test = OrderedDict()271 update_test.update(od)272 check(update_test)273 check(OrderedDict(od))274 def test_yaml_linkage(self):275 OrderedDict = self.OrderedDict276 # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.277 # In yaml, lists are native but tuples are not.278 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]279 od = OrderedDict(pairs)280 # yaml.dump(od) -->281 # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n'282 self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))283 def test_reduce_not_too_fat(self):284 OrderedDict = self.OrderedDict285 # do not save instance dictionary if not needed286 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]287 od = OrderedDict(pairs)288 self.assertIsInstance(od.__dict__, dict)289 self.assertIsNone(od.__reduce__()[2])290 od.x = 10291 self.assertEqual(od.__dict__['x'], 10)292 self.assertEqual(od.__reduce__()[2], {'x': 10})293 def test_pickle_recursive(self):294 OrderedDict = self.OrderedDict295 od = OrderedDict()296 od[1] = od297 # pickle directly pulls the module, so we have to fake it298 with replaced_module('collections', self.module):299 for proto in range(-1, pickle.HIGHEST_PROTOCOL + 1):300 dup = pickle.loads(pickle.dumps(od, proto))301 self.assertIsNot(dup, od)302 self.assertEqual(list(dup.keys()), [1])303 self.assertIs(dup[1], dup)304 def test_repr(self):305 OrderedDict = self.OrderedDict306 od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])307 self.assertEqual(repr(od),308 "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])")309 self.assertEqual(eval(repr(od)), od)310 self.assertEqual(repr(OrderedDict()), "OrderedDict()")311 def test_repr_recursive(self):312 OrderedDict = self.OrderedDict313 # See issue #9826314 od = OrderedDict.fromkeys('abc')315 od['x'] = od316 self.assertEqual(repr(od),317 "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])")318 def test_repr_recursive_values(self):319 OrderedDict = self.OrderedDict320 od = OrderedDict()321 od[42] = od.values()322 r = repr(od)323 # Cannot perform a stronger test, as the contents of the repr324 # are implementation-dependent. All we can say is that we325 # want a str result, not an exception of any sort.326 self.assertIsInstance(r, str)327 od[42] = od.items()328 r = repr(od)329 # Again.330 self.assertIsInstance(r, str)331 def test_setdefault(self):332 OrderedDict = self.OrderedDict333 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]334 shuffle(pairs)335 od = OrderedDict(pairs)336 pair_order = list(od.items())337 self.assertEqual(od.setdefault('a', 10), 3)338 # make sure order didn't change339 self.assertEqual(list(od.items()), pair_order)340 self.assertEqual(od.setdefault('x', 10), 10)341 # make sure 'x' is added to the end342 self.assertEqual(list(od.items())[-1], ('x', 10))343 self.assertEqual(od.setdefault('g', default=9), 9)344 # make sure setdefault still works when __missing__ is defined345 class Missing(OrderedDict):346 def __missing__(self, key):347 return 0348 self.assertEqual(Missing().setdefault(5, 9), 9)349 def test_reinsert(self):350 OrderedDict = self.OrderedDict351 # Given insert a, insert b, delete a, re-insert a,352 # verify that a is now later than b.353 od = OrderedDict()354 od['a'] = 1355 od['b'] = 2356 del od['a']357 self.assertEqual(list(od.items()), [('b', 2)])358 od['a'] = 1359 self.assertEqual(list(od.items()), [('b', 2), ('a', 1)])360 def test_move_to_end(self):361 OrderedDict = self.OrderedDict362 od = OrderedDict.fromkeys('abcde')363 self.assertEqual(list(od), list('abcde'))364 od.move_to_end('c')365 self.assertEqual(list(od), list('abdec'))366 od.move_to_end('c', 0)367 self.assertEqual(list(od), list('cabde'))368 od.move_to_end('c', 0)369 self.assertEqual(list(od), list('cabde'))370 od.move_to_end('e')371 self.assertEqual(list(od), list('cabde'))372 od.move_to_end('b', last=False)373 self.assertEqual(list(od), list('bcade'))374 with self.assertRaises(KeyError):375 od.move_to_end('x')376 with self.assertRaises(KeyError):377 od.move_to_end('x', 0)378 def test_move_to_end_issue25406(self):379 OrderedDict = self.OrderedDict380 od = OrderedDict.fromkeys('abc')381 od.move_to_end('c', last=False)382 self.assertEqual(list(od), list('cab'))383 od.move_to_end('a', last=False)384 self.assertEqual(list(od), list('acb'))385 od = OrderedDict.fromkeys('abc')386 od.move_to_end('a')387 self.assertEqual(list(od), list('bca'))388 od.move_to_end('c')389 self.assertEqual(list(od), list('bac'))390 def test_sizeof(self):391 OrderedDict = self.OrderedDict392 # Wimpy test: Just verify the reported size is larger than a regular dict393 d = dict(a=1)394 od = OrderedDict(**d)395 self.assertGreater(sys.getsizeof(od), sys.getsizeof(d))396 def test_views(self):397 OrderedDict = self.OrderedDict398 # See http://bugs.python.org/issue24286399 s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split()400 od = OrderedDict.fromkeys(s)401 self.assertEqual(od.keys(), dict(od).keys())402 self.assertEqual(od.items(), dict(od).items())403 def test_override_update(self):404 OrderedDict = self.OrderedDict405 # Verify that subclasses can override update() without breaking __init__()406 class MyOD(OrderedDict):407 def update(self, *args, **kwds):408 raise Exception()409 items = [('a', 1), ('c', 3), ('b', 2)]410 self.assertEqual(list(MyOD(items).items()), items)411 def test_highly_nested(self):412 # Issue 25395: crashes during garbage collection413 OrderedDict = self.OrderedDict414 obj = None415 for _ in range(1000):416 obj = OrderedDict([(None, obj)])417 del obj418 support.gc_collect()419 def test_highly_nested_subclass(self):420 # Issue 25395: crashes during garbage collection421 OrderedDict = self.OrderedDict422 deleted = []423 class MyOD(OrderedDict):424 def __del__(self):425 deleted.append(self.i)426 obj = None427 for i in range(100):428 obj = MyOD([(None, obj)])429 obj.i = i430 del obj431 support.gc_collect()432 self.assertEqual(deleted, list(reversed(range(100))))433 def test_delitem_hash_collision(self):434 OrderedDict = self.OrderedDict435 class Key:436 def __init__(self, hash):437 self._hash = hash438 self.value = str(id(self))439 def __hash__(self):440 return self._hash441 def __eq__(self, other):442 try:443 return self.value == other.value444 except AttributeError:445 return False446 def __repr__(self):447 return self.value448 def blocking_hash(hash):449 # See the collision-handling in lookdict (in Objects/dictobject.c).450 MINSIZE = 8451 i = (hash & MINSIZE-1)452 return (i << 2) + i + hash + 1453 COLLIDING = 1454 key = Key(COLLIDING)455 colliding = Key(COLLIDING)456 blocking = Key(blocking_hash(COLLIDING))457 od = OrderedDict()458 od[key] = ...459 od[blocking] = ...460 od[colliding] = ...461 od['after'] = ...462 del od[blocking]463 del od[colliding]464 self.assertEqual(list(od.items()), [(key, ...), ('after', ...)])465 def test_issue24347(self):466 OrderedDict = self.OrderedDict467 class Key:468 def __hash__(self):469 return randrange(100000)470 od = OrderedDict()471 for i in range(100):472 key = Key()473 od[key] = i474 # These should not crash.475 with self.assertRaises(KeyError):476 list(od.values())477 with self.assertRaises(KeyError):478 list(od.items())479 with self.assertRaises(KeyError):480 repr(od)481 with self.assertRaises(KeyError):482 od.copy()483 def test_issue24348(self):484 OrderedDict = self.OrderedDict485 class Key:486 def __hash__(self):487 return 1488 od = OrderedDict()489 od[Key()] = 0490 # This should not crash.491 od.popitem()492 def test_issue24667(self):493 """494 dict resizes after a certain number of insertion operations,495 whether or not there were deletions that freed up slots in the496 hash table. During fast node lookup, OrderedDict must correctly497 respond to all resizes, even if the current "size" is the same498 as the old one. We verify that here by forcing a dict resize499 on a sparse odict and then perform an operation that should500 trigger an odict resize (e.g. popitem). One key aspect here is501 that we will keep the size of the odict the same at each popitem502 call. This verifies that we handled the dict resize properly.503 """504 OrderedDict = self.OrderedDict505 od = OrderedDict()506 for c0 in '0123456789ABCDEF':507 for c1 in '0123456789ABCDEF':508 if len(od) == 4:509 # This should not raise a KeyError.510 od.popitem(last=False)511 key = c0 + c1512 od[key] = key513 # Direct use of dict methods514 def test_dict_setitem(self):515 OrderedDict = self.OrderedDict516 od = OrderedDict()517 dict.__setitem__(od, 'spam', 1)518 self.assertNotIn('NULL', repr(od))519 def test_dict_delitem(self):520 OrderedDict = self.OrderedDict521 od = OrderedDict()522 od['spam'] = 1523 od['ham'] = 2524 dict.__delitem__(od, 'spam')525 with self.assertRaises(KeyError):526 repr(od)527 def test_dict_clear(self):528 OrderedDict = self.OrderedDict529 od = OrderedDict()530 od['spam'] = 1531 od['ham'] = 2532 dict.clear(od)533 self.assertNotIn('NULL', repr(od))534 def test_dict_pop(self):535 OrderedDict = self.OrderedDict536 od = OrderedDict()537 od['spam'] = 1538 od['ham'] = 2539 dict.pop(od, 'spam')540 with self.assertRaises(KeyError):541 repr(od)542 def test_dict_popitem(self):543 OrderedDict = self.OrderedDict544 od = OrderedDict()545 od['spam'] = 1546 od['ham'] = 2547 dict.popitem(od)548 with self.assertRaises(KeyError):549 repr(od)550 def test_dict_setdefault(self):551 OrderedDict = self.OrderedDict552 od = OrderedDict()553 dict.setdefault(od, 'spam', 1)554 self.assertNotIn('NULL', repr(od))555 def test_dict_update(self):556 OrderedDict = self.OrderedDict557 od = OrderedDict()558 dict.update(od, [('spam', 1)])559 self.assertNotIn('NULL', repr(od))560 def test_reference_loop(self):561 # Issue 25935562 OrderedDict = self.OrderedDict563 class A:564 od = OrderedDict()565 A.od[A] = None566 r = weakref.ref(A)567 del A568 gc.collect()569 self.assertIsNone(r())570 def test_free_after_iterating(self):571 support.check_free_after_iterating(self, iter, self.OrderedDict)572 support.check_free_after_iterating(self, lambda d: iter(d.keys()), self.OrderedDict)573 support.check_free_after_iterating(self, lambda d: iter(d.values()), self.OrderedDict)574 support.check_free_after_iterating(self, lambda d: iter(d.items()), self.OrderedDict)575class PurePythonOrderedDictTests(OrderedDictTests, unittest.TestCase):576 module = py_coll577 OrderedDict = py_coll.OrderedDict578class CPythonBuiltinDictTests(unittest.TestCase):579 """Builtin dict preserves insertion order.580 Reuse some of tests in OrderedDict selectively.581 """582 module = builtins583 OrderedDict = dict584for method in (585 "test_init test_update test_abc test_clear test_delitem " +586 "test_setitem test_detect_deletion_during_iteration " +587 "test_popitem test_reinsert test_override_update " +588 "test_highly_nested test_highly_nested_subclass " +589 "test_delitem_hash_collision ").split():590 setattr(CPythonBuiltinDictTests, method, getattr(OrderedDictTests, method))591del method592@unittest.skipUnless(c_coll, 'requires the C version of the collections module')593class CPythonOrderedDictTests(OrderedDictTests, unittest.TestCase):594 module = c_coll595 OrderedDict = c_coll.OrderedDict596 check_sizeof = support.check_sizeof597 @support.cpython_only598 def test_sizeof_exact(self):599 OrderedDict = self.OrderedDict600 calcsize = struct.calcsize601 size = support.calcobjsize602 check = self.check_sizeof603 basicsize = size('nQ2P' + '3PnPn2P') + calcsize('2nP2n')604 entrysize = calcsize('n2P')605 p = calcsize('P')606 nodesize = calcsize('Pn2P')607 od = OrderedDict()608 check(od, basicsize + 8 + 5*entrysize) # 8byte indices + 8*2//3 * entry table609 od.x = 1610 check(od, basicsize + 8 + 5*entrysize)611 od.update([(i, i) for i in range(3)])612 check(od, basicsize + 8*p + 8 + 5*entrysize + 3*nodesize)613 od.update([(i, i) for i in range(3, 10)])614 check(od, basicsize + 16*p + 16 + 10*entrysize + 10*nodesize)615 check(od.keys(), size('P'))616 check(od.items(), size('P'))617 check(od.values(), size('P'))618 itersize = size('iP2n2P')619 check(iter(od), itersize)620 check(iter(od.keys()), itersize)621 check(iter(od.items()), itersize)622 check(iter(od.values()), itersize)623 def test_key_change_during_iteration(self):624 OrderedDict = self.OrderedDict625 od = OrderedDict.fromkeys('abcde')626 self.assertEqual(list(od), list('abcde'))627 with self.assertRaises(RuntimeError):628 for i, k in enumerate(od):629 od.move_to_end(k)630 self.assertLess(i, 5)631 with self.assertRaises(RuntimeError):632 for k in od:633 od['f'] = None634 with self.assertRaises(RuntimeError):635 for k in od:636 del od['c']637 self.assertEqual(list(od), list('bdeaf'))638 def test_iterators_pickling(self):639 OrderedDict = self.OrderedDict640 pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]641 od = OrderedDict(pairs)642 for method_name in ('keys', 'values', 'items'):643 meth = getattr(od, method_name)644 expected = list(meth())[1:]645 for i in range(pickle.HIGHEST_PROTOCOL + 1):646 with self.subTest(method_name=method_name, protocol=i):647 it = iter(meth())648 next(it)649 p = pickle.dumps(it, i)650 unpickled = pickle.loads(p)651 self.assertEqual(list(unpickled), expected)652 self.assertEqual(list(it), expected)653 @support.cpython_only654 def test_weakref_list_is_not_traversed(self):655 # Check that the weakref list is not traversed when collecting656 # OrderedDict objects. See bpo-39778 for more information.657 gc.collect()658 x = self.OrderedDict()659 x.cycle = x660 cycle = []661 cycle.append(cycle)662 x_ref = weakref.ref(x)663 cycle.append(x_ref)664 del x, cycle, x_ref665 gc.collect()666class PurePythonOrderedDictSubclassTests(PurePythonOrderedDictTests):667 module = py_coll668 class OrderedDict(py_coll.OrderedDict):669 pass670class CPythonOrderedDictSubclassTests(CPythonOrderedDictTests):671 module = c_coll672 class OrderedDict(c_coll.OrderedDict):673 pass674class PurePythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):675 @classmethod676 def setUpClass(cls):677 cls.type2test = py_coll.OrderedDict678 def test_popitem(self):679 d = self._empty_mapping()680 self.assertRaises(KeyError, d.popitem)681@unittest.skipUnless(c_coll, 'requires the C version of the collections module')682class CPythonGeneralMappingTests(mapping_tests.BasicTestMappingProtocol):683 @classmethod684 def setUpClass(cls):685 cls.type2test = c_coll.OrderedDict686 def test_popitem(self):687 d = self._empty_mapping()688 self.assertRaises(KeyError, d.popitem)689class PurePythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):690 @classmethod691 def setUpClass(cls):692 class MyOrderedDict(py_coll.OrderedDict):693 pass694 cls.type2test = MyOrderedDict695 def test_popitem(self):696 d = self._empty_mapping()697 self.assertRaises(KeyError, d.popitem)698@unittest.skipUnless(c_coll, 'requires the C version of the collections module')699class CPythonSubclassMappingTests(mapping_tests.BasicTestMappingProtocol):700 @classmethod701 def setUpClass(cls):702 class MyOrderedDict(c_coll.OrderedDict):703 pass704 cls.type2test = MyOrderedDict705 def test_popitem(self):706 d = self._empty_mapping()707 self.assertRaises(KeyError, d.popitem)708if __name__ == "__main__":...

Full Screen

Full Screen

adminPanelReducer.js

Source:adminPanelReducer.js Github

copy

Full Screen

1/* eslint-disable no-unused-vars */2/* eslint-disable no-redeclare */3import { GET_USERS, FILTER_BY_EMAIL, FILTER_BY_NAME, FILTER_BY_ID } from '../actions/index';4import { ORDER_BY_GAMES_ASC, ORDER_BY_GAMES_DESC, ORDER_BY_WINS_ASC, ORDER_BY_WINS_DESC } from '../actions/index';5import {6 ORDER_BY_LOST_ASC, ORDER_BY_LOST_DESC, GO_TO_N_PAGE, SET_SELECTED_PAGE, SET_USERS_PER_PAGE, SET_TOTAL_PAGES, SET_DISPLAYED_ON_PAGE,7 ORDER_BY_USER_SINCE_ASC, ORDER_BY_USER_SINCE_DESC,8 BAN_USER, SUSPEND_USER, ACTIVATE_USER9} from '../actions/index';10import comparers from './helpers/comparers';11import getForPage from './helpers/getForPage';12import arrCreator from './helpers/arrCreator';13const INITIAL_STATE = {14 users: {},15 currentPage: 1,16 selectedPage: 1,17 orderedUsers: [],18 filteredUsers: [], // mejor renombrarlo a filteredUsers --> se ordenan, se filtran y se muestran19 displayedInPage: [],20 filterValue: "",21 emailFilterValue: "",22 pages: [1, 2, 3],23 usersPerPage: 10,24};25//helper function26const adminPanelReducer = (state = INITIAL_STATE, { type, payload }) => {27 switch (type) {28 case GET_USERS:29 var newDisplayedInPage = payload;30 var newDisplayedInPage2 = getForPage(newDisplayedInPage, 1, 10);31 var pagesAmount = payload.length / state.usersPerPage;32 var pagesArr = arrCreator(pagesAmount);33 return {34 ...state,35 orderedUsers: payload,36 filteredUsers: payload,37 displayedInPage: newDisplayedInPage2,38 pages: pagesArr,39 };40 case FILTER_BY_NAME:41 var previousUsers = state.orderedUsers.filter(u => {42 return (43 u.username.toLowerCase().includes(state.filterValue.toLowerCase()) &&44 u.email.toLowerCase().includes(state.emailFilterValue.toLowerCase())45 )46 }47 )48 var newUsers = previousUsers.filter(u => u.username.toLowerCase().includes(payload.toLowerCase()));49 var newDisplayedInPage = newUsers;50 var newDisplayedInPage2 = getForPage(newDisplayedInPage, state.selectedPage, state.usersPerPage);51 var pagesAmount = newUsers.length / state.usersPerPage;52 var pagesArr = arrCreator(pagesAmount);53 return {54 ...state,55 filterValue: payload, // Que raro, hubiera esperado que tengo que concatenarlo pero no... por que será...56 filteredUsers: newUsers,57 displayedInPage: newDisplayedInPage2,58 pages: pagesArr,59 currentPage: 1,60 };61 case FILTER_BY_EMAIL:62 var previousUsers = state.orderedUsers.filter(u => {63 return (64 u.username.toLowerCase().includes(state.filterValue.toLowerCase()) &&65 u.email.toLowerCase().includes(state.emailFilterValue.toLowerCase())66 )67 }68 )69 var newUsers = previousUsers.filter(u => u.email.toLowerCase().includes(payload.toLowerCase()));70 var newDisplayedInPage = newUsers;71 var newDisplayedInPage2 = getForPage(newDisplayedInPage, state.selectedPage, state.usersPerPage);72 var pagesAmount = newUsers.length / state.usersPerPage;73 var pagesArr = arrCreator(pagesAmount);74 return {75 ...state,76 emailFilterValue: payload, // Que raro, hubiera esperado que tengo que concatenarlo pero no... por que será...77 filteredUsers: newUsers,78 displayedInPage: newDisplayedInPage2,79 pages: pagesArr,80 currentPage: 1,81 };82 case ORDER_BY_GAMES_ASC:83 var newOrderedUsers = [...state.orderedUsers];84 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byPlayedAsc)85 return {86 ...state,87 orderedUsers: newOrderedUsers2,88 filteredUsers: newOrderedUsers2,89 };90 case ORDER_BY_GAMES_DESC:91 var newOrderedUsers = [...state.orderedUsers];92 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byPlayedDesc)93 return {94 ...state,95 orderedUsers: newOrderedUsers2,96 filteredUsers: newOrderedUsers2,97 };98 case ORDER_BY_WINS_ASC:99 var newOrderedUsers = [...state.orderedUsers];100 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byWonAsc)101 return {102 ...state,103 orderedUsers: newOrderedUsers2,104 filteredUsers: newOrderedUsers2,105 };106 case ORDER_BY_WINS_DESC:107 var newOrderedUsers = [...state.orderedUsers];108 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byWonDesc)109 return {110 ...state,111 orderedUsers: newOrderedUsers2,112 filteredUsers: newOrderedUsers2,113 };114 case ORDER_BY_LOST_ASC:115 var newOrderedUsers = [...state.orderedUsers];116 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byLostAsc)117 return {118 ...state,119 orderedUsers: newOrderedUsers2,120 filteredUsers: newOrderedUsers2,121 };122 case ORDER_BY_LOST_DESC:123 var newOrderedUsers = [...state.orderedUsers];124 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byLostDesc)125 return {126 ...state,127 orderedUsers: newOrderedUsers2,128 filteredUsers: newOrderedUsers2,129 };130 case ORDER_BY_USER_SINCE_ASC:131 var newOrderedUsers = [...state.orderedUsers];132 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byUserSinceAsc)133 return {134 ...state,135 orderedUsers: newOrderedUsers2,136 filteredUsers: newOrderedUsers2,137 };138 case ORDER_BY_USER_SINCE_DESC:139 var newOrderedUsers = [...state.orderedUsers];140 var newOrderedUsers2 = newOrderedUsers.sort(comparers.byUserSinceDesc)141 return {142 ...state,143 orderedUsers: newOrderedUsers2,144 filteredUsers: newOrderedUsers2,145 };146 case SET_DISPLAYED_ON_PAGE:147 var newDisplayedInPage = [...state.displayedInPage];148 var newDisplayedInPage2 = getForPage(newDisplayedInPage, payload.pageToShow, payload.usersPerPage);149 return {150 ...state,151 displayedInPage: newDisplayedInPage2152 };153 case GO_TO_N_PAGE:154 var newDisplayedInPage = [...state.filteredUsers]155 var newDisplayedInPage2 = getForPage(newDisplayedInPage, state.selectedPage, state.usersPerPage);156 console.log("Usuarios mostrados en esta página:")157 console.log(newDisplayedInPage2);158 return {159 ...state,160 displayedInPage: newDisplayedInPage2,161 currentPage: state.selectedPage,162 };163 case SET_SELECTED_PAGE:164 return {165 ...state,166 selectedPage: payload,167 };168 case SET_USERS_PER_PAGE:169 var newValue = parseInt(payload)170 var pagesAmount = state.filteredUsers.length / newValue;171 var pagesArr = arrCreator(pagesAmount);172 return {173 ...state,174 usersPerPage: newValue,175 pages: pagesArr176 };177 case SET_TOTAL_PAGES:178 var pagesAmount = payload.length / state.resultsPerPage;179 var pagesArr = arrCreator(pagesAmount);180 return {181 ...state,182 pages: pagesArr183 };184 case BAN_USER:185 var newOrderedUsers = [...state.orderedUsers];186 var newFilteredUsers = [...state.filteredUsers]; // mejor renombrarlo a filteredUsers --> se ordenan, se filtran y se muestran187 var newDisplayedInPage = [...state.displayedInPage];188 function changeBan(userId, arr) {189 var user = arr.find(u => u.id === userId);190 user.status = "baneado";191 }192 changeBan(payload, newOrderedUsers);193 changeBan(payload, newFilteredUsers);194 changeBan(payload, newDisplayedInPage);195 return {196 ...state,197 OrderedUsers: newOrderedUsers,198 FilteredUsers: newFilteredUsers,199 DisplayedInPage: newDisplayedInPage200 };201 case SUSPEND_USER:202 var newOrderedUsers = [...state.orderedUsers];203 var newFilteredUsers = [...state.filteredUsers]; // mejor renombrarlo a filteredUsers --> se ordenan, se filtran y se muestran204 var newDisplayedInPage = [...state.displayedInPage];205 function changeSuspend(userId, arr) {206 var user = arr.find(u => u.id === userId);207 user.status = "suspendido";208 }209 changeSuspend(payload, newOrderedUsers);210 changeSuspend(payload, newFilteredUsers);211 changeSuspend(payload, newDisplayedInPage);212 return {213 ...state,214 OrderedUsers: newOrderedUsers,215 FilteredUsers: newFilteredUsers,216 DisplayedInPage: newDisplayedInPage217 };218 case ACTIVATE_USER:219 var newOrderedUsers = [...state.orderedUsers];220 var newFilteredUsers = [...state.filteredUsers]; // mejor renombrarlo a filteredUsers --> se ordenan, se filtran y se muestran221 var newDisplayedInPage = [...state.displayedInPage];222 function changeActivate(userId, arr) {223 var user = arr.find(u => u.id === userId);224 user.status = "activo";225 }226 changeActivate(payload, newOrderedUsers);227 changeActivate(payload, newFilteredUsers);228 changeActivate(payload, newDisplayedInPage);229 return {230 ...state,231 OrderedUsers: newOrderedUsers,232 FilteredUsers: newFilteredUsers,233 DisplayedInPage: newDisplayedInPage234 };235 default:236 return state;237 };238};...

Full Screen

Full Screen

View.js

Source:View.js Github

copy

Full Screen

1import { Component } from 'react';2import Footer from '../../footer/footer';3import Header from '../../header/header';4import axios from 'axios';5import io from 'socket.io-client';6import callApi from '../utils/apiCaller';7var connectionOptions = {8 "force new connection": true,9 "reconnectionAttempts": "Infinity",10 "timeout": 10000,11 "transports": ["websocket"]12};13const socket = io("https://service-table.herokuapp.com/", connectionOptions);14class View extends Component {15 constructor(props) {16 super(props);17 this.state = {18 table: [],19 ordered: [],20 content: '',21 tableOrder: []22 }23 }24 componentDidMount() {25 var { match } = this.props;26 var orderID = match.params.id;27 if (localStorage.getItem('token')) {28 this.onGetPerNum(orderID);29 }30 socket.on('connect', function (data) {31 socket.emit('join', 'hello server from client');32 });33 var ordered = this.state.ordered;34 for (var i = 0; i < 16; i++) {35 var table = {36 id: i,37 status: false38 }39 ordered.push(table);40 this.setState({41 ordered: ordered,42 });43 }44 // this.setState({45 // content: "5,6,7"46 // });47 socket.on('thread', (data) => {48 this.setState({49 table: data,50 });51 var table = this.state.table;52 if (table.length > 0) {53 for (var i = 0; i < 16; i++) {54 var checkStatus = false;55 if (table.indexOf(i + 1) > -1) {56 ordered[i].status = true;57 } else {58 ordered[i].status = false;59 }60 this.setState({61 ordered: ordered,62 });63 }64 } else {65 for (var i = 0; i < 16; i++) {66 ordered[i].status = false;67 this.setState({68 ordered: ordered,69 });70 }71 }72 });73 }74 onGetPerNum = (orderID) => {75 if (localStorage.getItem('token')) {76 var token = localStorage.getItem('token');77 callApi(`api/orders/${orderID}`, 'GET', null, { 'Authorization': `Bearer ${JSON.parse(token)}` }).then(res => {78 this.setState({79 content: res.data.data.perNum,80 });81 });82 }83 }84 render() {85 return (86 <div>87 <Header />88 <div className="section" data-aos="fade-up">89 <div className="container">90 <div className="row justify-content-center mb-5">91 <div className="col-md-8 text-center">92 <h2 className="mb-3">Reservation</h2>93 <p className="lead" style={{ fontSize: '30px' }}>Ban cua ban la: {this.state.content}</p>94 </div>95 </div>96 <div className="row justify-content-center">97 <div className="col-md-10 p-5 form-wrap">98 <div className="row justify-content-center">99 <div className='col-md-10 p-5 form-wrap'>100 <div className="row">101 {this.onFor(this.state.ordered, this.state.content)}102 </div>103 </div>104 </div>105 </div>106 </div>107 </div>108 </div>109 <div className="map-wrap" id="map" data-aos="fade"></div>110 <Footer />111 </div>112 );113 }114 onFor = (ordered, content) => {115 var result = null;116 var style1 = {117 color: 'black',118 textAlign: 'center',119 margin: '50px'120 }121 var style2 = {122 color: 'black',123 textAlign: 'center',124 margin: '50px',125 background: "#ff0"126 }127 if (ordered.length > 0) {128 result = ordered.map((order, index) => {129 return (130 <div key={index} className="col-xs-3 col-sm-3 col-md-3 col-lg-3" style={{ marginBottom: '10px' }}>131 <p style={order.status === false ? style1 : style2} table={index} onClick={(e) => this.onchoose(e, index, content)}>{index + 1}</p>132 </div>133 );134 })135 }136 return result;137 }138 onchoose = (e, i, content) => {139 var newTable = parseInt(e.target.innerText);140 var table = this.state.table;141 var { ordered } = this.state;142 var tableOrder;143 if (content.includes(',')) {144 tableOrder = content.split(",");145 } else {146 tableOrder = [content];147 //[...tableOrder, content];148 }149 if (tableOrder.length > 0) {150 if (tableOrder.indexOf(newTable + "") > -1) {151 var dem = 0;152 for (var y = 0; y < table.length; y++) {153 if (table[y] === newTable) {154 dem++;155 table.splice(y, 1);156 //ordered[i].status = !ordered[i].status;157 this.setState({158 table: table,159 //ordered: ordered160 })161 }162 }163 if (dem === 0) {164 table.push(newTable);165 //ordered[i].status = !ordered[i].status;166 this.setState({167 table: table,168 //ordered: ordered169 })170 }171 socket.emit('message', this.state.table);172 } else {173 alert('ban chua dat ban nay');174 }175 }176 }177}...

Full Screen

Full Screen

ordered-item.route.ts

Source:ordered-item.route.ts Github

copy

Full Screen

1import { Injectable } from '@angular/core';2import { HttpResponse } from '@angular/common/http';3import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router';4import { UserRouteAccessService } from 'app/core';5import { of } from 'rxjs';6import { map } from 'rxjs/operators';7import { OrderedItem } from 'app/shared/model/ordered-item.model';8import { OrderedItemService } from './ordered-item.service';9import { OrderedItemComponent } from './ordered-item.component';10import { OrderedItemDetailComponent } from './ordered-item-detail.component';11import { OrderedItemUpdateComponent } from './ordered-item-update.component';12import { OrderedItemDeletePopupComponent } from './ordered-item-delete-dialog.component';13import { IOrderedItem } from 'app/shared/model/ordered-item.model';14@Injectable({ providedIn: 'root' })15export class OrderedItemResolve implements Resolve<IOrderedItem> {16 constructor(private service: OrderedItemService) {}17 resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {18 const id = route.params['id'] ? route.params['id'] : null;19 if (id) {20 return this.service.find(id).pipe(map((orderedItem: HttpResponse<OrderedItem>) => orderedItem.body));21 }22 return of(new OrderedItem());23 }24}25export const orderedItemRoute: Routes = [26 {27 path: 'ordered-item',28 component: OrderedItemComponent,29 data: {30 authorities: ['ROLE_USER'],31 pageTitle: 'jhipsterMongodbWithRelationsApp.orderedItem.home.title'32 },33 canActivate: [UserRouteAccessService]34 },35 {36 path: 'ordered-item/:id/view',37 component: OrderedItemDetailComponent,38 resolve: {39 orderedItem: OrderedItemResolve40 },41 data: {42 authorities: ['ROLE_USER'],43 pageTitle: 'jhipsterMongodbWithRelationsApp.orderedItem.home.title'44 },45 canActivate: [UserRouteAccessService]46 },47 {48 path: 'ordered-item/new',49 component: OrderedItemUpdateComponent,50 resolve: {51 orderedItem: OrderedItemResolve52 },53 data: {54 authorities: ['ROLE_USER'],55 pageTitle: 'jhipsterMongodbWithRelationsApp.orderedItem.home.title'56 },57 canActivate: [UserRouteAccessService]58 },59 {60 path: 'ordered-item/:id/edit',61 component: OrderedItemUpdateComponent,62 resolve: {63 orderedItem: OrderedItemResolve64 },65 data: {66 authorities: ['ROLE_USER'],67 pageTitle: 'jhipsterMongodbWithRelationsApp.orderedItem.home.title'68 },69 canActivate: [UserRouteAccessService]70 }71];72export const orderedItemPopupRoute: Routes = [73 {74 path: 'ordered-item/:id/delete',75 component: OrderedItemDeletePopupComponent,76 resolve: {77 orderedItem: OrderedItemResolve78 },79 data: {80 authorities: ['ROLE_USER'],81 pageTitle: 'jhipsterMongodbWithRelationsApp.orderedItem.home.title'82 },83 canActivate: [UserRouteAccessService],84 outlet: 'popup'85 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator, addParameters } from '@storybook/react';2import { withA11y } from '@storybook/addon-a11y';3import { withInfo } from '@storybook/addon-info';4import { withKnobs } from '@storybook/addon-knobs';5import { withTests } from '@storybook/addon-jest';6import results from '../.jest-test-results.json';7addDecorator(withA11y);8addDecorator(withInfo);9addDecorator(withKnobs);10addDecorator(withTests({ results }));11addParameters({12 options: {13 storySort: (a, b) => {14 const aParent = a[1].kind.split('/')[0];15 const bParent = b[1].kind.split('/')[0];16 if (aParent !== bParent) {17 return aParent.localeCompare(bParent);18 }19 return a[1].id.localeCompare(b[1].id);20 },21 },22});23const path = require('path');24module.exports = (baseConfig, env, defaultConfig) => {25 defaultConfig.module.rules.push({26 test: /\.(ts|tsx)$/,27 include: path.resolve(__dirname, '../'),28 loader: require.resolve('ts-loader'),29 });30 defaultConfig.resolve.extensions.push('.ts', '.tsx');31 return defaultConfig;32};33module.exports = {34 stories: ['../src/**/*.stories.(js|jsx|ts|tsx)'],35};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator, configure } from '@storybook/react';2import { withOptions } from '@storybook/addon-options';3import { withKnobs } from '@storybook/addon-knobs';4import { withInfo } from '@storybook/addon-info';5import { withA11y } from '@storybook/addon-a11y';6import { withTests } from '@storybook/addon-jest';7import results from '../.jest-test-results.json';8import { setOptions } from '@storybook/addon-options';9import { setDefaults } from '@storybook/addon-info';10addDecorator(11 withTests({12 })13);14addDecorator(15 withInfo({16 styles: {17 infoBody: {18 },19 infoStory: {20 },21 },22 })23);24addDecorator(withKnobs);25addDecorator(withA11y);26addDecorator(27 withOptions({28 })29);30configure(require.context('../src', true, /\.stories\.js$/), module);31import { configure } from '@storybook/react';32import { setOptions } from '@storybook/addon-options';33setOptions({34});35configure(require.context('../src', true, /\.stories\.js$/), module);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import { withRootDecorator } from 'storybook-root-decorator';3addDecorator(withRootDecorator);4import { addDecorator } from '@storybook/react';5import { withRootDecorator } from 'storybook-root-decorator';6addDecorator(withRootDecorator({ordered: false}));7import { withRootDecorator } from 'storybook-root-decorator';8export const decorators = [withRootDecorator];9import { withRootDecorator } from 'storybook-root-decorator';10export const decorators = [withRootDecorator({ordered: false})];11import { addons } from '@storybook/addons';12import { withRootDecorator } from 'storybook-root-decorator';13addons.setConfig({14});15import { addons } from '@storybook/addons';16import { withRootDecorator } from 'storybook-root-decorator';17addons.setConfig({18 decorator: withRootDecorator({ordered: false}),19});20import { addDecorator } from '@storybook/react';21import { withRootDecorator } from 'storybook-root-decorator';22import { withThemeProvider } from 'storybook-theme-provider';23addDecorator(withRootDecorator);24addDecorator(withThemeProvider);25import { addDecorator } from '@storybook/react';26import { withRootDecorator } from 'storybook-root-decorator';27import { withThemeProvider } from 'storybook-theme-provider';28addDecorator(withRootDecorator({ordered: false}));29addDecorator(withThemeProvider);30import { withRootDecorator } from 'storybook-root-decorator';31import { withThemeProvider } from 'storybook-theme-provider';32export const decorators = [withRootDecorator, withThemeProvider];

Full Screen

Using AI Code Generation

copy

Full Screen

1import {configure, addDecorator} from '@storybook/react';2import {withA11y} from '@storybook/addon-a11y';3import {withInfo} from '@storybook/addon-info';4import {withKnobs} from '@storybook/addon-knobs';5import {withOptions} from '@storybook/addon-options';6import {setOptions} from '@storybook/addon-options';7import {withViewport} from '@storybook/addon-viewport';8import {configureViewport} from '@storybook/addon-viewport';9import {INITIAL_VIEWPORTS} from '@storybook/addon-viewport';10import {withTests} from '@storybook/addon-jest';11import results from '../.jest-test-results.json';12addDecorator(withA11y);13addDecorator(withInfo);14addDecorator(withKnobs);15addDecorator(withOptions);16addDecorator(withViewport);17addDecorator(withTests({ results }));18setOptions({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configure } from '@storybook/react';2import { withKnobs } from '@storybook/addon-knobs';3import { addDecorator } from '@storybook/react';4addDecorator(withKnobs);5const req = require.context('../src', true, /\.stories\.js$/);6function loadStories() {7 req.keys().forEach(filename => req(filename));8}9configure(loadStories, module);10const path = require('path');11const rootPath = path.resolve(__dirname, '../');12module.exports = async ({ config, mode }) => {13 config.module.rules.push({14 test: /\.(ts|tsx)$/,15 {16 loader: require.resolve('awesome-typescript-loader'),17 },18 {19 loader: require.resolve('react-docgen-typescript-loader'),20 },21 });22 config.resolve.extensions.push('.ts', '.tsx');23 config.resolve.alias = {24 '@src': path.resolve(rootPath, 'src'),25 '@storybook': path.resolve(rootPath, '.storybook'),26 '@components': path.resolve(rootPath, 'src/components'),27 '@containers': path.resolve(rootPath, 'src/containers'),28 '@pages': path.resolve(rootPath, 'src/pages'),29 '@utils': path.resolve(rootPath, 'src/utils'),30 '@store': path.resolve(rootPath, 'src/store'),31 '@constants': path.resolve(rootPath, 'src/constants'),32 '@types': path.resolve(rootPath, 'src/types'),33 '@hooks': path.resolve(rootPath, 'src/hooks'),34 '@assets': path.resolve(rootPath, 'src/assets'),35 };36 return config;37};38import '@storybook/addon-actions/register';39import '@storybook/addon-knobs/register';40import '@storybook/addon-links/register';41import '@storybook/addon-notes/register';42import '@storybook/addon-storysource/register';43import '@storybook/addon-viewport/register';44import '@storybook/addon-backgrounds/register';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withInfo } from '@storybook/addon-info';3import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';4import { withA11y } from '@storybook/addon-a11y';5import { withViewport } from '@storybook/addon-viewport';6storiesOf('Button', module)7 .addDecorator(withKnobs)8 .addDecorator(withA11y)9 .addDecorator(withViewport('iphone6'))10 .add('with text', () => (11 <Button onClick={action('clicked')}>Hello Button</Button>12 .add('with some emoji', () => (13 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>14 .add('with some emoji and info', withInfo('description')(() => (15 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>16 .add('with some emoji and info and knobs', withInfo('description')(() => (17 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>18 .add('with some emoji and info and knobs and viewport', withInfo('description')(() => (19 <Button onClick={action('clicked')}><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>20 )));21import { configure } from '@storybook/react';22const req = require.context('../src', true, /.stories.js$/);23function loadStories() {24 req.keys().forEach(filename => req(filename));25}26configure(loadStories, module);27module.exports = {28 module: {29 {30 loaders: [require.resolve('@storybook/addon-storysource/loader')],31 },32 },33};34import '@storybook/addon-storysource/register';35import '@storybook/add

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import withOrderedRootDecorator from 'storybook-root-decorator';3import { withKnobs } from '@storybook/addon-knobs';4import { withA11y } from '@storybook/addon-a11y';5import { withInfo } from '@storybook/addon-info';6const withRootDecorator = withOrderedRootDecorator([7]);8addDecorator(withRootDecorator);9import { addDecorator } from '@storybook/react';10import withRootDecorator from 'storybook-root-decorator';11addDecorator(withRootDecorator);12import { addDecorator } from '@storybook/react';13import withRootDecorator from 'storybook-root-decorator';14addDecorator(withRootDecorator());15import { addDecorator } from '@storybook/react';16import withRootDecorator from 'storybook-root-decorator';17import { withKnobs } from '@storybook/addon-knobs';18import { withA11y } from '@storybook/addon-a11y';19import { withInfo } from '@storybook/addon-info';20addDecorator(withRootDecorator([withKnobs, withA11y, withInfo]));

Full Screen

Using AI Code Generation

copy

Full Screen

1import StorybookRoot from './storybook-root.js';2let storybookRoot = new StorybookRoot();3document.body.appendChild(storybookRoot);4class StorybookRoot extends HTMLElement {5 constructor() {6 super();7 const shadow = this.attachShadow({mode: 'open'});8 const div = document.createElement('div');9 div.setAttribute('class', 'storybook-root');10 const para = document.createElement('p');11 para.textContent = 'The storybook-root element is the root of the storybook.';12 div.appendChild(para);13 shadow.appendChild(div);14 }15}16customElements.define('storybook-root', StorybookRoot);17.storybook-root {18 font-family: sans-serif;19 background-color: #f5f5f5;20 padding: 10px;21 border: 1px solid #e5e5e5;22 border-radius: 5px;23}24import StorybookRoot from './storybook-root.js';25let storybookRoot = new StorybookRoot();26document.body.appendChild(storybookRoot);27class StorybookRoot extends HTMLElement {28 constructor() {29 super();30 const shadow = this.attachShadow({mode: '

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