Best Python code snippet using pytest-django_python
export_test.py
Source:export_test.py
...96 ValueError, "receiver_tensor example1 must be a Tensor"):97 export.ServingInputReceiver(98 features=features,99 receiver_tensors={"example1": [1]})100 def test_single_feature_single_receiver(self):101 feature = constant_op.constant(5)102 receiver_tensor = array_ops.placeholder(dtypes.string)103 input_receiver = export.ServingInputReceiver(104 feature, receiver_tensor)105 # single feature is automatically named106 feature_key, = input_receiver.features.keys()107 self.assertEqual("feature", feature_key)108 # single receiver is automatically named109 receiver_key, = input_receiver.receiver_tensors.keys()110 self.assertEqual("input", receiver_key)111 def test_multi_feature_single_receiver(self):112 features = {"foo": constant_op.constant(5),113 "bar": constant_op.constant(6)}114 receiver_tensor = array_ops.placeholder(dtypes.string)115 _ = export.ServingInputReceiver(features, receiver_tensor)116 def test_multi_feature_multi_receiver(self):117 features = {"foo": constant_op.constant(5),118 "bar": constant_op.constant(6)}119 receiver_tensors = {"baz": array_ops.placeholder(dtypes.int64),120 "qux": array_ops.placeholder(dtypes.float32)}121 _ = export.ServingInputReceiver(features, receiver_tensors)122 def test_feature_wrong_type(self):123 feature = "not a tensor"124 receiver_tensor = array_ops.placeholder(dtypes.string)125 with self.assertRaises(ValueError):126 _ = export.ServingInputReceiver(feature, receiver_tensor)127 def test_feature_labeled_tensor(self):128 feature = LabeledTensorMock()129 receiver_tensor = array_ops.placeholder(dtypes.string)130 _ = export.ServingInputReceiver(feature, receiver_tensor)131 def test_receiver_wrong_type(self):132 feature = constant_op.constant(5)133 receiver_tensor = "not a tensor"134 with self.assertRaises(ValueError):135 _ = export.ServingInputReceiver(feature, receiver_tensor)136class UnsupervisedInputReceiverTest(test_util.TensorFlowTestCase):137 # Since this is basically a wrapper around ServingInputReceiver, we only138 # have a simple sanity check to ensure that it works.139 def test_unsupervised_input_receiver_constructor(self):140 """Tests that no errors are raised when input is expected."""141 features = {142 "feature0":143 constant_op.constant([0]),144 u"feature1":145 constant_op.constant([1]),146 "feature2":147 sparse_tensor.SparseTensor(148 indices=[[0, 0]], values=[1], dense_shape=[1, 1]),149 }150 receiver_tensors = {151 "example0": array_ops.placeholder(dtypes.string, name="example0"),152 u"example1": array_ops.placeholder(dtypes.string, name="example1"),153 }154 export.UnsupervisedInputReceiver(features, receiver_tensors)155class SupervisedInputReceiverTest(test_util.TensorFlowTestCase):156 def test_input_receiver_constructor(self):157 """Tests that no errors are raised when input is expected."""158 features = {159 "feature0": constant_op.constant([0]),160 u"feature1": constant_op.constant([1]),161 "feature2": sparse_tensor.SparseTensor(162 indices=[[0, 0]], values=[1], dense_shape=[1, 1]),163 }164 labels = {165 "classes": constant_op.constant([0] * 100),166 }167 receiver_tensors = {168 "example0": array_ops.placeholder(dtypes.string, name="example0"),169 u"example1": array_ops.placeholder(dtypes.string, name="example1"),170 }171 export.SupervisedInputReceiver(features, labels, receiver_tensors)172 def test_input_receiver_raw_values(self):173 """Tests that no errors are raised when input is expected."""174 features = {175 "feature0": constant_op.constant([0]),176 u"feature1": constant_op.constant([1]),177 "feature2": sparse_tensor.SparseTensor(178 indices=[[0, 0]], values=[1], dense_shape=[1, 1]),179 }180 labels = {181 "classes": constant_op.constant([0] * 100),182 }183 receiver_tensors = {184 "example0": array_ops.placeholder(dtypes.string, name="example0"),185 u"example1": array_ops.placeholder(dtypes.string, name="example1"),186 }187 rec = export.SupervisedInputReceiver(188 features["feature2"], labels, receiver_tensors)189 self.assertIsInstance(rec.features, sparse_tensor.SparseTensor)190 rec = export.SupervisedInputReceiver(191 features, labels["classes"], receiver_tensors)192 self.assertIsInstance(rec.labels, ops.Tensor)193 def test_input_receiver_features_invalid(self):194 features = constant_op.constant([0] * 100)195 labels = constant_op.constant([0])196 receiver_tensors = {197 "example0": array_ops.placeholder(dtypes.string, name="example0"),198 u"example1": array_ops.placeholder(dtypes.string, name="example1"),199 }200 with self.assertRaisesRegexp(ValueError, "features must be defined"):201 export.SupervisedInputReceiver(202 features=None,203 labels=labels,204 receiver_tensors=receiver_tensors)205 with self.assertRaisesRegexp(ValueError, "feature keys must be strings"):206 export.SupervisedInputReceiver(207 features={1: constant_op.constant([1])},208 labels=labels,209 receiver_tensors=receiver_tensors)210 with self.assertRaisesRegexp(ValueError, "label keys must be strings"):211 export.SupervisedInputReceiver(212 features=features,213 labels={1: constant_op.constant([1])},214 receiver_tensors=receiver_tensors)215 with self.assertRaisesRegexp(216 ValueError, "feature feature1 must be a Tensor or SparseTensor"):217 export.SupervisedInputReceiver(218 features={"feature1": [1]},219 labels=labels,220 receiver_tensors=receiver_tensors)221 with self.assertRaisesRegexp(222 ValueError, "feature must be a Tensor or SparseTensor"):223 export.SupervisedInputReceiver(224 features=[1],225 labels=labels,226 receiver_tensors=receiver_tensors)227 with self.assertRaisesRegexp(228 ValueError, "label must be a Tensor or SparseTensor"):229 export.SupervisedInputReceiver(230 features=features,231 labels=100,232 receiver_tensors=receiver_tensors)233 def test_input_receiver_receiver_tensors_invalid(self):234 features = {235 "feature0": constant_op.constant([0]),236 u"feature1": constant_op.constant([1]),237 "feature2": sparse_tensor.SparseTensor(238 indices=[[0, 0]], values=[1], dense_shape=[1, 1]),239 }240 labels = constant_op.constant([0])241 with self.assertRaisesRegexp(242 ValueError, "receiver_tensors must be defined"):243 export.SupervisedInputReceiver(244 features=features,245 labels=labels,246 receiver_tensors=None)247 with self.assertRaisesRegexp(248 ValueError, "receiver_tensor keys must be strings"):249 export.SupervisedInputReceiver(250 features=features,251 labels=labels,252 receiver_tensors={253 1: array_ops.placeholder(dtypes.string, name="example0")})254 with self.assertRaisesRegexp(255 ValueError, "receiver_tensor example1 must be a Tensor"):256 export.SupervisedInputReceiver(257 features=features,258 labels=labels,259 receiver_tensors={"example1": [1]})260 def test_single_feature_single_receiver(self):261 feature = constant_op.constant(5)262 label = constant_op.constant(5)263 receiver_tensor = array_ops.placeholder(dtypes.string)264 input_receiver = export.SupervisedInputReceiver(265 feature, label, receiver_tensor)266 # single receiver is automatically named267 receiver_key, = input_receiver.receiver_tensors.keys()268 self.assertEqual("input", receiver_key)269 def test_multi_feature_single_receiver(self):270 features = {"foo": constant_op.constant(5),271 "bar": constant_op.constant(6)}272 labels = {"value": constant_op.constant(5)}273 receiver_tensor = array_ops.placeholder(dtypes.string)274 _ = export.SupervisedInputReceiver(features, labels, receiver_tensor)275 def test_multi_feature_multi_receiver(self):276 features = {"foo": constant_op.constant(5),277 "bar": constant_op.constant(6)}278 labels = {"value": constant_op.constant(5)}279 receiver_tensors = {"baz": array_ops.placeholder(dtypes.int64),280 "qux": array_ops.placeholder(dtypes.float32)}281 _ = export.SupervisedInputReceiver(features, labels, receiver_tensors)282 def test_feature_labeled_tensor(self):283 feature = LabeledTensorMock()284 label = constant_op.constant(5)285 receiver_tensor = array_ops.placeholder(dtypes.string)286 _ = export.SupervisedInputReceiver(feature, label, receiver_tensor)287class ExportTest(test_util.TensorFlowTestCase):288 def test_build_parsing_serving_input_receiver_fn(self):289 feature_spec = {"int_feature": parsing_ops.VarLenFeature(dtypes.int64),...
oop-test.js
Source:oop-test.js
...180 "receiver function prototype should be augmented with supplier's prototype properties": function () {181 var receiverCalls = 0,182 supplierCalls = 0,183 instance;184 function receiver() { receiverCalls += 1; }185 function supplier() { supplierCalls += 1; }186 supplier.prototype.foo = 'foo';187 supplier.prototype.bar = function () { return 'bar'; };188 supplier.prototype.baz = function () { return 'baz'; };189 Assert.areSame(receiver, Y.augment(receiver, supplier));190 ArrayAssert.itemsAreSame(['foo', 'bar', 'baz'], Y.Object.keys(receiver.prototype));191 Assert.areSame('foo', receiver.prototype.foo);192 Assert.areNotSame(supplier.prototype.bar, receiver.prototype.bar, '`bar()` should be sequestered on `receiver.prototype`');193 Assert.areNotSame(supplier.prototype.baz, receiver.prototype.baz, '`baz()` should be sequestered on `receiver.prototype`');194 Assert.isFunction(receiver.prototype.bar);195 Assert.isFunction(receiver.prototype.baz);196 instance = new receiver();197 Assert.areSame(1, receiverCalls, "receiver's constructor should be called once");198 Assert.areSame(0, supplierCalls, "supplier's constructor should not be called yet");199 Assert.areNotSame(supplier.prototype.bar, instance.bar, '`bar()` should be sequestered on a new instance of `receiver`');200 Assert.areNotSame(supplier.prototype.baz, instance.baz, '`baz()` should be sequestered on a new instance of `receiver`');201 Assert.isFunction(instance.bar);202 Assert.isFunction(instance.baz);203 Assert.areSame('bar', instance.bar(), 'calling `bar()` on a new instance of `receiver` should work');204 Assert.areSame(1, supplierCalls, "supplier's constructor should be called on first use of a sequestered function");205 Assert.areSame(supplier.prototype.bar, instance.bar, 'after the first call, `instance.bar` and `supplier.prototype.bar` should be the same');206 Assert.areSame(supplier.prototype.baz, instance.baz, 'after the first call, `instance.baz` and `supplier.prototype.baz` should be the same');207 Assert.areSame('baz', instance.baz());208 Assert.areSame(1, supplierCalls, "supplier's constructor should not be called twice");209 },210 "receiver function prototype properties should not be overwritten when `overwrite` is not `true`": function () {211 var receiver = this.receiver,212 supplier = this.supplier;213 function quux() {}214 receiver.prototype.foo = 'moo';215 receiver.prototype.quux = quux;216 supplier.prototype.foo = 'foo';217 supplier.prototype.bar = 'bar';218 supplier.prototype.quux = function () {};219 Y.augment(receiver, supplier);220 Assert.areSame('moo', receiver.prototype.foo);221 Assert.areSame('bar', receiver.prototype.bar);222 Assert.areSame(quux, receiver.prototype.quux);223 },224 "receiver function prototype properties should be overwritten when `overwrite` is `true`": function () {225 var receiver = this.receiver,226 supplier = this.supplier;227 function quux() {}228 receiver.prototype.foo = 'moo';229 receiver.prototype.quux = quux;230 supplier.prototype.foo = 'foo';231 supplier.prototype.bar = 'bar';232 supplier.prototype.quux = function () {};233 Y.augment(receiver, supplier, true);234 Assert.areSame('foo', receiver.prototype.foo);235 Assert.areSame('bar', receiver.prototype.bar);236 Assert.areNotSame(quux, receiver.prototype.quux);237 },238 "only whitelisted properties should be copied to a receiver function": function () {239 var receiver = this.receiver,240 supplier = this.supplier;241 supplier.prototype.foo = 'a';242 supplier.prototype.bar = 'b';243 supplier.prototype.baz = 'c';244 Y.augment(receiver, supplier, false, ['foo', 'baz']);245 ArrayAssert.itemsAreSame(['foo', 'baz'], Y.Object.keys(receiver.prototype));246 },247 "supplier constructor should receive supplied args when augmenting a receiver function": function () {248 var calls = 0,249 receiver = function () {};250 function supplier(foo) {251 calls += 1;252 Assert.areSame('foo', foo);253 }254 function supplierTwo(foo, bar) {255 calls += 1;256 Assert.areSame('foo', foo);257 Assert.areSame('bar', bar);258 }259 supplier.prototype.foo = function () {};260 supplierTwo.prototype.foo = function () {};261 Y.augment(receiver, supplier, false, null, 'foo');262 new receiver().foo();263 receiver = function () {};264 Y.augment(receiver, supplierTwo, false, null, ['foo', 'bar']);265 new receiver().foo();266 Assert.areSame(2, calls);267 },268 // http://yuilibrary.com/projects/yui3/ticket/2530501269 'augmenting a Y.Node instance should not overwrite existing properties by default': function () {270 var node = Y.one('#test');271 Assert.isInstanceOf(Y.Node, node.get('parentNode'), 'parentNode attribute should be a Node instance before augment');272 Y.augment(node, Y.Attribute);273 Assert.isInstanceOf(Y.Node, node.get('parentNode'), 'parentNode attribute should be a Node instance after augment');274 }275}));276// TODO: mix tests should be moved to the tests for yui-core.js, where mix()277// lives now. Need to refactor yui-core tests first though.278suite.add(new Y.Test.Case({279 name: 'mix: default mode (object to object)',...
proxies-function.js
Source:proxies-function.js
1// Copyright 2011 the V8 project authors. All rights reserved.2// Redistribution and use in source and binary forms, with or without3// modification, are permitted provided that the following conditions are4// met:5//6// * Redistributions of source code must retain the above copyright7// notice, this list of conditions and the following disclaimer.8// * Redistributions in binary form must reproduce the above9// copyright notice, this list of conditions and the following10// disclaimer in the documentation and/or other materials provided11// with the distribution.12// * Neither the name of Google Inc. nor the names of its13// contributors may be used to endorse or promote products derived14// from this software without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27// Flags: --allow-natives-syntax28var handler = {29 get : function(r, n) { return n == "length" ? 2 : undefined }30}31// Calling (call, Function.prototype.call, Function.prototype.apply,32// Function.prototype.bind).33var global_object = this34var receiver35function TestCall(isStrict, callTrap) {36 assertEquals(42, callTrap(undefined, undefined, [5, 37]))37 var handler = {38 get: function(r, k) {39 return k == "length" ? 2 : Function.prototype[k]40 },41 apply: callTrap42 }43 var f = new Proxy(()=>{}, handler)44 var o = {f: f}45 global_object.f = f46 receiver = 33347 assertEquals(42, f(11, 31))48 receiver = 33349 assertEquals(42, o.f(10, 32))50 assertSame(o, receiver)51 receiver = 33352 assertEquals(42, o["f"](9, 33))53 assertSame(o, receiver)54 receiver = 33355 assertEquals(42, (1, o).f(8, 34))56 assertSame(o, receiver)57 receiver = 33358 assertEquals(42, (1, o)["f"](7, 35))59 assertSame(o, receiver)60 receiver = 33361 assertEquals(42, f.call(o, 32, 10))62 assertSame(o, receiver)63 receiver = 33364 assertEquals(42, f.call(undefined, 33, 9))65 receiver = 33366 assertEquals(42, f.call(null, 33, 9))67 receiver = 33368 assertEquals(44, f.call(2, 21, 23))69 assertSame(2, receiver.valueOf())70 receiver = 33371 assertEquals(42, Function.prototype.call.call(f, o, 20, 22))72 assertSame(o, receiver)73 receiver = 33374 assertEquals(43, Function.prototype.call.call(f, null, 20, 23))75 assertEquals(44, Function.prototype.call.call(f, 2, 21, 23))76 assertEquals(2, receiver.valueOf())77 receiver = 33378 assertEquals(32, f.apply(o, [16, 16]))79 assertSame(o, receiver)80 receiver = 33381 assertEquals(32, Function.prototype.apply.call(f, o, [17, 15]))82 assertSame(o, receiver)83 receiver = 33384 assertEquals(42, %Call(f, o, 11, 31));85 assertSame(o, receiver)86 receiver = 33387 assertEquals(42, %Call(f, null, 11, 31));88 receiver = 33389 assertEquals(42, %_Call(f, o, 11, 31))90 assertSame(o, receiver)91 receiver = 33392 assertEquals(42, %_Call(f, null, 11, 31))93 var ff = Function.prototype.bind.call(f, o, 12)94 assertTrue(ff.length <= 1) // TODO(rossberg): Not spec'ed yet, be lax.95 receiver = 33396 assertEquals(42, ff(30))97 assertSame(o, receiver)98 receiver = 33399 assertEquals(33, Function.prototype.call.call(ff, {}, 21))100 assertSame(o, receiver)101 receiver = 333102 assertEquals(32, Function.prototype.apply.call(ff, {}, [20]))103 assertSame(o, receiver)104 receiver = 333105 assertEquals(23, %Call(ff, {}, 11));106 assertSame(o, receiver)107 receiver = 333108 assertEquals(23, %Call(ff, {}, 11, 3));109 assertSame(o, receiver)110 receiver = 333111 assertEquals(34, %_Call(ff, {}, 22))112 assertSame(o, receiver)113 receiver = 333114 assertEquals(34, %_Call(ff, {}, 22, 3))115 assertSame(o, receiver)116 var fff = Function.prototype.bind.call(ff, o, 30)117 assertEquals(0, fff.length)118 receiver = 333119 assertEquals(42, fff())120 assertSame(o, receiver)121 receiver = 333122 assertEquals(42, Function.prototype.call.call(fff, {}))123 assertSame(o, receiver)124 receiver = 333125 assertEquals(42, Function.prototype.apply.call(fff, {}))126 assertSame(o, receiver)127 receiver = 333128 assertEquals(42, %Call(fff, {}));129 assertSame(o, receiver)130 receiver = 333131 assertEquals(42, %Call(fff, {}, 11, 3))132 assertSame(o, receiver)133 receiver = 333134 assertEquals(42, %_Call(fff, {}))135 assertSame(o, receiver)136 receiver = 333137 assertEquals(42, %_Call(fff, {}, 3, 4, 5))138 assertSame(o, receiver)139 var f = new Proxy(()=>{}, {apply: callTrap})140 receiver = 333141 assertEquals(42, f(11, 31))142 var o = {f: f}143 receiver = 333144 assertEquals(42, o.f(10, 32))145 assertSame(o, receiver)146 receiver = 333147 assertEquals(42, o["f"](9, 33))148 assertSame(o, receiver)149 receiver = 333150 assertEquals(42, (1, o).f(8, 34))151 assertSame(o, receiver)152 receiver = 333153 assertEquals(42, (1, o)["f"](7, 35))154 assertSame(o, receiver)155 receiver = 333156 assertEquals(42, Function.prototype.call.call(f, o, 20, 22))157 assertSame(o, receiver)158 receiver = 333159 assertEquals(32, Function.prototype.apply.call(f, o, [17, 15]))160 assertSame(o, receiver)161 receiver = 333162 assertEquals(23, %Call(f, o, 11, 12))163 assertSame(o, receiver)164 receiver = 333165 assertEquals(42, %_Call(f, o, 18, 24))166 assertSame(o, receiver)167}168TestCall(false, function(_, that, [x, y]) {169 receiver = that170 return x + y171})172TestCall(true, function(_, that, args) {173 "use strict"174 receiver = that175 return args[0] + args[1]176})177TestCall(false, function() {178 receiver = arguments[1]179 return arguments[2][0] + arguments[2][1]180})181TestCall(false, new Proxy(function(_, that, [x, y]) {182 receiver = that183 return x + y184 }, handler))185TestCall(true, new Proxy(function(_, that, args) {186 "use strict"187 receiver = that188 return args[0] + args[1]189 }, handler))190TestCall(false, Object.freeze(new Proxy(function(_, that, [x, y]) {191 receiver = that192 return x + y193 }, handler)))194// Using intrinsics as call traps.195function TestCallIntrinsic(type, callTrap) {196 var f = new Proxy(()=>{}, {apply: (_, that, args) => callTrap(...args)})197 var x = f()198 assertTrue(typeof x == type)199}200TestCallIntrinsic("boolean", Boolean)201TestCallIntrinsic("number", Number)202TestCallIntrinsic("string", String)203TestCallIntrinsic("object", Object)204TestCallIntrinsic("function", Function)205// Throwing from call trap.206function TestCallThrow(callTrap) {207 var f = new Proxy(()=>{}, {apply: callTrap})208 assertThrowsEquals(() => f(11), "myexn")209 assertThrowsEquals(() => ({x: f}).x(11), "myexn")210 assertThrowsEquals(() => ({x: f})["x"](11), "myexn")211 assertThrowsEquals(() => Function.prototype.call.call(f, {}, 2), "myexn")212 assertThrowsEquals(() => Function.prototype.apply.call(f, {}, [1]), "myexn")213 assertThrowsEquals(() => %Call(f, {}), "myexn")214 assertThrowsEquals(() => %Call(f, {}, 1, 2), "myexn")215 assertThrowsEquals(() => %_Call(f, {}), "myexn")216 assertThrowsEquals(() => %_Call(f, {}, 1, 2), "myexn")217 var f = Object.freeze(new Proxy(()=>{}, {apply: callTrap}))218 assertThrowsEquals(() => f(11), "myexn")219 assertThrowsEquals(() => ({x: f}).x(11), "myexn")220 assertThrowsEquals(() => ({x: f})["x"](11), "myexn")221 assertThrowsEquals(() => Function.prototype.call.call(f, {}, 2), "myexn")222 assertThrowsEquals(() => Function.prototype.apply.call(f, {}, [1]), "myexn")223 assertThrowsEquals(() => %Call(f, {}), "myexn")224 assertThrowsEquals(() => %Call(f, {}, 1, 2), "myexn")225 assertThrowsEquals(() => %_Call(f, {}), "myexn")226 assertThrowsEquals(() => %_Call(f, {}, 1, 2), "myexn")227}228TestCallThrow(function() { throw "myexn" })229TestCallThrow(new Proxy(() => {throw "myexn"}, {}))230TestCallThrow(Object.freeze(new Proxy(() => {throw "myexn"}, {})))231// Construction (new).232var prototype = {myprop: 0}233var receiver234var handlerWithPrototype = {235 get: function(r, n) {236 if (n == "length") return 2;237 assertEquals("prototype", n);238 return prototype;239 }240}241var handlerSansPrototype = {242 get: function(r, n) {243 if (n == "length") return 2;244 assertEquals("prototype", n);245 return undefined;246 }247}248function ReturnUndef(_, args, newt) {249 "use strict";250 newt.sum = args[0] + args[1];251}252function ReturnThis(x, y) {253 "use strict";254 receiver = this;255 this.sum = x + y;256 return this;257}258function ReturnNew(_, args, newt) {259 "use strict";260 return {sum: args[0] + args[1]};261}262function ReturnNewWithProto(_, args, newt) {263 "use strict";264 var result = Object.create(prototype);265 result.sum = args[0] + args[1];266 return result;267}268function TestConstruct(proto, constructTrap) {269 TestConstruct2(proto, constructTrap, handlerWithPrototype)270 TestConstruct2(proto, constructTrap, handlerSansPrototype)271}272function TestConstruct2(proto, constructTrap, handler) {273 var f = new Proxy(function(){}, {construct: constructTrap})274 var o = new f(11, 31)275 assertEquals(42, o.sum)276 assertSame(proto, Object.getPrototypeOf(o))277 var f = Object.freeze(new Proxy(function(){}, {construct: constructTrap}))278 var o = new f(11, 32)279 assertEquals(43, o.sum)280 assertSame(proto, Object.getPrototypeOf(o))281}282TestConstruct(Object.prototype, ReturnNew)283TestConstruct(prototype, ReturnNewWithProto)284TestConstruct(Object.prototype, new Proxy(ReturnNew, {}))285TestConstruct(prototype, new Proxy(ReturnNewWithProto, {}))286TestConstruct(Object.prototype, Object.freeze(new Proxy(ReturnNew, {})))287TestConstruct(prototype, Object.freeze(new Proxy(ReturnNewWithProto, {})))288// Throwing from the construct trap.289function TestConstructThrow(trap) {290 var f = new Proxy(function(){}, {construct: trap});291 assertThrowsEquals(() => new f(11), "myexn")292 Object.freeze(f)293 assertThrowsEquals(() => new f(11), "myexn")294}295TestConstructThrow(function() { throw "myexn" })296TestConstructThrow(new Proxy(function() { throw "myexn" }, {}))297TestConstructThrow(Object.freeze(new Proxy(function() { throw "myexn" }, {})))298// Using function proxies as getters and setters.299var value300var receiver301function TestAccessorCall(getterCallTrap, setterCallTrap) {302 var pgetter = new Proxy(()=>{}, {apply: getterCallTrap})303 var psetter = new Proxy(()=>{}, {apply: setterCallTrap})304 var o = {}305 var oo = Object.create(o)306 Object.defineProperty(o, "a", {get: pgetter, set: psetter})307 Object.defineProperty(o, "b", {get: pgetter})308 Object.defineProperty(o, "c", {set: psetter})309 Object.defineProperty(o, "3", {get: pgetter, set: psetter})310 Object.defineProperty(oo, "a", {value: 43})311 receiver = ""312 assertEquals(42, o.a)313 assertSame(o, receiver)314 receiver = ""315 assertEquals(42, o.b)316 assertSame(o, receiver)317 receiver = ""318 assertEquals(undefined, o.c)319 assertEquals("", receiver)320 receiver = ""321 assertEquals(42, o["a"])322 assertSame(o, receiver)323 receiver = ""324 assertEquals(42, o[3])325 assertSame(o, receiver)326 receiver = ""327 assertEquals(43, oo.a)328 assertEquals("", receiver)329 receiver = ""330 assertEquals(42, oo.b)331 assertSame(oo, receiver)332 receiver = ""333 assertEquals(undefined, oo.c)334 assertEquals("", receiver)335 receiver = ""336 assertEquals(43, oo["a"])337 assertEquals("", receiver)338 receiver = ""339 assertEquals(42, oo[3])340 assertSame(oo, receiver)341 receiver = ""342 assertEquals(50, o.a = 50)343 assertSame(o, receiver)344 assertEquals(50, value)345 receiver = ""346 assertEquals(51, o.b = 51)347 assertEquals("", receiver)348 assertEquals(50, value) // no setter349 assertThrows(function() { "use strict"; o.b = 51 }, TypeError)350 receiver = ""351 assertEquals(52, o.c = 52)352 assertSame(o, receiver)353 assertEquals(52, value)354 receiver = ""355 assertEquals(53, o["a"] = 53)356 assertSame(o, receiver)357 assertEquals(53, value)358 receiver = ""359 assertEquals(54, o[3] = 54)360 assertSame(o, receiver)361 assertEquals(54, value)362 value = 0363 receiver = ""364 assertEquals(60, oo.a = 60)365 assertEquals("", receiver)366 assertEquals(0, value) // oo has own 'a'367 assertEquals(61, oo.b = 61)368 assertSame("", receiver)369 assertEquals(0, value) // no setter370 assertThrows(function() { "use strict"; oo.b = 61 }, TypeError)371 receiver = ""372 assertEquals(62, oo.c = 62)373 assertSame(oo, receiver)374 assertEquals(62, value)375 receiver = ""376 assertEquals(63, oo["c"] = 63)377 assertSame(oo, receiver)378 assertEquals(63, value)379 receiver = ""380 assertEquals(64, oo[3] = 64)381 assertSame(oo, receiver)382 assertEquals(64, value)383}384TestAccessorCall(385 function(_, that) { receiver = that; return 42 },386 function(_, that, [x]) { receiver = that; value = x }387)388TestAccessorCall(389 function(_, that) { "use strict"; receiver = that; return 42 },390 function(_, that, args) { "use strict"; receiver = that; value = args[0] }391)392TestAccessorCall(393 new Proxy(function(_, that) { receiver = that; return 42 }, {}),394 new Proxy(function(_, that, [x]) { receiver = that; value = x }, {})395)396TestAccessorCall(397 Object.freeze(398 new Proxy(function(_, that) { receiver = that; return 42 }, {})),399 Object.freeze(400 new Proxy(function(_, that, [x]) { receiver = that; value = x }, {}))401)402// Passing a proxy function to higher-order library functions.403function TestHigherOrder(f) {404 assertEquals(6, [6, 2].map(f)[0])405 assertEquals(4, [5, 2].reduce(f, 4))406 assertTrue([1, 2].some(f))407 assertEquals("a.b.c", "a.b.c".replace(".", f))408}409TestHigherOrder(function(x) { return x })410TestHigherOrder(function(x) { "use strict"; return x })411TestHigherOrder(new Proxy(function(x) { return x }, {}))412TestHigherOrder(Object.freeze(new Proxy(function(x) { return x }, {})))413// TODO(rossberg): Ultimately, I want to have the following test function414// run through, but it currently fails on so many cases (some not even415// involving proxies), that I leave that for later...416/*417function TestCalls() {418 var handler = {419 get: function(r, k) {420 return k == "length" ? 2 : Function.prototype[k]421 }422 }423 var bind = Function.prototype.bind424 var o = {}425 var traps = [426 function(x, y) {427 return {receiver: this, result: x + y, strict: false}428 },429 function(x, y) { "use strict";430 return {receiver: this, result: x + y, strict: true}431 },432 function() {433 var x = arguments[0], y = arguments[1]434 return {receiver: this, result: x + y, strict: false}435 },436 Proxy.createFunction(handler, function(x, y) {437 return {receiver: this, result: x + y, strict: false}438 }),439 Proxy.createFunction(handler, function() {440 var x = arguments[0], y = arguments[1]441 return {receiver: this, result: x + y, strict: false}442 }),443 Proxy.createFunction(handler, function(x, y) { "use strict"444 return {receiver: this, result: x + y, strict: true}445 }),446 CreateFrozen(handler, function(x, y) {447 return {receiver: this, result: x + y, strict: false}448 }),449 CreateFrozen(handler, function(x, y) { "use strict"450 return {receiver: this, result: x + y, strict: true}451 }),452 ]453 var creates = [454 function(trap) { return trap },455 function(trap) { return CreateFrozen({}, callTrap) },456 function(trap) { return Proxy.createFunction(handler, callTrap) },457 function(trap) {458 return Proxy.createFunction(handler, CreateFrozen({}, callTrap))459 },460 function(trap) {461 return Proxy.createFunction(handler, Proxy.createFunction(handler, callTrap))462 },463 ]464 var binds = [465 function(f, o, x, y) { return f },466 function(f, o, x, y) { return bind.call(f, o) },467 function(f, o, x, y) { return bind.call(f, o, x) },468 function(f, o, x, y) { return bind.call(f, o, x, y) },469 function(f, o, x, y) { return bind.call(f, o, x, y, 5) },470 function(f, o, x, y) { return bind.call(bind.call(f, o), {}, x, y) },471 function(f, o, x, y) { return bind.call(bind.call(f, o, x), {}, y) },472 function(f, o, x, y) { return bind.call(bind.call(f, o, x, y), {}, 5) },473 ]474 var calls = [475 function(f, x, y) { return f(x, y) },476 function(f, x, y) { var g = f; return g(x, y) },477 function(f, x, y) { with ({}) return f(x, y) },478 function(f, x, y) { var g = f; with ({}) return g(x, y) },479 function(f, x, y, o) { with (o) return f(x, y) },480 function(f, x, y, o) { return f.call(o, x, y) },481 function(f, x, y, o) { return f.apply(o, [x, y]) },482 function(f, x, y, o) { return Function.prototype.call.call(f, o, x, y) },483 function(f, x, y, o) { return Function.prototype.apply.call(f, o, [x, y]) },484 function(f, x, y, o) { return %_Call(f, o, x, y) },485 function(f, x, y, o) { return %Call(f, o, x, y) },486 function(f, x, y, o) { return %Apply(f, o, [null, x, y, null], 1, 2) },487 function(f, x, y, o) { return %Apply(f, o, arguments, 2, 2) },488 function(f, x, y, o) { if (typeof o == "object") return o.f(x, y) },489 function(f, x, y, o) { if (typeof o == "object") return o["f"](x, y) },490 function(f, x, y, o) { if (typeof o == "object") return (1, o).f(x, y) },491 function(f, x, y, o) { if (typeof o == "object") return (1, o)["f"](x, y) },492 ]493 var receivers = [o, global_object, undefined, null, 2, "bla", true]494 var expectedSloppies = [o, global_object, global_object, global_object]495 for (var t = 0; t < traps.length; ++t) {496 for (var i = 0; i < creates.length; ++i) {497 for (var j = 0; j < binds.length; ++j) {498 for (var k = 0; k < calls.length; ++k) {499 for (var m = 0; m < receivers.length; ++m) {500 for (var n = 0; n < receivers.length; ++n) {501 var bound = receivers[m]502 var receiver = receivers[n]503 var func = binds[j](creates[i](traps[t]), bound, 31, 11)504 var expected = j > 0 ? bound : receiver505 var expectedSloppy = expectedSloppies[j > 0 ? m : n]506 o.f = func507 global_object.f = func508 var x = calls[k](func, 11, 31, receiver)509 if (x !== undefined) {510 assertEquals(42, x.result)511 if (calls[k].length < 4)512 assertSame(x.strict ? undefined : global_object, x.receiver)513 else if (x.strict)514 assertSame(expected, x.receiver)515 else if (expectedSloppy === undefined)516 assertSame(expected, x.receiver.valueOf())517 else518 assertSame(expectedSloppy, x.receiver)519 }520 }521 }522 }523 }524 }525 }526}527TestCalls()528*/529var realms = [Realm.create(), Realm.create()];530Realm.shared = {};531Realm.eval(realms[0], "function f(_, that) { return that; };");532Realm.eval(realms[0], "Realm.shared.f = f;");533Realm.eval(realms[0], "Realm.shared.fg = this;");534Realm.eval(realms[1], "function g(_, that) { return that; };");535Realm.eval(realms[1], "Realm.shared.g = g;");536Realm.eval(realms[1], "Realm.shared.gg = this;");537var fp = new Proxy(()=>{}, {apply: Realm.shared.f});538var gp = new Proxy(()=>{}, {apply: Realm.shared.g});539for (var i = 0; i < 10; i++) {540 assertEquals(undefined, fp());541 assertEquals(undefined, gp());542 with (this) {543 assertEquals(this, fp());544 assertEquals(this, gp());545 }546 with ({}) {547 assertEquals(undefined, fp());548 assertEquals(undefined, gp());549 }...
data_receiver_unittest.js
Source:data_receiver_unittest.js
1// Copyright 2014 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4// Tests launched by extensions/renderer/api/serial/data_receiver_unittest.cc5var test = require('test').binding;6var unittestBindings = require('test_environment_specific_bindings');7var BUFFER_SIZE = 10;8var FATAL_ERROR = 2;9// Returns a promise to a newly created DataReceiver.10function createReceiver() {11 return Promise.all([12 requireAsync('data_receiver'),13 requireAsync('device/serial/data_receiver_test_factory'),14 ]).then(function(modules) {15 var dataReceiver = modules[0];16 var factory = modules[1];17 var receiver = factory.create();18 return new dataReceiver.DataReceiver(receiver.source, receiver.client,19 BUFFER_SIZE, FATAL_ERROR);20 });21}22// Returns a promise that will resolve to |receiver| when it has received an23// error from its DataSource.24function waitForReceiveError(receiver) {25 return new Promise(function(resolve, reject) {26 var onError = receiver.onError;27 receiver.onError = function() {28 $Function.apply(onError, receiver, arguments);29 resolve(receiver);30 };31 });32}33// Returns a function that receives data from a provided DataReceiver34// |receiver|, checks that it matches the expected data and returns a promise35// that will resolve to |receiver|.36function receiveAndCheckData(expectedData) {37 return function(receiver) {38 return receiver.receive().then(function(data) {39 test.assertEq(expectedData.length, data.byteLength);40 for (var i = 0; i < expectedData.length; i++)41 test.assertEq(expectedData.charCodeAt(i), new Int8Array(data)[i]);42 return receiver;43 });44 test.assertThrows(45 receiver.receive, receiver, [], 'Receive already in progress.');46 };47}48// Returns a function that attempts to receive data from a provided DataReceiver49// |receiver|, checks that the correct error is reported and returns a promise50// that will resolve to |receiver|.51function receiveAndCheckError(expectedError) {52 return function(receiver) {53 return receiver.receive().catch(function(error) {54 test.assertEq(expectedError, error.error);55 return receiver;56 });57 test.assertThrows(58 receiver.receive, receiver, [], 'Receive already in progress.');59 };60}61// Serializes and deserializes the provided DataReceiver |receiver|, returning62// a promise that will resolve to the newly deserialized DataReceiver.63function serializeRoundTrip(receiver) {64 return Promise.all([65 receiver.serialize(),66 requireAsync('data_receiver'),67 ]).then(function(promises) {68 var serialized = promises[0];69 var dataReceiverModule = promises[1];70 return dataReceiverModule.DataReceiver.deserialize(serialized);71 });72}73// Closes and returns the provided DataReceiver |receiver|.74function closeReceiver(receiver) {75 receiver.close();76 return receiver;77}78unittestBindings.exportTests([79 function testReceive() {80 createReceiver()81 .then(receiveAndCheckData('a'))82 .then(closeReceiver)83 .then(test.succeed, test.fail);84 },85 function testReceiveError() {86 createReceiver()87 .then(receiveAndCheckError(1))88 .then(closeReceiver)89 .then(test.succeed, test.fail);90 },91 function testReceiveDataAndError() {92 createReceiver()93 .then(receiveAndCheckData('a'))94 .then(receiveAndCheckError(1))95 .then(receiveAndCheckData('b'))96 .then(closeReceiver)97 .then(test.succeed, test.fail);98 },99 function testReceiveErrorThenData() {100 createReceiver()101 .then(receiveAndCheckError(1))102 .then(receiveAndCheckData('a'))103 .then(closeReceiver)104 .then(test.succeed, test.fail);105 },106 function testReceiveBeforeAndAfterSerialization() {107 createReceiver()108 .then(receiveAndCheckData('a'))109 .then(serializeRoundTrip)110 .then(receiveAndCheckData('b'))111 .then(closeReceiver)112 .then(test.succeed, test.fail);113 },114 function testReceiveErrorSerialization() {115 createReceiver()116 .then(waitForReceiveError)117 .then(serializeRoundTrip)118 .then(receiveAndCheckError(1))119 .then(receiveAndCheckError(3))120 .then(closeReceiver)121 .then(test.succeed, test.fail);122 },123 function testReceiveDataAndErrorSerialization() {124 createReceiver()125 .then(waitForReceiveError)126 .then(receiveAndCheckData('a'))127 .then(serializeRoundTrip)128 .then(receiveAndCheckError(1))129 .then(receiveAndCheckData('b'))130 .then(receiveAndCheckError(3))131 .then(closeReceiver)132 .then(test.succeed, test.fail);133 },134 function testSerializeDuringReceive() {135 var receiver = createReceiver();136 Promise.all([137 receiver.then(receiveAndCheckError(FATAL_ERROR)),138 receiver139 .then(serializeRoundTrip)140 .then(receiveAndCheckData('a'))141 .then(closeReceiver)142 ]).then(test.succeed, test.fail);143 },144 function testSerializeAfterClose() {145 function receiveAfterClose(receiver) {146 test.assertThrows(147 receiver.receive, receiver, [], 'DataReceiver has been closed');148 }149 createReceiver()150 .then(closeReceiver)151 .then(serializeRoundTrip)152 .then(receiveAfterClose)153 .then(test.succeed, test.fail);154 },...
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!!