Best Python code snippet using lisa_python
np_array_ops_test.py
Source:np_array_ops_test.py
...390 np_array_ops.array,391 lambda x: np_array_ops.array(x, dtype=np.float32),392 lambda x: np_array_ops.array(x, dtype=np.float64)393 ]394 def run_test(arr):395 for fn in array_transforms:396 arr = fn(arr)397 self.match(398 np_array_ops.diag(arr), np.diag(arr), msg='diag({})'.format(arr))399 for k in range(-3, 3):400 self.match(401 np_array_ops.diag(arr, k),402 np.diag(arr, k),403 msg='diag({}, k={})'.format(arr, k))404 # 2-d arrays.405 run_test(np.arange(9).reshape((3, 3)).tolist())406 run_test(np.arange(6).reshape((2, 3)).tolist())407 run_test(np.arange(6).reshape((3, 2)).tolist())408 run_test(np.arange(3).reshape((1, 3)).tolist())409 run_test(np.arange(3).reshape((3, 1)).tolist())410 run_test([[5]])411 run_test([[]])412 run_test([[], []])413 # 1-d arrays.414 run_test([])415 run_test([1])416 run_test([1, 2])417 def testDiagFlat(self):418 array_transforms = [419 lambda x: x, # Identity,420 ops.convert_to_tensor,421 np.array,422 lambda x: np.array(x, dtype=np.float32),423 lambda x: np.array(x, dtype=np.float64),424 np_array_ops.array,425 lambda x: np_array_ops.array(x, dtype=np.float32),426 lambda x: np_array_ops.array(x, dtype=np.float64)427 ]428 def run_test(arr):429 for fn in array_transforms:430 arr = fn(arr)431 self.match(432 np_array_ops.diagflat(arr),433 np.diagflat(arr),434 msg='diagflat({})'.format(arr))435 for k in range(-3, 3):436 self.match(437 np_array_ops.diagflat(arr, k),438 np.diagflat(arr, k),439 msg='diagflat({}, k={})'.format(arr, k))440 # 1-d arrays.441 run_test([])442 run_test([1])443 run_test([1, 2])444 # 2-d arrays.445 run_test([[]])446 run_test([[5]])447 run_test([[], []])448 run_test(np.arange(4).reshape((2, 2)).tolist())449 run_test(np.arange(2).reshape((2, 1)).tolist())450 run_test(np.arange(2).reshape((1, 2)).tolist())451 # 3-d arrays452 run_test(np.arange(8).reshape((2, 2, 2)).tolist())453 def match_shape(self, actual, expected, msg=None):454 if msg:455 msg = 'Shape match failed for: {}. Expected: {} Actual: {}'.format(456 msg, expected.shape, actual.shape)457 self.assertEqual(actual.shape, expected.shape, msg=msg)458 def match_dtype(self, actual, expected, msg=None):459 if msg:460 msg = 'Dtype match failed for: {}. Expected: {} Actual: {}.'.format(461 msg, expected.dtype, actual.dtype)462 self.assertEqual(actual.dtype, expected.dtype, msg=msg)463 def match(self, actual, expected, msg=None, almost=False, decimal=7):464 msg_ = 'Expected: {} Actual: {}'.format(expected, actual)465 if msg:466 msg = '{} {}'.format(msg_, msg)467 else:468 msg = msg_469 self.assertIsInstance(actual, np_arrays.ndarray)470 self.match_dtype(actual, expected, msg)471 self.match_shape(actual, expected, msg)472 if not almost:473 if not actual.shape.rank:474 self.assertEqual(actual.tolist(), expected.tolist())475 else:476 self.assertSequenceEqual(actual.tolist(), expected.tolist())477 else:478 np.testing.assert_almost_equal(479 actual.tolist(), expected.tolist(), decimal=decimal)480 def testIndexedSlices(self):481 dtype = dtypes.int64482 iss = indexed_slices.IndexedSlices(483 values=np_array_ops.ones([2, 3], dtype=dtype),484 indices=constant_op.constant([1, 9]),485 dense_shape=[10, 3])486 a = np_array_ops.array(iss, copy=False)487 expected = array_ops.scatter_nd([[1], [9]],488 array_ops.ones([2, 3], dtype=dtype),489 [10, 3])490 self.assertAllEqual(expected, a)491class ArrayMethodsTest(test.TestCase):492 def setUp(self):493 super(ArrayMethodsTest, self).setUp()494 set_up_virtual_devices()495 self.array_transforms = [496 lambda x: x,497 ops.convert_to_tensor,498 np.array,499 np_array_ops.array,500 ]501 def testAllAny(self):502 def run_test(arr, *args, **kwargs):503 for fn in self.array_transforms:504 arr = fn(arr)505 self.match(506 np_array_ops.all(arr, *args, **kwargs),507 np.all(arr, *args, **kwargs))508 self.match(509 np_array_ops.any(arr, *args, **kwargs),510 np.any(arr, *args, **kwargs))511 run_test(0)512 run_test(1)513 run_test([])514 run_test([[True, False], [True, True]])515 run_test([[True, False], [True, True]], axis=0)516 run_test([[True, False], [True, True]], axis=0, keepdims=True)517 run_test([[True, False], [True, True]], axis=1)518 run_test([[True, False], [True, True]], axis=1, keepdims=True)519 run_test([[True, False], [True, True]], axis=(0, 1))520 run_test([[True, False], [True, True]], axis=(0, 1), keepdims=True)521 run_test([5.2, 3.5], axis=0)522 run_test([1, 0], axis=0)523 def testCompress(self):524 def run_test(condition, arr, *args, **kwargs):525 for fn1 in self.array_transforms:526 for fn2 in self.array_transforms:527 arg1 = fn1(condition)528 arg2 = fn2(arr)529 self.match(530 np_array_ops.compress(arg1, arg2, *args, **kwargs),531 np.compress(532 np.asarray(arg1).astype(np.bool_), arg2, *args, **kwargs))533 run_test([True], 5)534 run_test([False], 5)535 run_test([], 5)536 run_test([True, False, True], [1, 2, 3])537 run_test([True, False], [1, 2, 3])538 run_test([False, True], [[1, 2], [3, 4]])539 run_test([1, 0, 1], [1, 2, 3])540 run_test([1, 0], [1, 2, 3])541 run_test([0, 1], [[1, 2], [3, 4]])542 run_test([True], [[1, 2], [3, 4]])543 run_test([False, True], [[1, 2], [3, 4]], axis=1)544 run_test([False, True], [[1, 2], [3, 4]], axis=0)545 run_test([False, True], [[1, 2], [3, 4]], axis=-1)546 run_test([False, True], [[1, 2], [3, 4]], axis=-2)547 def testCopy(self):548 def run_test(arr, *args, **kwargs):549 for fn in self.array_transforms:550 arg = fn(arr)551 self.match(552 np_array_ops.copy(arg, *args, **kwargs),553 np.copy(arg, *args, **kwargs))554 run_test([])555 run_test([1, 2, 3])556 run_test([1., 2., 3.])557 run_test([True])558 run_test(np.arange(9).reshape((3, 3)).tolist())559 a = np_array_ops.asarray(0)560 self.assertNotIn('CPU:1', a.backing_device)561 with ops.device('CPU:1'):562 self.assertIn('CPU:1', np_array_ops.array(a, copy=True)563 .backing_device)564 self.assertIn('CPU:1', np_array_ops.array(np.array(0), copy=True)565 .backing_device)566 def testCumProdAndSum(self):567 def run_test(arr, *args, **kwargs):568 for fn in self.array_transforms:569 arg = fn(arr)570 self.match(571 np_array_ops.cumprod(arg, *args, **kwargs),572 np.cumprod(arg, *args, **kwargs))573 self.match(574 np_array_ops.cumsum(arg, *args, **kwargs),575 np.cumsum(arg, *args, **kwargs))576 run_test([])577 run_test([1, 2, 3])578 run_test([1, 2, 3], dtype=float)579 run_test([1, 2, 3], dtype=np.float32)580 run_test([1, 2, 3], dtype=np.float64)581 run_test([1., 2., 3.])582 run_test([1., 2., 3.], dtype=int)583 run_test([1., 2., 3.], dtype=np.int32)584 run_test([1., 2., 3.], dtype=np.int64)585 run_test([[1, 2], [3, 4]], axis=1)586 run_test([[1, 2], [3, 4]], axis=0)587 run_test([[1, 2], [3, 4]], axis=-1)588 run_test([[1, 2], [3, 4]], axis=-2)589 def testImag(self):590 def run_test(arr, *args, **kwargs):591 for fn in self.array_transforms:592 arg = fn(arr)593 self.match(594 np_array_ops.imag(arg, *args, **kwargs),595 # np.imag may return a scalar so we convert to a np.ndarray.596 np.array(np.imag(arg, *args, **kwargs)))597 run_test(1)598 run_test(5.5)599 run_test(5 + 3j)600 run_test(3j)601 run_test([])602 run_test([1, 2, 3])603 run_test([1 + 5j, 2 + 3j])604 run_test([[1 + 5j, 2 + 3j], [1 + 7j, 2 + 8j]])605 def testAMaxAMin(self):606 def run_test(arr, *args, **kwargs):607 axis = kwargs.pop('axis', None)608 for fn1 in self.array_transforms:609 for fn2 in self.array_transforms:610 arr_arg = fn1(arr)611 axis_arg = fn2(axis) if axis is not None else None612 self.match(613 np_array_ops.amax(arr_arg, axis=axis_arg, *args, **kwargs),614 np.amax(arr_arg, axis=axis, *args, **kwargs))615 self.match(616 np_array_ops.amin(arr_arg, axis=axis_arg, *args, **kwargs),617 np.amin(arr_arg, axis=axis, *args, **kwargs))618 run_test([1, 2, 3])619 run_test([1., 2., 3.])620 run_test([[1, 2], [3, 4]], axis=1)621 run_test([[1, 2], [3, 4]], axis=0)622 run_test([[1, 2], [3, 4]], axis=-1)623 run_test([[1, 2], [3, 4]], axis=-2)624 run_test([[1, 2], [3, 4]], axis=(0, 1))625 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2))626 run_test(627 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2), keepdims=True)628 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0))629 run_test(630 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0), keepdims=True)631 self.assertRaises(ValueError, np_array_ops.amax, np.ones([2, 2]), out=[])632 self.assertRaises(ValueError, np_array_ops.amin, np.ones([2, 2]), out=[])633 def testMean(self):634 def run_test(arr, *args, **kwargs):635 axis = kwargs.pop('axis', None)636 for fn1 in self.array_transforms:637 for fn2 in self.array_transforms:638 arr_arg = fn1(arr)639 axis_arg = fn2(axis) if axis is not None else None640 self.match(641 np_array_ops.mean(arr_arg, axis=axis_arg, *args, **kwargs),642 np.mean(arr_arg, axis=axis, *args, **kwargs))643 run_test([1, 2, 1])644 run_test([1., 2., 1.])645 run_test([1., 2., 1.], dtype=int)646 run_test([[1, 2], [3, 4]], axis=1)647 run_test([[1, 2], [3, 4]], axis=0)648 run_test([[1, 2], [3, 4]], axis=-1)649 run_test([[1, 2], [3, 4]], axis=-2)650 run_test([[1, 2], [3, 4]], axis=(0, 1))651 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2))652 run_test(653 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2), keepdims=True)654 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0))655 run_test(656 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0), keepdims=True)657 self.assertRaises(ValueError, np_array_ops.mean, np.ones([2, 2]), out=[])658 def testStd(self):659 def run_test(arr, *args, **kwargs):660 axis = kwargs.pop('axis', None)661 for fn1 in self.array_transforms:662 for fn2 in self.array_transforms:663 arr_arg = fn1(arr)664 axis_arg = fn2(axis) if axis is not None else None665 self.match(666 np_array_ops.std(arr_arg, axis=axis_arg, *args, **kwargs),667 np.std(arr_arg, axis=axis, *args, **kwargs))668 run_test([1, 2, 1])669 run_test([1., 2., 1.])670 run_test([1.j, 2., 1.j])671 run_test([[1, 2], [3, 4]], axis=1)672 run_test([[1, 2], [3, 4]], axis=0)673 run_test([[1, 2], [3, 4]], axis=-1)674 run_test([[1, 2], [3, 4]], axis=-2)675 run_test([[1, 2], [3, 4]], axis=(0, 1))676 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2))677 run_test(678 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2), keepdims=True)679 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0))680 run_test(681 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0), keepdims=True)682 def testVar(self):683 def run_test(arr, *args, **kwargs):684 axis = kwargs.pop('axis', None)685 for fn1 in self.array_transforms:686 for fn2 in self.array_transforms:687 arr_arg = fn1(arr)688 axis_arg = fn2(axis) if axis is not None else None689 self.match(690 np_array_ops.var(arr_arg, axis=axis_arg, *args, **kwargs),691 np.var(arr_arg, axis=axis, *args, **kwargs))692 run_test([1, 2, 1])693 run_test([1., 2., 1.])694 run_test([1.j, 2., 1.j])695 run_test([1., 2., 1.], dtype=np.int64)696 run_test([[1, 2], [3, 4]], axis=1)697 run_test([[1, 2], [3, 4]], axis=0)698 run_test([[1, 2], [3, 4]], axis=-1)699 run_test([[1, 2], [3, 4]], axis=-2)700 run_test([[1, 2], [3, 4]], axis=(0, 1))701 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2))702 run_test(703 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2), keepdims=True)704 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0))705 run_test(706 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0), keepdims=True)707 self.assertRaises(ValueError, np_array_ops.var, np.ones([2, 2]), out=[])708 def testProd(self):709 def run_test(arr, *args, **kwargs):710 for fn in self.array_transforms:711 arg = fn(arr)712 self.match(713 np_array_ops.prod(arg, *args, **kwargs),714 np.prod(arg, *args, **kwargs))715 run_test([1, 2, 3])716 run_test([1., 2., 3.])717 run_test(np.array([1, 2, 3], dtype=np.int16))718 run_test([[1, 2], [3, 4]], axis=1)719 run_test([[1, 2], [3, 4]], axis=0)720 run_test([[1, 2], [3, 4]], axis=-1)721 run_test([[1, 2], [3, 4]], axis=-2)722 run_test([[1, 2], [3, 4]], axis=(0, 1))723 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2))724 run_test(725 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(0, 2), keepdims=True)726 run_test(np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0))727 run_test(728 np.arange(8).reshape((2, 2, 2)).tolist(), axis=(2, 0), keepdims=True)729 def _testReduce(self, math_fun, np_fun, name):730 axis_transforms = [731 lambda x: x, # Identity,732 ops.convert_to_tensor,733 np.array,734 np_array_ops.array,735 lambda x: np_array_ops.array(x, dtype=np.float32),736 lambda x: np_array_ops.array(x, dtype=np.float64),737 ]738 def run_test(a, **kwargs):739 axis = kwargs.pop('axis', None)740 for fn1 in self.array_transforms:741 for fn2 in axis_transforms:742 arg1 = fn1(a)743 axis_arg = fn2(axis) if axis is not None else None744 self.match(745 math_fun(arg1, axis=axis_arg, **kwargs),746 np_fun(arg1, axis=axis, **kwargs),747 msg='{}({}, axis={}, keepdims={})'.format(name, arg1, axis,748 kwargs.get('keepdims')))749 run_test(5)750 run_test([2, 3])751 run_test([[2, -3], [-6, 7]])752 run_test([[2, -3], [-6, 7]], axis=0)753 run_test([[2, -3], [-6, 7]], axis=0, keepdims=True)754 run_test([[2, -3], [-6, 7]], axis=1)755 run_test([[2, -3], [-6, 7]], axis=1, keepdims=True)756 run_test([[2, -3], [-6, 7]], axis=(0, 1))757 run_test([[2, -3], [-6, 7]], axis=(1, 0))758 def testSum(self):759 self._testReduce(np_array_ops.sum, np.sum, 'sum')760 def testAmax(self):761 self._testReduce(np_array_ops.amax, np.amax, 'amax')762 def testSize(self):763 def run_test(arr, axis=None):764 onp_arr = np.array(arr)765 self.assertEqual(np_array_ops.size(arr, axis), np.size(onp_arr, axis))766 run_test(np_array_ops.array([1]))767 run_test(np_array_ops.array([1, 2, 3, 4, 5]))768 run_test(np_array_ops.ones((2, 3, 2)))769 run_test(np_array_ops.ones((3, 2)))770 run_test(np_array_ops.zeros((5, 6, 7)))771 run_test(1)772 run_test(np_array_ops.ones((3, 2, 1)))773 run_test(constant_op.constant(5))774 run_test(constant_op.constant([1, 1, 1]))775 self.assertRaises(NotImplementedError, np_array_ops.size, np.ones((2, 2)),776 1)777 @def_function.function(input_signature=[778 tensor_spec.TensorSpec(dtype=dtypes.float64, shape=None)])779 def f(arr):780 arr = np_array_ops.asarray(arr)781 return np_array_ops.size(arr)782 self.assertEqual(f(np_array_ops.ones((3, 2))).numpy(), 6)783 def testRavel(self):784 def run_test(arr, *args, **kwargs):785 for fn in self.array_transforms:786 arg = fn(arr)787 self.match(788 np_array_ops.ravel(arg, *args, **kwargs),789 np.ravel(arg, *args, **kwargs))790 run_test(5)791 run_test(5.)792 run_test([])793 run_test([[]])794 run_test([[], []])795 run_test([1, 2, 3])796 run_test([1., 2., 3.])797 run_test([[1, 2], [3, 4]])798 run_test(np.arange(8).reshape((2, 2, 2)).tolist())799 def testReal(self):800 def run_test(arr, *args, **kwargs):801 for fn in self.array_transforms:802 arg = fn(arr)803 self.match(804 np_array_ops.real(arg, *args, **kwargs),805 np.array(np.real(arg, *args, **kwargs)))806 run_test(1)807 run_test(5.5)808 run_test(5 + 3j)809 run_test(3j)810 run_test([])811 run_test([1, 2, 3])812 run_test([1 + 5j, 2 + 3j])813 run_test([[1 + 5j, 2 + 3j], [1 + 7j, 2 + 8j]])814 def testRepeat(self):815 def run_test(arr, repeats, *args, **kwargs):816 for fn1 in self.array_transforms:817 for fn2 in self.array_transforms:818 arr_arg = fn1(arr)819 repeats_arg = fn2(repeats)820 self.match(821 np_array_ops.repeat(arr_arg, repeats_arg, *args, **kwargs),822 np.repeat(arr_arg, repeats_arg, *args, **kwargs))823 run_test(1, 2)824 run_test([1, 2], 2)825 run_test([1, 2], [2])826 run_test([1, 2], [1, 2])827 run_test([[1, 2], [3, 4]], 3, axis=0)828 run_test([[1, 2], [3, 4]], 3, axis=1)829 run_test([[1, 2], [3, 4]], [3], axis=0)830 run_test([[1, 2], [3, 4]], [3], axis=1)831 run_test([[1, 2], [3, 4]], [3, 2], axis=0)832 run_test([[1, 2], [3, 4]], [3, 2], axis=1)833 run_test([[1, 2], [3, 4]], [3, 2], axis=-1)834 run_test([[1, 2], [3, 4]], [3, 2], axis=-2)835 def testAround(self):836 def run_test(arr, *args, **kwargs):837 for fn in self.array_transforms:838 arg = fn(arr)839 self.match(840 np_array_ops.around(arg, *args, **kwargs),841 np.around(arg, *args, **kwargs))842 run_test(5.5)843 run_test(5.567, decimals=2)844 run_test([])845 run_test([1.27, 2.49, 2.75], decimals=1)846 run_test([23.6, 45.1], decimals=-1)847 def testReshape(self):848 def run_test(arr, newshape, *args, **kwargs):849 for fn1 in self.array_transforms:850 for fn2 in self.array_transforms:851 arr_arg = fn1(arr)852 newshape_arg = fn2(newshape)853 self.match(854 np_array_ops.reshape(arr_arg, newshape_arg, *args, **kwargs),855 np.reshape(arr_arg, newshape, *args, **kwargs))856 run_test(5, [-1])857 run_test([], [-1])858 run_test([1, 2, 3], [1, 3])859 run_test([1, 2, 3], [3, 1])860 run_test([1, 2, 3, 4], [2, 2])861 run_test([1, 2, 3, 4], [2, 1, 2])862 def testExpandDims(self):863 def run_test(arr, axis):864 self.match(np_array_ops.expand_dims(arr, axis), np.expand_dims(arr, axis))865 run_test([1, 2, 3], 0)866 run_test([1, 2, 3], 1)867 def testSqueeze(self):868 def run_test(arr, *args, **kwargs):869 for fn in self.array_transforms:870 arg = fn(arr)871 # Note: np.squeeze ignores the axis arg for non-ndarray objects.872 # This looks like a bug: https://github.com/numpy/numpy/issues/8201873 # So we convert the arg to np.ndarray before passing to np.squeeze.874 self.match(875 np_array_ops.squeeze(arg, *args, **kwargs),876 np.squeeze(np.array(arg), *args, **kwargs))877 run_test(5)878 run_test([])879 run_test([5])880 run_test([[1, 2, 3]])881 run_test([[[1], [2], [3]]])882 run_test([[[1], [2], [3]]], axis=0)883 run_test([[[1], [2], [3]]], axis=2)884 run_test([[[1], [2], [3]]], axis=(0, 2))885 run_test([[[1], [2], [3]]], axis=-1)886 run_test([[[1], [2], [3]]], axis=-3)887 def testTranspose(self):888 def run_test(arr, axes=None):889 for fn1 in self.array_transforms:890 for fn2 in self.array_transforms:891 arr_arg = fn1(arr)892 axes_arg = fn2(axes) if axes is not None else None893 self.match(894 np_array_ops.transpose(arr_arg, axes_arg),895 np.transpose(arr_arg, axes))896 run_test(5)897 run_test([])898 run_test([5])899 run_test([5, 6, 7])900 run_test(np.arange(30).reshape(2, 3, 5).tolist())901 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [0, 1, 2])902 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [0, 2, 1])903 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [1, 0, 2])904 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [1, 2, 0])905 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [2, 0, 1])906 run_test(np.arange(30).reshape(2, 3, 5).tolist(), [2, 1, 0])907 def match_shape(self, actual, expected, msg=None):908 if msg:909 msg = 'Shape match failed for: {}. Expected: {} Actual: {}'.format(910 msg, expected.shape, actual.shape)911 self.assertEqual(actual.shape, expected.shape, msg=msg)912 def match_dtype(self, actual, expected, msg=None):913 if msg:914 msg = 'Dtype match failed for: {}. Expected: {} Actual: {}.'.format(915 msg, expected.dtype, actual.dtype)916 self.assertEqual(actual.dtype, expected.dtype, msg=msg)917 def match(self, actual, expected, msg=None, check_dtype=True):918 msg_ = 'Expected: {} Actual: {}'.format(expected, actual)919 if msg:920 msg = '{} {}'.format(msg_, msg)921 else:922 msg = msg_923 self.assertIsInstance(actual, np_arrays.ndarray)924 if check_dtype:925 self.match_dtype(actual, expected, msg)926 self.match_shape(actual, expected, msg)927 if not actual.shape.rank:928 self.assertAllClose(actual.tolist(), expected.tolist())929 else:930 self.assertAllClose(actual.tolist(), expected.tolist())931 def testPad(self):932 t = [[1, 2, 3], [4, 5, 6]]933 paddings = [[934 1,935 1,936 ], [2, 2]]937 self.assertAllEqual(938 np_array_ops.pad(t, paddings, 'constant'),939 [[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0],940 [0, 0, 0, 0, 0, 0, 0]])941 self.assertAllEqual(942 np_array_ops.pad(t, paddings, 'reflect'),943 [[6, 5, 4, 5, 6, 5, 4], [3, 2, 1, 2, 3, 2, 1], [6, 5, 4, 5, 6, 5, 4],944 [3, 2, 1, 2, 3, 2, 1]])945 self.assertAllEqual(946 np_array_ops.pad(t, paddings, 'symmetric'),947 [[2, 1, 1, 2, 3, 3, 2], [2, 1, 1, 2, 3, 3, 2], [5, 4, 4, 5, 6, 6, 5],948 [5, 4, 4, 5, 6, 6, 5]])949 def testTake(self):950 a = [4, 3, 5, 7, 6, 8]951 indices = [0, 1, 4]952 self.assertAllEqual([4, 3, 6], np_array_ops.take(a, indices))953 indices = [[0, 1], [2, 3]]954 self.assertAllEqual([[4, 3], [5, 7]], np_array_ops.take(a, indices))955 a = [[4, 3, 5], [7, 6, 8]]956 self.assertAllEqual([[4, 3], [5, 7]], np_array_ops.take(a, indices))957 a = np.random.rand(2, 16, 3)958 axis = 1959 self.assertAllEqual(960 np.take(a, indices, axis=axis),961 np_array_ops.take(a, indices, axis=axis))962 def testWhere(self):963 self.assertAllEqual([[1.0, 1.0], [1.0, 1.0]],964 np_array_ops.where([True], [1.0, 1.0],965 [[0, 0], [0, 0]]))966 def testShape(self):967 self.assertAllEqual((1, 2), np_array_ops.shape([[0, 0]]))968 def testSwapaxes(self):969 x = [[1, 2, 3]]970 self.assertAllEqual([[1], [2], [3]], np_array_ops.swapaxes(x, 0, 1))971 self.assertAllEqual([[1], [2], [3]], np_array_ops.swapaxes(x, -2, -1))972 x = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]973 self.assertAllEqual([[[0, 4], [2, 6]], [[1, 5], [3, 7]]],974 np_array_ops.swapaxes(x, 0, 2))975 self.assertAllEqual([[[0, 4], [2, 6]], [[1, 5], [3, 7]]],976 np_array_ops.swapaxes(x, -3, -1))977 def testMoveaxis(self):978 def _test(*args):979 # pylint: disable=no-value-for-parameter980 expected = np.moveaxis(*args)981 raw_ans = np_array_ops.moveaxis(*args)982 self.assertAllEqual(expected, raw_ans)983 a = np.random.rand(1, 2, 3, 4, 5, 6)984 # Basic985 _test(a, (0, 2), (3, 5))986 _test(a, (0, 2), (-1, -3))987 _test(a, (-6, -4), (3, 5))988 _test(a, (-6, -4), (-1, -3))989 _test(a, 0, 4)990 _test(a, -6, -2)991 _test(a, tuple(range(6)), tuple(range(6)))992 _test(a, tuple(range(6)), tuple(reversed(range(6))))993 _test(a, (), ())994 def testNdim(self):995 self.assertAllEqual(0, np_array_ops.ndim(0.5))996 self.assertAllEqual(1, np_array_ops.ndim([1, 2]))997 def testIsscalar(self):998 self.assertTrue(np_array_ops.isscalar(0.5))999 self.assertTrue(np_array_ops.isscalar(5))1000 self.assertTrue(np_array_ops.isscalar(False))1001 self.assertFalse(np_array_ops.isscalar([1, 2]))1002 def assertListEqual(self, a, b):1003 self.assertAllEqual(len(a), len(b))1004 for x, y in zip(a, b):1005 self.assertAllEqual(x, y)1006 def testSplit(self):1007 x = np_array_ops.arange(9)1008 y = np_array_ops.split(x, 3)1009 self.assertListEqual([([0, 1, 2]), ([3, 4, 5]), ([6, 7, 8])], y)1010 x = np_array_ops.arange(8)1011 y = np_array_ops.split(x, [3, 5, 6, 10])1012 self.assertListEqual([([0, 1, 2]), ([3, 4]), ([5]), ([6, 7]), ([])], y)1013 def testSign(self):1014 state = np.random.RandomState(0)1015 test_types = [np.float16, np.float32, np.float64, np.int32, np.int64,1016 np.complex64, np.complex128]1017 test_shapes = [(), (1,), (2, 3, 4), (2, 3, 0, 4)]1018 for dtype in test_types:1019 for shape in test_shapes:1020 if np.issubdtype(dtype, np.complexfloating):1021 arr = (np.asarray(state.randn(*shape) * 100, dtype=dtype) +1022 1j * np.asarray(state.randn(*shape) * 100, dtype=dtype))1023 else:1024 arr = np.asarray(state.randn(*shape) * 100, dtype=dtype)1025 self.match(np_array_ops.sign(arr), np.sign(arr))1026class ArrayManipulationTest(test.TestCase):1027 def setUp(self):1028 super(ArrayManipulationTest, self).setUp()1029 self.array_transforms = [1030 lambda x: x,1031 ops.convert_to_tensor,1032 np.array,1033 np_array_ops.array,1034 ]1035 def testBroadcastTo(self):1036 def run_test(arr, shape):1037 for fn in self.array_transforms:1038 arg1 = fn(arr)1039 self.match(1040 np_array_ops.broadcast_to(arg1, shape),1041 np.broadcast_to(arg1, shape))1042 run_test(1, 2)1043 run_test(1, (2, 2))1044 run_test([1, 2], (2, 2))1045 run_test([[1], [2]], (2, 2))1046 run_test([[1, 2]], (3, 2))1047 run_test([[[1, 2]], [[3, 4]], [[5, 6]]], (3, 4, 2))1048 def testIx_(self):1049 possible_arys = [[True, True], [True, False], [False, False],1050 list(range(5)), np_array_ops.empty(0, dtype=np.int64)]1051 for r in range(len(possible_arys)):1052 for arys in itertools.combinations_with_replacement(possible_arys, r):1053 tnp_ans = np_array_ops.ix_(*arys)1054 onp_ans = np.ix_(*arys)1055 for t, o in zip(tnp_ans, onp_ans):1056 self.match(t, o)1057 def match_shape(self, actual, expected, msg=None):1058 if msg:1059 msg = 'Shape match failed for: {}. Expected: {} Actual: {}'.format(1060 msg, expected.shape, actual.shape)1061 self.assertEqual(actual.shape, expected.shape, msg=msg)...
App.js
Source:App.js
1import * as React from 'react';2import { AppRegistry, Platform, StyleSheet, View, Image, StatusBar, TouchableOpacity, ScrollView } from 'react-native';3import HTMLView from 'react-native-htmlview';4import { Avatar, Button, DefaultTheme, Text, Modal, Portal, Provider as PaperProvider, Snackbar, TextInput, ActivityIndicator, Appbar, Surface, Title, Caption, Subheading, Paragraph, RadioButton, Checkbox } from 'react-native-paper';5import { name as appName } from './app.json';6import magnox_logo from './assets/logo.png';7const API_URI = "localhost:3000";8const theme = {9 ...DefaultTheme,10 roundness: 2,11 colors: {12 ...DefaultTheme.colors,13 placeholder: "#42c5f5", primary: "#42c5f5",14 surface: "#42c5f5",15 accent: '#f1c40f',16 },17};18const styles = Platform.select({19 web: StyleSheet.create({20 login: {21 flexDirection: "column",22 alignItems: "center",23 justifyContent: "center",24 flex: 125 },26 loginPasscodeContainer: {27 paddingLeft: 50,28 paddingRight: 50,29 paddingTop: 250,30 flexDirection: "column",31 justifyContent: "center",32 flex: 1,33 width: 64034 },35 loginButton: {36 marginTop: 1037 },38 loginButtonContent: {39 height: 5040 },41 loginButtonText: {42 color: "#ffffff"43 },44 loginLogo: {45 width: 250,46 height: 250,47 resizeMode: "contain"48 },49 loginLogoContainer: {50 alignItems: "center"51 },52 error: {53 flexDirection: "row",54 backgroundColor: "#f00",55 width: 640,56 alignSelf: "center"57 },58 errorText: {59 color: "#fff",60 flex: 161 },62 testLogo: {63 width: 240,64 height: 100,65 resizeMode: "cover"66 },67 test: {68 flexDirection: "column",69 flex: 170 },71 testContainer: {72 flexDirection: "row"73 },74 testCanDetails: {75 margin: 10,76 flex: 1,77 padding: 1078 },79 testDetails: {80 margin: 10,81 flex: 2,82 padding: 1083 },84 top: {85 backgroundColor: "#efefef",86 flexDirection: "row",87 justifyContent: "space-between",88 alignItems: "center",89 padding: 590 },91 topLogo: {92 alignItems: "center",93 flexDirection: "row",94 flex: 1,95 },96 testSections: {97 flexDirection: "row",98 alignSelf: "stretch",99 backgroundColor: "#ffffe0",100 margin: 10101 },102 testSection: {103 margin: 10104 },105 testInstructions: {106 alignSelf: "stretch",107 backgroundColor: "#e0ffef",108 alignContent: "stretch",109 margin: 10,110 padding: 5111 },112 testTitle: {113 textAlign: "center",114 },115 testInfo: {116 flexDirection: "row",117 justifyContent: "space-evenly",118 margin: 10,119 backgroundColor: "#e0efff"120 },121 testEntry: {122 alignItems: "center",123 padding: 10,124 margin: 10125 },126 runTestContainer: {127 flex: 1,128 flexDirection: "row",129 },130 question: {131 alignSelf: "flex-start",132 padding: 50,133 flex: 3,134 margin: 10,135 fontSize: 25136 },137 questionT1: {138 padding: 20139 },140 questionT2: {141 padding: 20142 },143 questionT3: {144 padding: 20145 },146 runTestControls: {147 backgroundColor: "#efefef",148 flexDirection: "row",149 justifyContent: "space-evenly",150 padding: 10151 },152 runTestQIndicesContainer: {153 backgroundColor: "#e0efff",154 margin: 10,155 flex: 1156 },157 runTestQIndices: {158 padding: 10,159 flexDirection: "row",160 flexWrap: "wrap",161 justifyContent: "space-between"162 }163 }),164 default: StyleSheet.create({165 login: {166 flexDirection: "column",167 alignItems: "stretch",168 justifyContent: "center",169 flex: 1170 },171 loginPasscodeContainer: {172 paddingLeft: 50,173 paddingRight: 50,174 paddingTop: 250,175 flexDirection: "column",176 justifyContent: "center",177 flex: 1178 },179 loginButton: {180 marginTop: 10,181 zIndex: 3,182 elevation: 3183 },184 loginButtonContent: {185 height: 50186 },187 loginButtonText: {188 color: "#ffffff"189 },190 loginLogo: {191 width: 250,192 height: 250,193 resizeMode: "contain"194 },195 loginLogoContainer: {196 alignItems: "center"197 },198 error: {199 flexDirection: "row",200 backgroundColor: "#f00",201 },202 errorText: {203 color: "#fff",204 flex: 1205 },206 testLogo: {207 width: 240,208 height: 100,209 resizeMode: "cover"210 },211 test: {212 flexDirection: "column",213 flex: 1214 },215 testCanDetails: {216 margin: 10217 },218 testDetails: {219 margin: 10,220 padding: 10221 },222 top: {223 backgroundColor: "#efefef",224 flexDirection: "row",225 justifyContent: "space-between",226 alignItems: "center",227 padding: 5228 },229 testSections: {230 flexDirection: "row",231 alignSelf: "stretch",232 backgroundColor: "#ffffe0",233 margin: 10234 },235 testSection: {236 margin: 10237 },238 testInstructions: {239 backgroundColor: "#e0ffef",240 margin: 10,241 padding: 5242 },243 testTitle: {244 textAlign: "center",245 },246 testInfo: {247 flexDirection: "row",248 justifyContent: "space-evenly",249 margin: 10,250 backgroundColor: "#e0efff"251 },252 testEntry: {253 alignItems: "center",254 padding: 10,255 margin: 10256 },257 runTestContainer: {258 flex: 1,259 },260 question: {261 alignSelf: "flex-start",262 margin: 10,263 fontSize: 25264 },265 questionT1: {266 padding: 20267 },268 questionT2: {269 padding: 20270 },271 questionT3: {272 padding: 20273 },274 runTestControls: {275 backgroundColor: "#efefef",276 flexDirection: "row",277 justifyContent: "space-evenly",278 padding: 10279 },280 runTestQIndicesContainer: {281 backgroundColor: "#e0efff",282 margin: 10283 },284 runTestQIndices: {285 padding: 10,286 flexDirection: "row",287 flexWrap: "wrap",288 justifyContent: "space-between"289 }290 })291});292export default class Main extends React.Component {293 constructor(props) {294 super(props);295 this._state = {296 login: {297 passcode: "",298 },299 test: { "runtest_can": { "id": 14, "test_pub_id": "8", "can_id": "60", "pswd": "279684", "test_start_flag": true, "test_end_flag": false, "present_ques_id": "119", "create_date_time": "2020-12-15T12:45:59.000Z", "entry_date_time": "2020-12-15T12:22:14.000Z", "sec_id": "6", "test_start_dttm": "2020-12-15T12:22:14.000Z", "test_end_dttm": "2020-12-15T13:22:14.000Z" }, "user_details": { "id": "60", "first_name": "Aniruddha", "last_name": "Sarkar", "photo_sm": null, "photo_lg": null, "dateofbirth": "1998-01-03T18:30:00.000Z", "gender": "M", "maritalstatus": null, "email": "sarkar4540@gmail.com", "alt_email": null, "phone": "7548950804", "alt_phone": null, "bloodgroup": null, "aadhar_no": null, "website": null, "address": null, "pin": null, "facebook_link": null, "linkedin_link": null, "google_link": null, "mothertongue_id": null, "about_me": null, "resume_heading": null, "expected_ctc": null, "caste": null, "physical_challenge": null, "percentage_ph": null, "passport_no": null, "organization": null, "designation": null, "mothers_name": null, "mothers_occupation": null, "created_date_time": "2020-11-28T06:16:45.000Z", "modified_date_time": null, "city_id": null }, "test_pub": { "id": 8, "test_id": "5", "org_id": null, "user_id": "58", "publish_type": "1", "start_datetm": null, "create_date_time": "2020-12-03T14:08:29.000Z", "modified_date_time": null, "end_datetm": null, "testc": null, "tp_archive": false }, "test": { "id": 5, "cat_id": "21", "user_id": "58", "title": "College Test", "details": "<p>Write the Test Carefully <br></p>", "admin_flag": true, "duration": 60, "archive_status": false, "hint_display_status": null, "create_date_time": "2020-12-02T11:24:25.000Z", "modified_date_time": null, "scat_id": "0", "marks": 40, "publish": true }, "program": { "id": 21, "code": "TEST001 ", "title": "Nayarozgar", "type": "2 ", "category": "Corporate Program ", "duration": "12 ", "start_date": "2020-11-26T18:30:00.000Z", "end_date": "2021-11-10T18:30:00.000Z", "user_id": "58", "status": "approved ", "total_fee": " ", "total_credit": " ", "why_learn": null, "intro_video_link": null, "overview": "", "requirements": null, "curriculam": "", "selection_procedure": "", "program_brochure": null, "contact_info": null, "certificate_sample": null, "statusch_date": "2020-11-27T08:56:16.000Z", "date_added": "2020-11-27T08:13:57.000Z", "last_updated": null, "email": "himadri@cyanberg.com", "mobile": "9901072124", "facebook": null, "linkedin": null, "twitter": null, "student_enroll": 0, "teacher_enroll": 0, "fee_details": null, "banner": null, "lastdate_apply": null, "dtype": "month", "feetype": "Paid" }, "course": null },300 loading: false,301 error: false,302 testEntryTimeLeft: null,303 testEndTimeLeft: null,304 testEnded: false,305 run_test: null,306 runTestIndex: 0307 }308 this.state = this._state;309 }310 get(uri = "", body, cb) {311 this.setState({ loading: true })312 fetch(313 API_URI + "/" + uri,314 { method: "POST", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : "{}" }315 ).then(res => {316 if (res.status == 200) {317 res.json()318 .then(json => {319 if (cb) cb(json);320 })321 .catch(err => {322 this.setState({ ...this.state, error: err.message })323 console.log(err);324 })325 }326 else {327 res.json()328 .then(json => {329 this.setState({ error: json.message });330 })331 .catch(err => {332 this.setState({ error: "Error networking!" })333 console.log(err);334 })335 }336 }).catch(err => {337 this.setState({ error: err.message })338 console.log(err);339 }).finally(() => {340 this.setState({ loading: false });341 });342 }343 getTest() {344 this.get("test_info", { passcode: this.state.login.passcode }, test => {345 if (test.runtest_can) {346 this.setState({ test, error: null, login: null });347 if (test.runtest_can.test_end_dttm) {348 let test_end_dttm = new Date(test.runtest_can.test_end_dttm.replace(" ", "T"));349 var timer = setInterval(() => {350 if (this.state.run_test) {351 clearInterval(timer);352 }353 else if (test_end_dttm.getTime() > this.now()) {354 this.setState({ testEnded: false, testEndTimeLeft: this.timeDiff(test_end_dttm) });355 }356 else {357 this.setState({ testEnded: true })358 clearInterval(timer);359 }360 }, 1000);361 }362 }363 else {364 this.setState({ error: "Invalid passcode" })365 }366 })367 }368 runTest() {369 this.get("run_test", { passcode: this.state.test.runtest_can.pswd }, (run_test) => {370 if (run_test.success) {371 let test_end_dttm = new Date(run_test.runtest_can.test_end_dttm.replace(" ", "T"));372 var timer = setInterval(() => {373 if (test_end_dttm.getTime() > this.now() && this.state.run_test && !this.state.testEnded) {374 this.setState({ testEnded: false, testEndTimeLeft: this.timeDiff(test_end_dttm) });375 }376 else {377 this.setState({ testEnded: true });378 if (this.state.run_test) this.saveAnswerAndFinish();379 clearInterval(timer);380 }381 }, 1000);382 this.setState({ run_test, error: null });383 }384 else this.setState({ error: run_test.message ? run_test.message : "Some error occurred!" });385 });386 }387 saveAnswerAndShow(question_index) {388 this.get("save_answer",389 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 2390 ?391 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, run_test_option_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_option, present_ques_id: question_index }392 :393 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 3394 ?395 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, run_test_option_ids: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_options, present_ques_id: question_index }396 :397 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, answer_body: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].ans_body, present_ques_id: question_index },398 (response) => {399 if (response.success) {400 let run_test = this.state.run_test;401 run_test.runtest_can.present_ques_id = question_index;402 this.setState({ run_test });403 }404 else {405 this.setState({ error: response.message });406 }407 }408 )409 }410 saveAnswerAndFinish() {411 this.get("save_answer",412 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 2413 ?414 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, run_test_option_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_option, present_ques_id: this.state.run_test.runtest_can.present_ques_id }415 :416 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 3417 ?418 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, run_test_option_ids: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_options, present_ques_id: this.state.run_test.runtest_can.present_ques_id }419 :420 { passcode: this.state.run_test.runtest_can.pswd, run_test_id: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].id, answer_body: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].ans_body, present_ques_id: this.state.run_test.runtest_can.present_ques_id },421 (response) => {422 if (response.success) {423 this.get("finish_test", { passcode: this.state.run_test.runtest_can.pswd }, (response2) => {424 if (response2.success) {425 this.setState({ run_test: null, testEnded: true });426 }427 else this.setState({ error: response2.message });428 });429 }430 else {431 this.setState({ error: response.message });432 }433 }434 )435 }436 render() {437 return (438 <PaperProvider>439 <StatusBar />440 <Portal>441 <Modal442 dismissable={false}443 visible={this.state.loading}444 theme={theme}445 >446 <ActivityIndicator />447 </Modal>448 </Portal>449 {450 this.state.login ?451 <View style={styles.login} theme={theme}>452 <View style={styles.loginPasscodeContainer}>453 <TextInput454 label="Passcode"455 style={styles.loginPasscode}456 value={this.state.login.passcode}457 mode="outlined"458 secureTextEntry459 theme={theme}460 onChangeText={text => {461 this.setState({ login: { ...this.state.login, passcode: text } })462 }}463 onSubmitEditing={this.getTest.bind(this)}464 />465 <Button466 style={styles.loginButton}467 contentStyle={styles.loginButtonContent}468 labelStyle={styles.loginButtonText}469 mode="contained"470 color="#42c5f5"471 onPress={this.getTest.bind(this)}472 >Continue</Button>473 </View>474 <View style={styles.loginLogoContainer}>475 <Image style={styles.loginLogo} source={magnox_logo} />476 </View>477 </View>478 :479 this.state.test480 ?481 <View style={styles.test}>482 <Surface style={styles.top}>483 <View style={styles.topLogo}>484 <Image style={styles.testLogo} source={magnox_logo} />485 {486 this.state.run_test ?487 <View>488 <Caption>Time left to end</Caption>489 <Title>{this.state.testEndTimeLeft}</Title>490 </View>491 :492 null493 }494 </View>495 {496 this.state.run_test ?497 <Button498 style={styles.loginButton}499 contentStyle={styles.loginButtonContent}500 labelStyle={styles.loginButtonText}501 mode="contained"502 color="#42c5f5"503 onPress={() => this.saveAnswerAndFinish()}504 >Exit</Button>505 :506 <Button507 style={styles.loginButton}508 contentStyle={styles.loginButtonContent}509 labelStyle={styles.loginButtonText}510 mode="contained"511 color="#42c5f5"512 onPress={() => this.setState(this._state)}513 >Exit</Button>514 }515 </Surface>516 <ScrollView>517 {518 !this.state.run_test ?519 <View style={styles.testContainer}>520 <Surface style={styles.testCanDetails}>521 <Caption>522 Name523 </Caption>524 <Title>525 {this.state.test.user_details.first_name} 526 {this.state.test.user_details.last_name}527 </Title>528 <Caption>529 Email530 </Caption>531 <Subheading>532 {this.state.test.user_details.email}533 </Subheading>534 <Caption>535 Phone536 </Caption>537 <Subheading>538 {this.state.test.user_details.phone}539 </Subheading>540 <Caption>541 Program542 </Caption>543 <Subheading>544 {this.state.test.program.title}545 </Subheading>546 {547 this.state.test.course548 ?549 <View>550 <Caption>551 Course552 </Caption>553 <Subheading>554 {this.state.test.course.title} 555 </Subheading>556 </View>557 :558 null559 }560 </Surface>561 <Surface style={styles.testDetails}>562 <Title style={styles.testTitle}>563 {this.state.test.test.title}564 </Title>565 <Surface style={styles.testInfo}>566 {567 this.state.test.test_pub.publish_type == 1568 ?569 <View>570 <Caption>571 Start Time572 </Caption>573 <Subheading>574 Any575 </Subheading>576 </View>577 :578 this.state.test.test_pub.publish_type == 2579 ?580 <View>581 <Caption>582 Start Time583 </Caption>584 <Subheading>585 {this.then(this.state.test.test_pub.start_datetm.replace(" ", "T"))}586 </Subheading>587 </View>588 :589 <View>590 <Caption>591 Start Time592 </Caption>593 <Subheading>594 from {this.then(this.state.test.test_pub.start_datetm.replace(" ", "T"))} to {this.then(this.state.test.test_pub.end_datetm.replace(" ", "T"))}595 </Subheading>596 </View>597 }598 <View>599 <Caption>600 Duration601 </Caption>602 <Subheading>603 {this.state.test.test.duration} Minutes604 </Subheading>605 </View>606 </Surface>607 <Surface style={styles.testSections}>608 {609 this.state.test.sections.map(section => <View style={styles.testSection}>610 <Caption>611 {section.section_name}612 </Caption>613 <Subheading>614 {section.count} Questions615 </Subheading>616 </View>)617 }618 </Surface>619 <Surface style={styles.testInstructions}>620 <Subheading>Instructions</Subheading>621 {622 Platform.OS === 'web'623 ?624 <div dangerouslySetInnerHTML={{ __html: this.state.test.test.details }} />625 :626 <HTMLView value={this.state.test.test.details} />627 }628 </Surface>629 {630 this.state.test.runtest_can.test_start_flag631 ?632 <Surface style={styles.testEntry}>633 <View>634 <Caption>Test attempted at</Caption>635 <Title>{this.then(this.state.test.runtest_can.test_start_dttm.replace(" ", "T"))}</Title>636 </View>637 {638 this.state.testEnded639 ?640 <View>641 <Caption>Test ended at</Caption>642 <Title>{this.then(this.state.test.runtest_can.test_end_dttm.replace(" ", "T"))}</Title>643 </View>644 :645 <View>646 <Caption>Time left to end</Caption>647 <Title>{this.state.testEndTimeLeft}</Title>648 <Button649 style={styles.loginButton}650 contentStyle={styles.loginButtonContent}651 labelStyle={styles.loginButtonText}652 mode="contained"653 color="#42c5f5"654 onPress={this.runTest.bind(this)}655 >Re-enter</Button>656 </View>657 }658 </Surface>659 :660 <Surface style={styles.testEntry}>661 {662 this.state.testEntryTimeLeft663 ?664 <View>665 <Caption>Time left to start</Caption>666 <Title>{this.state.testEntryTimeLeft}</Title>667 </View>668 :669 this.state.test.test_pub.publish_type != 1 && new Date(this.state.test.test_pub.end_datetm.replace(" ", "T")).getTime() < this.now()670 ?671 <View>672 <Caption>Time to attempt test is over at</Caption>673 <Title>{this.then(this.state.test.test_pub.end_datetm.replace(" ", "T"))}</Title>674 </View>675 :676 <Button677 style={styles.loginButton}678 contentStyle={styles.loginButtonContent}679 labelStyle={styles.loginButtonText}680 mode="contained"681 color="#42c5f5"682 onPress={() => {683 let start_datetm = this.state.test.test_pub.publish_type == 1 ? new Date(this.now()) : new Date(this.state.test.test_pub.start_datetm.replace(" ", "T"));684 let timer = setInterval(() => {685 if (start_datetm.getTime() < this.now()) {686 clearInterval(timer);687 this.get("start_test", { passcode: this.state.test.runtest_can.pswd }, (response) => {688 if (response.success) {689 this.runTest.bind(this)();690 this.setState({ error: null, testEntryTimeLeft: null });691 }692 else this.setState({ error: response.message ? response.message : "Some error occurred!", testEntryTimeLeft: null });693 });694 }695 else {696 this.setState({697 testEntryTimeLeft: this.timeDiff(start_datetm)698 })699 }700 }, 1000);701 }}702 >Continue</Button>703 }704 </Surface>705 }706 </Surface>707 </View>708 :709 <View style={styles.runTestContainer}>710 {711 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id]712 ?713 <Surface style={styles.question}>714 <Subheading>Question {this.state.run_test.runtest_can.present_ques_id + 1} of {this.state.run_test.questions.length}</Subheading>715 {716 Platform.OS === 'web'717 ?718 <div dangerouslySetInnerHTML={{ __html: this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].qbody }} />719 :720 <HTMLView value={this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].qbody} />721 }722 {723 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 2724 ?725 <RadioButton.Group value={this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_option} onValueChange={(val) => {726 let run_test = this.state.run_test;727 run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_option = val;728 run_test.questions[this.state.run_test.runtest_can.present_ques_id].status = 1;729 this.setState({ run_test });730 }} style={styles.questionT2}>731 {this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].options.map(option => <RadioButton.Item label={732 Platform.OS === 'web'733 ?734 <div dangerouslySetInnerHTML={{ __html: option.body }} />735 :736 <HTMLView value={option.body} />737 } value={option.id} />)}738 </RadioButton.Group>739 :740 this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].type_id == 3741 ?742 <View style={styles.questionT3}>743 {this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].options.map(option, index => <Checkbox.Item label={744 Platform.OS === 'web'745 ?746 <div dangerouslySetInnerHTML={{ __html: option.body }} />747 :748 <HTMLView value={option.body} />749 }750 onPress={() => {751 let run_test = this.state.run_test;752 if (option.id in run_test.questions[run_test.runtest_can.present_ques_id].selected_options) {753 run_test.questions[run_test.runtest_can.present_ques_id].selected_options = run_test.questions[run_test.runtest_can.present_ques_id].selected_options.filter(e => e != option.id);754 }755 else {756 run_test.questions[run_test.runtest_can.present_ques_id].selected_options.push(option.id);757 }758 run_test.questions[run_test.runtest_can.present_ques_id].status = 1;759 this.setState({ run_test });760 }}761 status={option.id in this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].selected_options ? 'checked' : 'unchecked'} />)}762 </View>763 :764 <TextInput765 multiline766 label="Answer"767 style={styles.questionT1}768 value={this.state.run_test.questions[this.state.run_test.runtest_can.present_ques_id].ans_body}769 onChangeText={text => {770 let run_test = this.state.run_test;771 run_test.questions[run_test.runtest_can.present_ques_id].ans_body = text;772 run_test.questions[run_test.runtest_can.present_ques_id].status = 1;773 this.setState({ run_test });774 }}775 />776 }777 <Surface style={styles.runTestControls}>778 <Button779 style={styles.loginButton}780 contentStyle={styles.loginButtonContent}781 labelStyle={styles.loginButtonText}782 mode="contained"783 color="#42c5f5"784 onPress={() => this.saveAnswerAndShow((parseInt(this.state.run_test.runtest_can.present_ques_id) - 1) % this.state.run_test.questions.length)}785 >Previous</Button>786 <Button787 style={styles.loginButton}788 contentStyle={styles.loginButtonContent}789 labelStyle={styles.loginButtonText}790 mode="contained"791 color="#42c5f5"792 onPress={() => {793 let run_test = this.state.run_test;794 if (run_test.questions[run_test.runtest_can.present_ques_id].type_id == 2) {795 run_test.questions[run_test.runtest_can.present_ques_id].selected_option = 0;796 }797 else if (run_test.questions[run_test.runtest_can.present_ques_id].type_id == 3) {798 run_test.questions[run_test.runtest_can.present_ques_id].selected_options = [];799 }800 else {801 run_test.questions[run_test.runtest_can.present_ques_id].ans_body = null;802 }803 run_test.questions[run_test.runtest_can.present_ques_id].status = 0;804 this.setState({ run_test })805 }}806 >Clear</Button>807 <Button808 style={styles.loginButton}809 contentStyle={styles.loginButtonContent}810 labelStyle={styles.loginButtonText}811 mode="contained"812 color="#42c5f5"813 onPress={() => {814 if (this.state.run_test.runtest_can.present_ques_id == this.state.run_test.questions.length - 1) this.saveAnswerAndFinish();815 else this.saveAnswerAndShow((parseInt(this.state.run_test.runtest_can.present_ques_id) + 1) % this.state.run_test.questions.length)816 }817 }818 >{this.state.run_test.runtest_can.present_ques_id == this.state.run_test.questions.length - 1 ? "Finish" : "Next"}</Button>819 </Surface>820 </Surface>821 :822 null823 }824 <Surface style={styles.runTestQIndicesContainer}>825 <ScrollView>826 <View style={styles.runTestQIndices}>827 {this.state.run_test.questions.map((question, index) => {828 return <TouchableOpacity style={{ margin: 5 }} onPress={() => this.saveAnswerAndShow(index)}>829 <Avatar.Text style={{ backgroundColor: this.state.run_test.runtest_can.present_ques_id == index ? "#42c5f5" : question.status == 0 ? "#ff5050" : "#50ff50" }} size={50} label={index + 1} />830 </TouchableOpacity>831 })}832 </View>833 </ScrollView>834 </Surface>835 </View>836 }837 </ScrollView>838 </View>839 :840 null841 }842 <Snackbar843 visible={this.state.error}844 onDismiss={() => {845 this.setState({ error: false });846 }}847 style={styles.error}848 action={{849 label: 'Close',850 onPress: () => this.setState({ error: false })851 }}852 theme={theme}853 >854 <Text style={styles.errorText}>{this.state.error}</Text>855 </Snackbar>856 </PaperProvider >857 );858 }859 timeDiff(date) {860 let diff = new Date(date.getTime() - this.now());861 return (diff.getUTCMonth() ? diff.getUTCMonth() + " month(s) " : "") +862 ((diff.getUTCDate() - 1) > 0 ? (diff.getUTCDate() - 1) + " day(s) " : "") +863 (diff.getUTCHours() ? diff.getUTCHours() + " hour(s) " : "") +864 (diff.getUTCMinutes() ? diff.getUTCMinutes() + " minute(s) " : "") +865 (diff.getUTCSeconds() ? diff.getUTCSeconds() + " second(s) " : "");866 }867 now() {868 let curdate = new Date();869 return curdate.getTime() + (Platform.OS === 'web' ? curdate.getTimezoneOffset() * 60000 : 0);870 }871 then(date_str) {872 let curdate = new Date();873 let date = new Date(date_str);874 date = new Date(date.getTime() - (Platform.OS === 'web' ? curdate.getTimezoneOffset() * 60000 : 0));875 return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();876 }877}...
test_features_runner.py
Source:test_features_runner.py
...88 UniformRangeSelectionActivationTest89layers = tf.keras.layers90class FeatureNetworkTest(unittest.TestCase):91 def test_edit_error_method(self):92 EditActivationErrorMethod(self).run_test()93 def test_change_qc_attr(self):94 ChangeFinalWeightQCAttrTest(self).run_test()95 ChangeFinalActivationQCAttrTest(self).run_test()96 def test_bias_correction_dw(self):97 BiasCorrectionDepthwiseTest(self).run_test()98 def test_lut_quantizer(self):99 LUTQuantizerTest(self).run_test()100 def test_remove_upper_bound(self):101 RemoveUpperBoundTest(self).run_test()102 def test_reused_separable_mixed_precision(self):103 ReusedSeparableMixedPrecisionTest(self).run_test()104 def test_reused_layer_mixed_precision(self):105 ReusedLayerMixedPrecisionTest(self).run_test()106 def test_reuse_separable(self):107 ReusedSeparableTest(self).run_test()108 def test_mixed_precision_search_kpi_2bits_avg(self):109 MixedPercisionSearchKPI2BitsAvgTest(self).run_test()110 def test_mixed_precision_search_kpi_4bits_avg(self):111 MixedPercisionSearchKPI4BitsAvgTest(self).run_test()112 def test_mixed_precision_search(self):113 MixedPercisionSearchTest(self).run_test()114 def test_mixed_precision_activation_disabled(self):115 MixedPrecisionActivationDisabled(self).run_test()116 def test_mixed_precision_dw(self):117 MixedPercisionDepthwiseTest(self).run_test()118 def test_mixed_precision_activation_search(self):119 MixedPrecisionActivationSearchTest(self).run_test()120 def test_mixed_precision_activation_only(self):121 MixedPrecisionActivationOnlyTest(self).run_test()122 def test_mixed_precision_activation_only_weights_disabled(self):123 MixedPrecisionActivationOnlyWeightsDisabledTest(self).run_test()124 def test_mixed_precision_activation_search_kpi_4bits_avg(self):125 MixedPrecisionActivationSearchKPI4BitsAvgTest(self).run_test()126 def test_mixed_precision_activation_search_kpi_2bits_avg(self):127 MixedPrecisionActivationSearchKPI2BitsAvgTest(self).run_test()128 def test_mixed_precision_activation_dw(self):129 MixedPrecisionActivationDepthwiseTest(self).run_test()130 def test_mixed_precision_activation_dw_4bit(self):131 MixedPrecisionActivationDepthwise4BitTest(self).run_test()132 def test_mixed_precision_activation_add(self):133 MixedPrecisionActivationAddLayerTest(self).run_test()134 def test_mixed_precision_activation_split(self):135 MixedPrecisionActivationSplitLayerTest(self).run_test()136 def test_mixed_precision_activation_multiple_inputs(self):137 MixedPrecisionActivationMultipleInputsTest(self).run_test()138 def test_mixed_precision_total_kpi(self):139 MixedPrecisionTotalKPISearchTest(self).run_test()140 def test_mixed_precision_multiple_kpis_tight(self):141 MixedPrecisionMultipleKPIsTightSearchTest(self).run_test()142 def test_mixed_precision_reduced_total_kpi(self):143 MixedPrecisionReducedTotalKPISearchTest(self).run_test()144 def test_name_filter(self):145 NameFilterTest(self).run_test()146 def test_scope_filter(self):147 ScopeFilterTest(self).run_test()148 def test_type_filter(self):149 TypeFilterTest(self).run_test()150 def test_add_same(self):151 AddSameTest(self).run_test()152 def test_scale_equalization(self):153 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2D(3, 4)).run_test()154 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2DTranspose(3, 4)).run_test()155 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4)).run_test()156 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2D(3, 4),157 zero_pad=True).run_test()158 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2DTranspose(3, 4),159 zero_pad=True).run_test()160 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4),161 zero_pad=True).run_test()162 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2D(3, 4),163 act_node=tf.nn.relu).run_test()164 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2DTranspose(3, 4),165 act_node=tf.nn.relu).run_test()166 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4),167 act_node=tf.nn.relu).run_test()168 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2D(3, 4),169 act_node=tf.nn.relu, zero_pad=True).run_test()170 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.Conv2DTranspose(3, 4),171 act_node=tf.nn.relu, zero_pad=True).run_test()172 ScaleEqualizationTest(self, first_op2d=layers.Conv2D(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4),173 act_node=tf.nn.relu, zero_pad=True).run_test()174 ScaleEqualizationTest(self, first_op2d=layers.Conv2DTranspose(3, 4), second_op2d=layers.Conv2D(3, 4)).run_test()175 ScaleEqualizationTest(self, first_op2d=layers.DepthwiseConv2D(3, 4), second_op2d=layers.Conv2DTranspose(3, 4)176 ).run_test()177 ScaleEqualizationTest(self, first_op2d=layers.DepthwiseConv2D(3, 4), second_op2d=layers.Conv2D(3, 4),178 zero_pad=True).run_test()179 ScaleEqualizationTest(self, first_op2d=layers.Conv2DTranspose(3, 4), second_op2d=layers.Conv2DTranspose(3, 4),180 zero_pad=True).run_test()181 ScaleEqualizationTest(self, first_op2d=layers.DepthwiseConv2D(3, 4), second_op2d=layers.Conv2D(3, 4),182 act_node=tf.nn.relu).run_test()183 ScaleEqualizationTest(self, first_op2d=layers.Conv2DTranspose(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4),184 act_node=tf.nn.relu).run_test()185 ScaleEqualizationTest(self, first_op2d=layers.Conv2DTranspose(3, 4), second_op2d=layers.Conv2DTranspose(3, 4),186 act_node=tf.nn.relu, zero_pad=True).run_test()187 ScaleEqualizationTest(self, first_op2d=layers.DepthwiseConv2D(3, 4), second_op2d=layers.DepthwiseConv2D(3, 4),188 act_node=tf.nn.relu, zero_pad=True).run_test()189 def test_multiple_inputs_model(self):190 MultipleInputsModelTest(self).run_test()191 def test_output_in_middle(self):192 OutputInMiddleTest(self).run_test()193 def test_conv_bn_relu_residual(self):194 ConvBnReluResidualTest(self).run_test()195 def test_split_concat(self):196 SplitConcatenateTest(self).run_test()197 def test_multiple_output_nodes_multiple_tensors(self):198 MultipleOutputNodesMultipleTensors(self).run_test()199 def test_reused_layer(self):200 ReusedLayerTest(self).run_test()201 def test_nested_model_multiple_inputs(self):202 NestedModelMultipleInputsTest(self).run_test()203 def test_nested_model_multiple_outputs(self):204 NestedModelMultipleOutputsTest(self).run_test()205 def test_nested_model_unused_inputs_outputs(self):206 NestedModelUnusedInputsOutputsTest(self).run_test()207 def test_nested_model(self):208 NestedTest(self).run_test()209 NestedTest(self, is_inner_functional=False).run_test()210 def test_shift_neg_activation_conv2d(self):211 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, 4),212 activation_op_to_test=layers.Activation('swish')).run_test()213 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, 4, strides=3),214 activation_op_to_test=layers.Activation('swish')).run_test()215 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (3, 4), strides=2),216 activation_op_to_test=layers.Activation('swish')).run_test()217 def test_shift_neg_activation_conv2d_pad_same(self):218 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (5, 7), padding='same'),219 activation_op_to_test=layers.Activation('swish')).run_test()220 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (5, 7), padding='same', strides=3),221 activation_op_to_test=layers.Activation('swish')).run_test()222 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (7, 5), padding='same', strides=4),223 activation_op_to_test=layers.Activation('swish')).run_test()224 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (8, 10), padding='same', strides=5),225 activation_op_to_test=layers.Activation('swish')).run_test()226 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (10, 8), padding='same', strides=6),227 activation_op_to_test=layers.Activation('swish')).run_test()228 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (5, 7), padding='same', strides=(4, 6)),229 activation_op_to_test=layers.Activation('swish')).run_test()230 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (7, 5), padding='same', strides=(6, 4)),231 activation_op_to_test=layers.Activation('swish')).run_test()232 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (8, 10), padding='same', strides=(5, 7)),233 activation_op_to_test=layers.Activation('swish')).run_test()234 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (10, 8), padding='same', strides=(7, 5)),235 activation_op_to_test=layers.Activation('swish')).run_test()236 def test_shift_neg_activation_pad_conv2d(self):237 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (5, 7)),238 activation_op_to_test=layers.Activation('swish'),239 use_pad_layer=True).run_test()240 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (5, 7), strides=3),241 activation_op_to_test=layers.Activation('swish'),242 use_pad_layer=True).run_test()243 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (7, 5), strides=4),244 activation_op_to_test=layers.Activation('swish'),245 use_pad_layer=True).run_test()246 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (8, 10), strides=5),247 activation_op_to_test=layers.Activation('swish'),248 use_pad_layer=True).run_test()249 ShiftNegActivationTest(self, linear_op_to_test=layers.Conv2D(3, (10, 8), strides=6),250 activation_op_to_test=layers.Activation('swish'),251 use_pad_layer=True).run_test()252 def test_shift_neg_activation_dense(self):253 ShiftNegActivationTest(self, linear_op_to_test=layers.Dense(3),254 activation_op_to_test=tf.nn.leaky_relu, input_shape=(8, 3)).run_test()255 ShiftNegActivationTest(self, linear_op_to_test=layers.Dense(4),256 activation_op_to_test=layers.ReLU(negative_slope=0.99),257 bypass_op_list=[layers.GlobalAveragePooling2D()]).run_test()258 def test_shift_neg_activation_pad_dense(self):259 ShiftNegActivationTest(self, linear_op_to_test=layers.Dense(3),260 activation_op_to_test=PReLU(alpha_initializer='ones'), use_pad_layer=True).run_test()261 ShiftNegActivationTest(self, linear_op_to_test=layers.Dense(4),262 activation_op_to_test=ELU(), use_pad_layer=True).run_test()263 def test_shift_neg_activation_depthwise(self):264 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D((4, 5)),265 activation_op_to_test=tf.nn.silu).run_test()266 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D(5, strides=3),267 activation_op_to_test=tf.nn.elu).run_test()268 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D((5, 4), strides=4),269 activation_op_to_test=tf.nn.leaky_relu).run_test()270 def test_shift_neg_activation_depthwise_pad_same(self):271 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D(depth_multiplier=1, kernel_size=(7, 8),272 padding='same', strides=5),273 activation_op_to_test=layers.Activation('swish')).run_test()274 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D(depth_multiplier=3, kernel_size=(8, 7),275 padding='same', strides=6),276 activation_op_to_test=layers.Activation('gelu')).run_test()277 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D(kernel_size=4, padding='same'),278 activation_op_to_test=layers.Activation('selu')).run_test()279 def test_shift_neg_activation_pad_depthwise(self):280 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D((4, 5)),281 activation_op_to_test=tf.nn.gelu, use_pad_layer=True).run_test()282 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D(5, strides=3),283 activation_op_to_test=tf.nn.selu, use_pad_layer=True).run_test()284 ShiftNegActivationTest(self, linear_op_to_test=layers.DepthwiseConv2D((5, 4), strides=4),285 activation_op_to_test=tf.nn.swish, use_pad_layer=True).run_test()286 def test_shift_neg_activation_post_add(self):287 ShiftNegActivationPostAddTest(self,288 linear_op_to_test=layers.Conv2D(3, 4),289 activation_op_to_test=layers.Activation('swish'),290 post_add_nbits=7).run_test()291 def test_activation_decomposition(self):292 ActivationDecompositionTest(self, activation_function='swish').run_test()293 ActivationDecompositionTest(self, activation_function='relu').run_test()294 ActivationDecompositionTest(self, activation_function='tanh').run_test()295 ActivationDecompositionTest(self, activation_function='softmax').run_test()296 def test_layer_fusing(self):297 LayerFusingTest1(self).run_test()298 LayerFusingTest2(self).run_test()299 LayerFusingTest3(self).run_test()300 LayerFusingTest4(self).run_test()301 def test_conv2d_bn_concant(self):302 Conv2DBNConcatnFoldingTest(self).run_test()303 def test_activation_scaling_relu6(self):304 ReLUBoundToPOTNetTest(self).run_test()305 def test_layer_activation_softmax_shift(self):306 SoftmaxShiftTest(self, layers.Dense(20, activation='softmax'), None).run_test()307 def test_layer_softmax_shift(self):308 SoftmaxShiftTest(self, layers.Dense(20), layers.Softmax()).run_test()309 def test_function_softmax_shift(self):310 SoftmaxShiftTest(self, layers.Dense(20), tf.nn.softmax).run_test()311 def test_multiple_inputs_node(self):312 MultipleInputsNodeTests(self).run_test()313 def test_multiple_outputs_node(self):314 MultipleOutputsNodeTests(self).run_test()315 def test_conv2dbn_folding(self):316 Conv2DBNFoldingTest(self).run_test()317 def test_residual_collapsing(self):318 ResidualCollapsingTest1(self).run_test()319 ResidualCollapsingTest2(self).run_test()320 def test_separableconv2dbn_folding(self):321 SeparableConv2DBNFoldingTest(self).run_test()322 def test_dwbn_folding(self):323 DepthwiseConv2DBNFoldingTest(self).run_test()324 def test_dwbn_high_multipler_folding(self):325 DepthwiseConv2DBNFoldingHighMultiplierTest(self).run_test()326 def test_conv2dtransposebn_folding(self):327 Conv2DTransposeBNFoldingTest(self).run_test()328 def test_linear_collapsing(self):329 TwoConv2DCollapsingTest(self).run_test()330 ThreeConv2DCollapsingTest(self).run_test()331 FourConv2DCollapsingTest(self).run_test()332 SixConv2DCollapsingTest(self).run_test()333 def test_decompose_separable_conv(self):334 DecomposeSeparableConvTest(self).run_test()335 def test_decompose_separable_conv_high_multiplier(self):336 DecomposeSeparableConvTest(self, depth=2).run_test()337 def test_input_scale(self):338 InputScalingDenseTest(self).run_test()339 InputScalingConvTest(self).run_test()340 InputScalingDWTest(self).run_test()341 InputScalingZeroPadTest(self).run_test()342 def test_multi_input_to_node(self):343 MultiInputsToNodeTest(self).run_test()344 def test_gptq(self):345 GradientPTQTest(self).run_test()346 GradientPTQWeightsUpdateTest(self).run_test()347 GradientPTQLearnRateZeroTest(self).run_test()348 def test_split_conv_bug(self):349 SplitConvBugTest(self).run_test()350 def test_symmetric_threshold_selection_activation(self):351 SymmetricThresholdSelectionActivationTest(self, QuantizationErrorMethod.NOCLIPPING).run_test()352 SymmetricThresholdSelectionActivationTest(self, QuantizationErrorMethod.MSE).run_test()353 SymmetricThresholdSelectionActivationTest(self, QuantizationErrorMethod.MAE).run_test()354 SymmetricThresholdSelectionActivationTest(self, QuantizationErrorMethod.LP).run_test()355 SymmetricThresholdSelectionActivationTest(self, QuantizationErrorMethod.KL).run_test()356 def test_uniform_range_selection_activation(self):357 UniformRangeSelectionActivationTest(self, QuantizationErrorMethod.NOCLIPPING).run_test()358 UniformRangeSelectionActivationTest(self, QuantizationErrorMethod.MSE).run_test()359 UniformRangeSelectionActivationTest(self, QuantizationErrorMethod.MAE).run_test()360 UniformRangeSelectionActivationTest(self, QuantizationErrorMethod.LP).run_test()361 UniformRangeSelectionActivationTest(self, QuantizationErrorMethod.KL).run_test()362 def test_multi_head_attention(self):363 q_seq_len, kv_seq_len = 5, 6364 q_dim, k_dim, v_dim = 11, 12, 13365 num_heads, qk_proj_dim, v_proj_dim = 3, 4, 7366 attention_axes = [1, 3]367 num_iterations = 9368 for separate_key_value in [False, True]:369 MultiHeadAttentionTest(self, [(q_seq_len, q_dim),370 (kv_seq_len, k_dim),371 (kv_seq_len, v_dim)],372 num_heads, qk_proj_dim, v_proj_dim, None,373 separate_key_value=separate_key_value, output_dim=15).run_test()374 input_shapes = [(2, num_iterations, q_seq_len, q_dim),375 (2, num_iterations, kv_seq_len, k_dim),376 (2, num_iterations, kv_seq_len, v_dim)]377 MultiHeadAttentionTest(self, input_shapes,378 num_heads, qk_proj_dim, v_proj_dim, attention_axes,379 separate_key_value=separate_key_value, output_dim=14).run_test()380 MultiHeadAttentionTest(self, input_shapes,381 num_heads, qk_proj_dim, v_proj_dim, attention_axes,382 separate_key_value=separate_key_value, output_dim=None).run_test()383 MultiHeadAttentionTest(self, input_shapes,384 num_heads, qk_proj_dim, v_proj_dim, None,385 separate_key_value=separate_key_value, output_dim=14).run_test()386if __name__ == '__main__':...
conformance.spec.ts
Source:conformance.spec.ts
...5 * dynamically generated using generate_conformance.ts script see README.md file6 * for details on how to re-generate or change this file.7 */8describe("conformance", () => {9 function run_test(doc: any, patch: any[], error: any, expected: any) {10 try {11 let result = Patch.apply(doc, ...patch);12 if(error) {13 throw new Error("Missing error: " + error);14 } else {15 expect(result).eql(expected);16 }17 } catch(e) {18 if(error) {19 expect(!!e.message, error).be.true;20 } else {21 expect("Unexpected error: " + e.message + ", missing expected: " + JSON.stringify(expected)).eql('to pass');22 }23 }24 }25 describe("tests.json - main tests", () => {26 it("empty list, empty docs", () => {27 run_test({}, [], undefined, {});28 });29 it("empty patch list", () => {30 run_test({"foo":1}, [], undefined, {"foo":1});31 });32 it("rearrangements OK?", () => {33 run_test({"foo":1,"bar":2}, [], undefined, {"bar":2,"foo":1});34 });35 it("rearrangements OK? How about one level down ... array", () => {36 run_test([{"foo":1,"bar":2}], [], undefined, [{"bar":2,"foo":1}]);37 });38 it("rearrangements OK? How about one level down...", () => {39 run_test({"foo":{"foo":1,"bar":2}}, [], undefined, {"foo":{"bar":2,"foo":1}});40 });41 it("add replaces any existing field", () => {42 run_test({"foo":null}, [{"op":"add","path":"/foo","value":1}], undefined, {"foo":1});43 });44 it("toplevel array", () => {45 run_test([], [{"op":"add","path":"/0","value":"foo"}], undefined, ["foo"]);46 });47 it("toplevel array, no change", () => {48 run_test(["foo"], [], undefined, ["foo"]);49 });50 it("toplevel object, numeric string", () => {51 run_test({}, [{"op":"add","path":"/foo","value":"1"}], undefined, {"foo":"1"});52 });53 it("toplevel object, integer", () => {54 run_test({}, [{"op":"add","path":"/foo","value":1}], undefined, {"foo":1});55 });56 xit("Toplevel scalar values OK?", () => {57 run_test("foo", [{"op":"replace","path":"","value":"bar"}], undefined, "bar");58 });59 it("replace object document with array document?", () => {60 run_test({}, [{"op":"add","path":"","value":[]}], undefined, []);61 });62 it("replace array document with object document?", () => {63 run_test([], [{"op":"add","path":"","value":{}}], undefined, {});64 });65 it("append to root array document?", () => {66 run_test([], [{"op":"add","path":"/-","value":"hi"}], undefined, ["hi"]);67 });68 it("Add, / target", () => {69 run_test({}, [{"op":"add","path":"/","value":1}], undefined, {"":1});70 });71 it("Add, /foo/ deep target (trailing slash)", () => {72 run_test({"foo":{}}, [{"op":"add","path":"/foo/","value":1}], undefined, {"foo":{"":1}});73 });74 it("Add composite value at top level", () => {75 run_test({"foo":1}, [{"op":"add","path":"/bar","value":[1,2]}], undefined, {"foo":1,"bar":[1,2]});76 });77 it("Add into composite value", () => {78 run_test({"foo":1,"baz":[{"qux":"hello"}]}, [{"op":"add","path":"/baz/0/foo","value":"world"}], undefined, {"foo":1,"baz":[{"qux":"hello","foo":"world"}]});79 });80 it("conformance #18", () => {81 run_test({"bar":[1,2]}, [{"op":"add","path":"/bar/8","value":"5"}], "Out of bounds (upper)", undefined);82 });83 it("conformance #19", () => {84 run_test({"bar":[1,2]}, [{"op":"add","path":"/bar/-1","value":"5"}], "Out of bounds (lower)", undefined);85 });86 it("conformance #20", () => {87 run_test({"foo":1}, [{"op":"add","path":"/bar","value":true}], undefined, {"foo":1,"bar":true});88 });89 it("conformance #21", () => {90 run_test({"foo":1}, [{"op":"add","path":"/bar","value":false}], undefined, {"foo":1,"bar":false});91 });92 it("conformance #22", () => {93 run_test({"foo":1}, [{"op":"add","path":"/bar","value":null}], undefined, {"foo":1,"bar":null});94 });95 it("0 can be an array index or object element name", () => {96 run_test({"foo":1}, [{"op":"add","path":"/0","value":"bar"}], undefined, {"0":"bar","foo":1});97 });98 it("conformance #24", () => {99 run_test(["foo"], [{"op":"add","path":"/1","value":"bar"}], undefined, ["foo","bar"]);100 });101 it("conformance #25", () => {102 run_test(["foo","sil"], [{"op":"add","path":"/1","value":"bar"}], undefined, ["foo","bar","sil"]);103 });104 it("conformance #26", () => {105 run_test(["foo","sil"], [{"op":"add","path":"/0","value":"bar"}], undefined, ["bar","foo","sil"]);106 });107 it("push item to array via last index + 1", () => {108 run_test(["foo","sil"], [{"op":"add","path":"/2","value":"bar"}], undefined, ["foo","sil","bar"]);109 });110 it("add item to array at index > length should fail", () => {111 run_test(["foo","sil"], [{"op":"add","path":"/3","value":"bar"}], "index is greater than number of items in array", undefined);112 });113 it("test against implementation-specific numeric parsing", () => {114 run_test({"1e0":"foo"}, [{"op":"test","path":"/1e0","value":"foo"}], undefined, {"1e0":"foo"});115 });116 it("test with bad number should fail", () => {117 run_test(["foo","bar"], [{"op":"test","path":"/1e0","value":"bar"}], "test op shouldn't get array element 1", undefined);118 });119 it("conformance #31", () => {120 run_test(["foo","sil"], [{"op":"add","path":"/bar","value":42}], "Object operation on array target", undefined);121 });122 it("value in array add not flattened", () => {123 run_test(["foo","sil"], [{"op":"add","path":"/1","value":["bar","baz"]}], undefined, ["foo",["bar","baz"],"sil"]);124 });125 it("conformance #33", () => {126 run_test({"foo":1,"bar":[1,2,3,4]}, [{"op":"remove","path":"/bar"}], undefined, {"foo":1});127 });128 it("conformance #34", () => {129 run_test({"foo":1,"baz":[{"qux":"hello"}]}, [{"op":"remove","path":"/baz/0/qux"}], undefined, {"foo":1,"baz":[{}]});130 });131 it("conformance #35", () => {132 run_test({"foo":1,"baz":[{"qux":"hello"}]}, [{"op":"replace","path":"/foo","value":[1,2,3,4]}], undefined, {"foo":[1,2,3,4],"baz":[{"qux":"hello"}]});133 });134 it("conformance #36", () => {135 run_test({"foo":[1,2,3,4],"baz":[{"qux":"hello"}]}, [{"op":"replace","path":"/baz/0/qux","value":"world"}], undefined, {"foo":[1,2,3,4],"baz":[{"qux":"world"}]});136 });137 it("conformance #37", () => {138 run_test(["foo"], [{"op":"replace","path":"/0","value":"bar"}], undefined, ["bar"]);139 });140 it("conformance #38", () => {141 run_test([""], [{"op":"replace","path":"/0","value":0}], undefined, [0]);142 });143 it("conformance #39", () => {144 run_test([""], [{"op":"replace","path":"/0","value":true}], undefined, [true]);145 });146 it("conformance #40", () => {147 run_test([""], [{"op":"replace","path":"/0","value":false}], undefined, [false]);148 });149 it("conformance #41", () => {150 run_test([""], [{"op":"replace","path":"/0","value":null}], undefined, [null]);151 });152 it("value in array replace not flattened", () => {153 run_test(["foo","sil"], [{"op":"replace","path":"/1","value":["bar","baz"]}], undefined, ["foo",["bar","baz"]]);154 });155 it("replace whole document", () => {156 run_test({"foo":"bar"}, [{"op":"replace","path":"","value":{"baz":"qux"}}], undefined, {"baz":"qux"});157 });158 it("test replace with missing parent key should fail", () => {159 run_test({"bar":"baz"}, [{"op":"replace","path":"/foo/bar","value":false}], "replace op should fail with missing parent key", undefined);160 });161 it("spurious patch properties", () => {162 run_test({"foo":1}, [{"op":"test","path":"/foo","value":1,"spurious":1}], undefined, {"foo":1});163 });164 it("null value should be valid obj property", () => {165 run_test({"foo":null}, [{"op":"test","path":"/foo","value":null}], undefined, {"foo":null});166 });167 it("null value should be valid obj property to be replaced with something truthy", () => {168 run_test({"foo":null}, [{"op":"replace","path":"/foo","value":"truthy"}], undefined, {"foo":"truthy"});169 });170 it("null value should be valid obj property to be moved", () => {171 run_test({"foo":null}, [{"op":"move","from":"/foo","path":"/bar"}], undefined, {"bar":null});172 });173 it("null value should be valid obj property to be copied", () => {174 run_test({"foo":null}, [{"op":"copy","from":"/foo","path":"/bar"}], undefined, {"foo":null,"bar":null});175 });176 it("null value should be valid obj property to be removed", () => {177 run_test({"foo":null}, [{"op":"remove","path":"/foo"}], undefined, {});178 });179 it("null value should still be valid obj property replace other value", () => {180 run_test({"foo":"bar"}, [{"op":"replace","path":"/foo","value":null}], undefined, {"foo":null});181 });182 it("test should pass despite rearrangement", () => {183 run_test({"foo":{"foo":1,"bar":2}}, [{"op":"test","path":"/foo","value":{"bar":2,"foo":1}}], undefined, {"foo":{"foo":1,"bar":2}});184 });185 it("test should pass despite (nested) rearrangement", () => {186 run_test({"foo":[{"foo":1,"bar":2}]}, [{"op":"test","path":"/foo","value":[{"bar":2,"foo":1}]}], undefined, {"foo":[{"foo":1,"bar":2}]});187 });188 it("test should pass - no error", () => {189 run_test({"foo":{"bar":[1,2,5,4]}}, [{"op":"test","path":"/foo","value":{"bar":[1,2,5,4]}}], undefined, {"foo":{"bar":[1,2,5,4]}});190 });191 it("conformance #55", () => {192 run_test({"foo":{"bar":[1,2,5,4]}}, [{"op":"test","path":"/foo","value":[1,2]}], "test op should fail", undefined);193 });194 xit("Whole document", () => {195 run_test({"foo":1}, [{"op":"test","path":"","value":{"foo":1}}], undefined, undefined);196 });197 it("Empty-string element", () => {198 run_test({"":1}, [{"op":"test","path":"/","value":1}], undefined, {"":1});199 });200 it("conformance #58", () => {201 run_test({"foo":["bar","baz"],"":0,"a/b":1,"c%d":2,"e^f":3,"g|h":4,"i\\j":5,"k\"l":6," ":7,"m~n":8}, [{"op":"test","path":"/foo","value":["bar","baz"]},{"op":"test","path":"/foo/0","value":"bar"},{"op":"test","path":"/","value":0},{"op":"test","path":"/a~1b","value":1},{"op":"test","path":"/c%d","value":2},{"op":"test","path":"/e^f","value":3},{"op":"test","path":"/g|h","value":4},{"op":"test","path":"/i\\j","value":5},{"op":"test","path":"/k\"l","value":6},{"op":"test","path":"/ ","value":7},{"op":"test","path":"/m~0n","value":8}], undefined, {"":0," ":7,"a/b":1,"c%d":2,"e^f":3,"foo":["bar","baz"],"g|h":4,"i\\j":5,"k\"l":6,"m~n":8});202 });203 it("Move to same location has no effect", () => {204 run_test({"foo":1}, [{"op":"move","from":"/foo","path":"/foo"}], undefined, {"foo":1});205 });206 it("conformance #60", () => {207 run_test({"foo":1,"baz":[{"qux":"hello"}]}, [{"op":"move","from":"/foo","path":"/bar"}], undefined, {"baz":[{"qux":"hello"}],"bar":1});208 });209 it("conformance #61", () => {210 run_test({"baz":[{"qux":"hello"}],"bar":1}, [{"op":"move","from":"/baz/0/qux","path":"/baz/1"}], undefined, {"baz":[{},"hello"],"bar":1});211 });212 it("conformance #62", () => {213 run_test({"baz":[{"qux":"hello"}],"bar":1}, [{"op":"copy","from":"/baz/0","path":"/boo"}], undefined, {"baz":[{"qux":"hello"}],"bar":1,"boo":{"qux":"hello"}});214 });215 it("replacing the root of the document is possible with add", () => {216 run_test({"foo":"bar"}, [{"op":"add","path":"","value":{"baz":"qux"}}], undefined, {"baz":"qux"});217 });218 it("Adding to \"/-\" adds to the end of the array", () => {219 run_test([1,2], [{"op":"add","path":"/-","value":{"foo":["bar","baz"]}}], undefined, [1,2,{"foo":["bar","baz"]}]);220 });221 it("Adding to \"/-\" adds to the end of the array, even n levels down", () => {222 run_test([1,2,[3,[4,5]]], [{"op":"add","path":"/2/1/-","value":{"foo":["bar","baz"]}}], undefined, [1,2,[3,[4,5,{"foo":["bar","baz"]}]]]);223 });224 it("test remove with bad number should fail", () => {225 run_test({"foo":1,"baz":[{"qux":"hello"}]}, [{"op":"remove","path":"/baz/1e0/qux"}], "remove op shouldn't remove from array with bad number", undefined);226 });227 it("test remove on array", () => {228 run_test([1,2,3,4], [{"op":"remove","path":"/0"}], undefined, [2,3,4]);229 });230 it("test repeated removes", () => {231 run_test([1,2,3,4], [{"op":"remove","path":"/1"},{"op":"remove","path":"/2"}], undefined, [1,3]);232 });233 it("test remove with bad index should fail", () => {234 run_test([1,2,3,4], [{"op":"remove","path":"/1e0"}], "remove op shouldn't remove from array with bad number", undefined);235 });236 it("test replace with bad number should fail", () => {237 run_test([""], [{"op":"replace","path":"/1e0","value":false}], "replace op shouldn't replace in array with bad number", undefined);238 });239 it("test copy with bad number should fail", () => {240 run_test({"baz":[1,2,3],"bar":1}, [{"op":"copy","from":"/baz/1e0","path":"/boo"}], "copy op shouldn't work with bad number", undefined);241 });242 it("test move with bad number should fail", () => {243 run_test({"foo":1,"baz":[1,2,3,4]}, [{"op":"move","from":"/baz/1e0","path":"/foo"}], "move op shouldn't work with bad number", undefined);244 });245 it("test add with bad number should fail", () => {246 run_test(["foo","sil"], [{"op":"add","path":"/1e0","value":"bar"}], "add op shouldn't add to array with bad number", undefined);247 });248 it("missing 'path' parameter", () => {249 run_test({}, [{"op":"add","value":"bar"}], "missing 'path' parameter", undefined);250 });251 it("'path' parameter with null value", () => {252 run_test({}, [{"op":"add","path":null,"value":"bar"}], "null is not valid value for 'path'", undefined);253 });254 it("invalid JSON Pointer token", () => {255 run_test({}, [{"op":"add","path":"foo","value":"bar"}], "JSON Pointer should start with a slash", undefined);256 });257 it("missing 'value' parameter to add", () => {258 run_test([1], [{"op":"add","path":"/-"}], "missing 'value' parameter", undefined);259 });260 it("missing 'value' parameter to replace", () => {261 run_test([1], [{"op":"replace","path":"/0"}], "missing 'value' parameter", undefined);262 });263 it("missing 'value' parameter to test", () => {264 run_test([null], [{"op":"test","path":"/0"}], "missing 'value' parameter", undefined);265 });266 it("missing value parameter to test - where undef is falsy", () => {267 run_test([false], [{"op":"test","path":"/0"}], "missing 'value' parameter", undefined);268 });269 it("missing from parameter to copy", () => {270 run_test([1], [{"op":"copy","path":"/-"}], "missing 'from' parameter", undefined);271 });272 it("missing from location to copy", () => {273 run_test({"foo":1}, [{"op":"copy","from":"/bar","path":"/foo"}], "missing 'from' location", undefined);274 });275 it("missing from parameter to move", () => {276 run_test({"foo":1}, [{"op":"move","path":""}], "missing 'from' parameter", undefined);277 });278 it("missing from location to move", () => {279 run_test({"foo":1}, [{"op":"move","from":"/bar","path":"/foo"}], "missing 'from' location", undefined);280 });281 xit("duplicate ops", () => {282 run_test({"foo":"bar"}, [{"op":"move","path":"/baz","value":"qux","from":"/foo"}], "patch has two 'op' members", undefined);283 });284 it("unrecognized op should fail", () => {285 run_test({"foo":1}, [{"op":"spam","path":"/foo","value":1}], "Unrecognized op 'spam'", undefined);286 });287 it("test with bad array number that has leading zeros", () => {288 run_test(["foo","bar"], [{"op":"test","path":"/00","value":"foo"}], "test op should reject the array value, it has leading zeros", undefined);289 });290 it("test with bad array number that has leading zeros", () => {291 run_test(["foo","bar"], [{"op":"test","path":"/01","value":"bar"}], "test op should reject the array value, it has leading zeros", undefined);292 });293 it("Removing nonexistent field", () => {294 run_test({"foo":"bar"}, [{"op":"remove","path":"/baz"}], "removing a nonexistent field should fail", undefined);295 });296 it("Removing deep nonexistent path", () => {297 run_test({"foo":"bar"}, [{"op":"remove","path":"/missing1/missing2"}], "removing a nonexistent field should fail", undefined);298 });299 it("Removing nonexistent index", () => {300 run_test(["foo","bar"], [{"op":"remove","path":"/2"}], "removing a nonexistent index should fail", undefined);301 });302 it("Patch with different capitalisation than doc", () => {303 run_test({"foo":"bar"}, [{"op":"add","path":"/FOO","value":"BAR"}], undefined, {"foo":"bar","FOO":"BAR"});304 });305 });306 307 describe("spec_tests.json - RFC6902 spec", () => {308 it("4.1. add with missing object", () => {309 run_test({"q":{"bar":2}}, [{"op":"add","path":"/a/b","value":1}], "path /a does not exist -- missing objects are not created recursively", undefined);310 });311 it("A.1. Adding an Object Member", () => {312 run_test({"foo":"bar"}, [{"op":"add","path":"/baz","value":"qux"}], undefined, {"baz":"qux","foo":"bar"});313 });314 it("A.2. Adding an Array Element", () => {315 run_test({"foo":["bar","baz"]}, [{"op":"add","path":"/foo/1","value":"qux"}], undefined, {"foo":["bar","qux","baz"]});316 });317 it("A.3. Removing an Object Member", () => {318 run_test({"baz":"qux","foo":"bar"}, [{"op":"remove","path":"/baz"}], undefined, {"foo":"bar"});319 });320 it("A.4. Removing an Array Element", () => {321 run_test({"foo":["bar","qux","baz"]}, [{"op":"remove","path":"/foo/1"}], undefined, {"foo":["bar","baz"]});322 });323 it("A.5. Replacing a Value", () => {324 run_test({"baz":"qux","foo":"bar"}, [{"op":"replace","path":"/baz","value":"boo"}], undefined, {"baz":"boo","foo":"bar"});325 });326 it("A.6. Moving a Value", () => {327 run_test({"foo":{"bar":"baz","waldo":"fred"},"qux":{"corge":"grault"}}, [{"op":"move","from":"/foo/waldo","path":"/qux/thud"}], undefined, {"foo":{"bar":"baz"},"qux":{"corge":"grault","thud":"fred"}});328 });329 it("A.7. Moving an Array Element", () => {330 run_test({"foo":["all","grass","cows","eat"]}, [{"op":"move","from":"/foo/1","path":"/foo/3"}], undefined, {"foo":["all","cows","eat","grass"]});331 });332 it("A.8. Testing a Value: Success", () => {333 run_test({"baz":"qux","foo":["a",2,"c"]}, [{"op":"test","path":"/baz","value":"qux"},{"op":"test","path":"/foo/1","value":2}], undefined, {"baz":"qux","foo":["a",2,"c"]});334 });335 it("A.9. Testing a Value: Error", () => {336 run_test({"baz":"qux"}, [{"op":"test","path":"/baz","value":"bar"}], "string not equivalent", undefined);337 });338 it("A.10. Adding a nested Member Object", () => {339 run_test({"foo":"bar"}, [{"op":"add","path":"/child","value":{"grandchild":{}}}], undefined, {"foo":"bar","child":{"grandchild":{}}});340 });341 it("A.11. Ignoring Unrecognized Elements", () => {342 run_test({"foo":"bar"}, [{"op":"add","path":"/baz","value":"qux","xyz":123}], undefined, {"foo":"bar","baz":"qux"});343 });344 it("A.12. Adding to a Non-existent Target", () => {345 run_test({"foo":"bar"}, [{"op":"add","path":"/baz/bat","value":"qux"}], "add to a non-existent target", undefined);346 });347 xit("A.13 Invalid JSON Patch Document", () => {348 run_test({"foo":"bar"}, [{"op":"remove","path":"/baz","value":"qux"}], "operation has two 'op' members", undefined);349 });350 it("A.14. ~ Escape Ordering", () => {351 run_test({"/":9,"~1":10}, [{"op":"test","path":"/~01","value":10}], undefined, {"/":9,"~1":10});352 });353 it("A.15. Comparing Strings and Numbers", () => {354 run_test({"/":9,"~1":10}, [{"op":"test","path":"/~01","value":"10"}], "number is not equal to string", undefined);355 });356 it("A.16. Adding an Array Value", () => {357 run_test({"foo":["bar"]}, [{"op":"add","path":"/foo/-","value":["abc","def"]}], undefined, {"foo":["bar",["abc","def"]]});358 });359 });...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!