public void WriteSingleJavaScriptWithScope() { using (var stream = new MemoryStream()) using (var reader = new BinaryReader(stream)) { var root = new BSONDocument(); var code = "function(){var x=1;var y='abc';return z;};"; var scope = new BSONDocument(); scope.Set(new BSONInt32Element("z", 23)); var jsWithScope = new BSONCodeWithScope(code, scope); root.Set(new BSONJavaScriptWithScopeElement("codeWithScope", jsWithScope)); root.WriteAsBSON(stream); Assert.AreEqual(stream.Position, 83); // ensure document length is 83 bytes stream.Seek(0, SeekOrigin.Begin); CollectionAssert.AreEqual(reader.ReadBytes(4), BitConverter.GetBytes(83)); // content length is 83 Assert.AreEqual(reader.ReadByte(), (byte)BSONElementType.JavaScriptWithScope); // element type is JavaScriptWithScope 0x0f CollectionAssert.AreEqual(reader.ReadBytes(13), Encoding.UTF8.GetBytes("codeWithScope")); // element name is 'codeWithScope' Assert.AreEqual(reader.ReadByte(), (byte)0x00); // string name terminator 0x00 is present CollectionAssert.AreEqual(reader.ReadBytes(4), BitConverter.GetBytes(63)); // full content length is 63 CollectionAssert.AreEqual(reader.ReadBytes(4), BitConverter.GetBytes(43)); // content length is 43 CollectionAssert.AreEqual(reader.ReadBytes(42), Encoding.UTF8.GetBytes(code)); // element value is code Assert.AreEqual(reader.ReadByte(), (byte)0x00); // string value terminator 0x00 is present CollectionAssert.AreEqual(reader.ReadBytes(4), BitConverter.GetBytes(12)); // full scope content length is 12 Assert.AreEqual(reader.ReadByte(), (byte)BSONElementType.Int32); // element type is int 0x10 CollectionAssert.AreEqual(reader.ReadBytes(1), Encoding.UTF8.GetBytes("z")); // element name is 'z' Assert.AreEqual(reader.ReadByte(), (byte)0x00); // string name terminator 0x00 is present CollectionAssert.AreEqual(reader.ReadBytes(4), BitConverter.GetBytes(23)); // z variable value is 23 Assert.AreEqual(reader.ReadByte(), (byte)0x00); // last byte is terminator 0x00 Assert.AreEqual(reader.ReadByte(), (byte)0x00); // last byte is terminator 0x00 Assert.AreEqual(stream.Position, 83); // ensure whole document readed } }
/// <summary> /// { codeWithScope: "function(){var x=1;var y='abc';return z;}; <with scope: z=23>" } /// </summary> public void WriteSingleJavaScriptWithScope(Stream stream) { var root = new BSONDocument(); var code = "function(){var x=1;var y='abc';return z;};"; var scope = new BSONDocument(); scope.Set(new BSONInt32Element("z", 23)); var jsWithScope = new BSONCodeWithScope(code, scope); root.Set(new BSONJavaScriptWithScopeElement("codeWithScope", jsWithScope)); root.WriteAsBSON(stream); }