Best Gauge code snippet using template.getProperty
v8_all_test.go
Source:v8_all_test.go
1package v82import (3 "io/ioutil"4 "math/rand"5 "os"6 "runtime"7 "runtime/pprof"8 "strings"9 "sync"10 "testing"11 "time"12)13var engine *Engine14func TestMain(m *testing.M) { 15 Initialize(".")16 engine = NewEngine()17 retCode := m.Run()18 19 os.Exit(retCode)20}21func init() {22 // traceDispose = true23 rand.Seed(time.Now().UnixNano())24 go func() {25 for {26 input, err := ioutil.ReadFile("test.cmd")27 if err == nil && len(input) > 0 {28 ioutil.WriteFile("test.cmd", []byte(""), 0744)29 cmd := strings.Trim(string(input), " \n\r\t")30 var p *pprof.Profile31 switch cmd {32 case "lookup goroutine":33 p = pprof.Lookup("goroutine")34 case "lookup heap":35 p = pprof.Lookup("heap")36 case "lookup threadcreate":37 p = pprof.Lookup("threadcreate")38 default:39 println("unknow command: '" + cmd + "'")40 }41 if p != nil {42 file, err := os.Create("test.out")43 if err != nil {44 println("couldn't create test.out")45 } else {46 p.WriteTo(file, 2)47 }48 }49 }50 time.Sleep(2 * time.Second)51 }52 }()53}54func Test_InternalField(t *testing.T) {55 iCache := make([]interface{}, 0)56 ot := engine.NewObjectTemplate()57 ot.SetInternalFieldCount(1)58 context := engine.NewContext(nil)59 context.SetPrivateData(iCache)60 context.Scope(func(cs ContextScope) {61 cache := cs.GetPrivateData().([]interface{})62 str1 := "hello"63 cache = append(cache, str1)64 cs.SetPrivateData(cache)65 obj := ot.NewObject().ToObject()66 obj.SetInternalField(0, str1)67 str2 := obj.GetInternalField(0).(string)68 if str1 != str2 {69 t.Fatal("data not match")70 }71 })72 context.SetPrivateData(nil)73}74func Test_GetVersion(t *testing.T) {75 t.Log(GetVersion())76}77func Test_MessageListener(t *testing.T) {78 engine.NewContext(nil).Scope(func(cs ContextScope) {79 cs.AddMessageListener(true, func(message string, data interface{}) {80 println("golang", message)81 }, nil)82 script := engine.Compile([]byte(`var test[ = ;`), nil)83 if script != nil {84 script.Run()85 }86 SetCaptureStackTraceForUncaughtExceptions(true, 1)87 cs.AddMessageListener(false, func(message string, data interface{}) {88 println("golang2", message)89 }, nil)90 script = engine.Compile([]byte(`var test] = ;`), nil)91 if script != nil {92 script.Run()93 }94 cs.AddMessageListener(true, nil, nil)95 exception := cs.TryCatch(true, func() {96 script = engine.Compile([]byte(`var test[] = ;`), nil)97 if script != nil {98 script.Run()99 }100 })101 if exception != "" {102 println("exception:", exception)103 }104 })105}106func Test_HelloWorld(t *testing.T) {107 engine.NewContext(nil).Scope(func(cs ContextScope) {108 if cs.Eval("'Hello ' + 'World!'").ToString() != "Hello World!" {109 t.Fatal("result not match")110 }111 })112 runtime.GC()113}114func Test_TryCatch(t *testing.T) {115 engine.NewContext(nil).Scope(func(cs ContextScope) {116 cs.TryCatch(true, func() {117 engine.Compile([]byte("a[=1"), nil)118 })119 if cs.TryCatch(true, func() {120 cs.ThrowException("this is error")121 }) != "this is error" {122 t.Fatal("error message not match")123 }124 })125 runtime.GC()126}127func Test_Values(t *testing.T) {128 engine.NewContext(nil).Scope(func(cs ContextScope) {129 if !engine.Undefined().IsUndefined() {130 t.Fatal("Undefined() not match")131 }132 if !engine.Null().IsNull() {133 t.Fatal("Null() not match")134 }135 if !engine.True().IsTrue() {136 t.Fatal("True() not match")137 }138 if !engine.False().IsFalse() {139 t.Fatal("False() not match")140 }141 if engine.Undefined() != engine.Undefined() {142 t.Fatal("Undefined() != Undefined()")143 }144 if engine.Null() != engine.Null() {145 t.Fatal("Null() != Null()")146 }147 if engine.True() != engine.True() {148 t.Fatal("True() != True()")149 }150 if engine.False() != engine.False() {151 t.Fatal("False() != False()")152 }153 var (154 maxInt32 = int64(0x7FFFFFFF)155 maxUint32 = int64(0xFFFFFFFF)156 maxUint64 = uint64(0xFFFFFFFFFFFFFFFF)157 maxNumber = int64(maxUint64)158 )159 if cs.NewBoolean(true).ToBoolean() != true {160 t.Fatal(`NewBoolean(true).ToBoolean() != true`)161 }162 if cs.NewNumber(12.34).ToNumber() != 12.34 {163 t.Fatal(`NewNumber(12.34).ToNumber() != 12.34`)164 }165 if cs.NewNumber(float64(maxNumber)).ToInteger() != maxNumber {166 t.Fatal(`NewNumber(float64(maxNumber)).ToInteger() != maxNumber`)167 }168 if cs.NewInteger(maxInt32).IsInt32() == false {169 t.Fatal(`NewInteger(maxInt32).IsInt32() == false`)170 }171 if cs.NewInteger(maxUint32).IsInt32() != false {172 t.Fatal(`NewInteger(maxUint32).IsInt32() != false`)173 }174 if cs.NewInteger(maxUint32).IsUint32() == false {175 t.Fatal(`NewInteger(maxUint32).IsUint32() == false`)176 }177 if cs.NewInteger(maxNumber).ToInteger() != maxNumber {178 t.Fatal(`NewInteger(maxNumber).ToInteger() != maxNumber`)179 }180 if cs.NewString("Hello World!").ToString() != "Hello World!" {181 t.Fatal(`NewString("Hello World!").ToString() != "Hello World!"`)182 }183 if cs.NewObject().IsObject() == false {184 t.Fatal(`NewObject().IsObject() == false`)185 }186 if cs.NewArray(5).IsArray() == false {187 t.Fatal(`NewArray(5).IsArray() == false`)188 }189 if cs.NewArray(5).ToArray().Length() != 5 {190 t.Fatal(`NewArray(5).Length() != 5`)191 }192 if cs.NewRegExp("foo", RF_None).IsRegExp() == false {193 t.Fatal(`NewRegExp("foo", RF_None).IsRegExp() == false`)194 }195 if cs.NewRegExp("foo", RF_Global).ToRegExp().Pattern() != "foo" {196 t.Fatal(`NewRegExp("foo", RF_Global).ToRegExp().Pattern() != "foo"`)197 }198 if cs.NewRegExp("foo", RF_Global).ToRegExp().Flags() != RF_Global {199 t.Fatal(`NewRegExp("foo", RF_Global).ToRegExp().Flags() != RF_Global`)200 }201 })202 runtime.GC()203}204func Test_Object(t *testing.T) {205 engine.NewContext(nil).Scope(func(cs ContextScope) {206 script := engine.Compile([]byte("a={};"), nil)207 value := script.Run()208 object := value.ToObject()209 // Test get/set property210 if prop := object.GetProperty("a"); prop != nil {211 if !prop.IsUndefined() {212 t.Fatal("property 'a' value not match")213 }214 } else {215 t.Fatal("could't get property 'a'")216 }217 if !object.SetProperty("b", engine.True()) {218 t.Fatal("could't set property 'b'")219 }220 if prop := object.GetProperty("b"); prop != nil {221 if !prop.IsBoolean() || !prop.IsTrue() {222 t.Fatal("property 'b' value not match")223 }224 } else {225 t.Fatal("could't get property 'b'")226 }227 // Test get/set non-ascii property228 if !object.SetProperty("ä¸æå段", engine.False()) {229 t.Fatal("could't set non-ascii property")230 }231 if prop := object.GetProperty("ä¸æå段"); prop != nil {232 if !prop.IsBoolean() || !prop.IsFalse() {233 t.Fatal("non-ascii property value not match")234 }235 } else {236 t.Fatal("could't get non-ascii property")237 }238 // Test get/set element239 if elem := object.GetElement(0); elem != nil {240 if !elem.IsUndefined() {241 t.Fatal("element 0 value not match")242 }243 } else {244 t.Fatal("could't get element 0")245 }246 if !object.SetElement(0, engine.True()) {247 t.Fatal("could't set element 0")248 }249 if elem := object.GetElement(0); elem != nil {250 if !elem.IsTrue() {251 t.Fatal("element 0 value not match")252 }253 } else {254 t.Fatal("could't get element 0")255 }256 // Test HasProperty and DeleteProperty257 if object.HasProperty("a") {258 t.Fatal("property 'a' exists")259 }260 if !object.HasProperty("b") {261 t.Fatal("property 'b' not exists")262 }263 if !object.DeleteProperty("b") {264 t.Fatal("could't delete property 'b'")265 }266 if object.HasProperty("b") {267 t.Fatal("delete property 'b' failed")268 }269 // Test HasElement and DeleteElement270 if object.HasElement(1) {271 t.Fatal("element 1 exists")272 }273 if !object.HasElement(0) {274 t.Fatal("element 0 not exists")275 }276 if !object.DeleteElement(0) {277 t.Fatal("could't delete element 0")278 }279 if object.HasElement(0) {280 t.Fatal("delete element 0 failed")281 }282 // Test GetPropertyNames283 script = engine.Compile([]byte("a={x:10,y:20,z:30};"), nil)284 value = script.Run()285 object = value.ToObject()286 names := object.GetPropertyNames()287 if names.Length() != 3 {288 t.Fatal(`names.Length() != 3`)289 }290 if names.GetElement(0).ToString() != "x" {291 t.Fatal(`names.GetElement(0).ToString() != "x"`)292 }293 if names.GetElement(1).ToString() != "y" {294 t.Fatal(`names.GetElement(1).ToString() != "y"`)295 }296 if names.GetElement(2).ToString() != "z" {297 t.Fatal(`names.GetElement(2).ToString() != "z"`)298 }299 })300 runtime.GC()301}302func Test_Array(t *testing.T) {303 engine.NewContext(nil).Scope(func(cs ContextScope) {304 script := engine.Compile([]byte("[1,2,3]"), nil)305 value := script.Run()306 result := value.ToArray()307 if result.Length() != 3 {308 t.Fatal("array length not match")309 }310 if elem := result.GetElement(0); elem != nil {311 if !elem.IsNumber() || elem.ToNumber() != 1 {312 t.Fatal("element 0 value not match")313 }314 } else {315 t.Fatal("could't get element 0")316 }317 if elem := result.GetElement(1); elem != nil {318 if !elem.IsNumber() || elem.ToNumber() != 2 {319 t.Fatal("element 1 value not match")320 }321 } else {322 t.Fatal("could't get element 1")323 }324 if elem := result.GetElement(2); elem != nil {325 if !elem.IsNumber() || elem.ToNumber() != 3 {326 t.Fatal("element 2 value not match")327 }328 } else {329 t.Fatal("could't get element 2")330 }331 if !result.SetElement(0, engine.True()) {332 t.Fatal("could't set element")333 }334 if elem := result.GetElement(0); elem != nil {335 if !elem.IsTrue() {336 t.Fatal("element 0 value not match")337 }338 } else {339 t.Fatal("could't get element 0")340 }341 })342 runtime.GC()343}344func Test_Function(t *testing.T) {345 engine.NewContext(nil).Scope(func(cs ContextScope) {346 script := engine.Compile([]byte(`347 a = function(x,y,z){ 348 return x+y+z; 349 }350 `), nil)351 value := script.Run()352 if value.IsFunction() == false {353 t.Fatal("value not a function")354 }355 result := value.ToFunction().Call(356 cs.NewInteger(1),357 cs.NewInteger(2),358 cs.NewInteger(3),359 )360 if result.IsNumber() == false {361 t.Fatal("result not a number")362 }363 if result.ToInteger() != 6 {364 t.Fatal("result != 6")365 }366 function := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {367 if info.Get(0).ToString() != "Hello World!" {368 t.Fatal(`info.Get(0).ToString() != "Hello World!"`)369 }370 info.ReturnValue().SetBoolean(true)371 }, nil).NewFunction()372 if function == nil {373 t.Fatal("function == nil")374 }375 if function.ToFunction().Call(376 cs.NewString("Hello World!"),377 ).IsTrue() == false {378 t.Fatal("callback return not match")379 }380 })381 runtime.GC()382}383func Test_Accessor(t *testing.T) {384 engine.NewContext(nil).Scope(func(cs ContextScope) {385 template := engine.NewObjectTemplate()386 var propertyValue int32387 template.SetAccessor(388 "abc",389 func(name string, info AccessorCallbackInfo) {390 data := info.Data().(*int32)391 info.ReturnValue().SetInt32(*data)392 },393 func(name string, value *Value, info AccessorCallbackInfo) {394 data := info.Data().(*int32)395 *data = value.ToInt32()396 },397 &propertyValue,398 PA_None,399 )400 template.SetProperty("def", cs.NewInteger(8888), PA_None)401 values := []*Value{402 template.NewObject(), // New403 cs.NewObject(), // Wrap404 }405 template.WrapObject(values[1])406 for i := 0; i < 2; i++ {407 value := values[i]408 propertyValue = 1234409 object := value.ToObject()410 if object.GetProperty("abc").ToInt32() != 1234 {411 t.Fatal(`object.GetProperty("abc").ToInt32() != 1234`)412 }413 object.SetProperty("abc", cs.NewInteger(5678))414 if propertyValue != 5678 {415 t.Fatal(`propertyValue != 5678`)416 }417 if object.GetProperty("abc").ToInt32() != 5678 {418 t.Fatal(`object.GetProperty("abc").ToInt32() != 5678`)419 }420 if object.GetProperty("def").ToInt32() != 8888 {421 t.Fatal(`object.GetProperty("def").ToInt32() != 8888`)422 }423 }424 })425 runtime.GC()426}427func Test_NamedPropertyHandler(t *testing.T) {428 obj_template := engine.NewObjectTemplate()429 var (430 get_called = false431 set_called = false432 query_called = false433 delete_called = false434 enum_called = false435 )436 obj_template.SetNamedPropertyHandler(437 func(name string, info PropertyCallbackInfo) {438 //t.Logf("get %s", name)439 get_called = get_called || name == "abc"440 },441 func(name string, value *Value, info PropertyCallbackInfo) {442 //t.Logf("set %s", name)443 set_called = set_called || name == "abc"444 },445 func(name string, info PropertyCallbackInfo) {446 //t.Logf("query %s", name)447 query_called = query_called || name == "abc"448 },449 func(name string, info PropertyCallbackInfo) {450 //t.Logf("delete %s", name)451 delete_called = delete_called || name == "abc"452 },453 func(info PropertyCallbackInfo) {454 //t.Log("enumerate")455 enum_called = true456 },457 nil,458 )459 func_template := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {460 info.ReturnValue().Set(obj_template.NewObject())461 }, nil)462 global_template := engine.NewObjectTemplate()463 global_template.SetAccessor("GetData", func(name string, info AccessorCallbackInfo) {464 info.ReturnValue().Set(func_template.NewFunction())465 }, nil, nil, PA_None)466 engine.NewContext(global_template).Scope(func(cs ContextScope) {467 object := obj_template.NewObject().ToObject()468 object.GetProperty("abc")469 object.SetProperty("abc", cs.NewInteger(123))470 object.GetPropertyAttributes("abc")471 cs.Eval(`472 var data = GetData();473 delete data.abc;474 for (var p in data) {475 }476 `)477 })478 if !(get_called && set_called && query_called && delete_called && enum_called) {479 t.Fatal(get_called, set_called, query_called, delete_called, enum_called)480 }481 runtime.GC()482}483func Test_IndexedPropertyHandler(t *testing.T) {484 obj_template := engine.NewObjectTemplate()485 var (486 get_called = false487 set_called = false488 query_called = true // TODO489 delete_called = true // TODO490 enum_called = true // TODO491 )492 obj_template.SetIndexedPropertyHandler(493 func(index uint32, info PropertyCallbackInfo) {494 //t.Logf("get %d", index)495 get_called = get_called || index == 1496 },497 func(index uint32, value *Value, info PropertyCallbackInfo) {498 //t.Logf("set %d", index)499 set_called = set_called || index == 1500 },501 func(index uint32, info PropertyCallbackInfo) {502 //t.Logf("query %d", index)503 query_called = query_called || index == 1504 },505 func(index uint32, info PropertyCallbackInfo) {506 //t.Logf("delete %d", index)507 delete_called = delete_called || index == 1508 },509 func(info PropertyCallbackInfo) {510 //t.Log("enumerate")511 enum_called = true512 },513 nil,514 )515 func_template := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {516 info.ReturnValue().Set(obj_template.NewObject())517 }, nil)518 global_template := engine.NewObjectTemplate()519 global_template.SetAccessor("GetData", func(name string, info AccessorCallbackInfo) {520 info.ReturnValue().Set(func_template.NewFunction())521 }, nil, nil, PA_None)522 engine.NewContext(global_template).Scope(func(cs ContextScope) {523 object := obj_template.NewObject().ToObject()524 object.GetElement(1)525 object.SetElement(1, cs.NewInteger(123))526 cs.Eval(`527 var data = GetData();528 delete data[1];529 for (var p in data) {530 }531 `)532 })533 if !(get_called && set_called && query_called && delete_called && enum_called) {534 t.Fatal(get_called, set_called, query_called, delete_called, enum_called)535 }536 runtime.GC()537}538func Test_ObjectConstructor(t *testing.T) {539 type MyClass struct {540 name string541 }542 data := new(MyClass)543 ftConstructor := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {544 info.This().SetInternalField(0, data)545 }, nil)546 ftConstructor.SetClassName("MyClass")547 obj_template := ftConstructor.InstanceTemplate()548 var (549 get_called = false550 set_called = false551 query_called = false552 delete_called = false553 enum_called = false554 )555 obj_template.SetNamedPropertyHandler(556 func(name string, info PropertyCallbackInfo) {557 //t.Logf("get %s", name)558 get_called = get_called || name == "abc"559 data := info.This().ToObject().GetInternalField(0).(*MyClass)560 cs := info.CurrentScope()561 info.ReturnValue().Set(cs.NewString(data.name))562 },563 func(name string, value *Value, info PropertyCallbackInfo) {564 //t.Logf("set %s", name)565 set_called = set_called || name == "abc"566 data := info.This().ToObject().GetInternalField(0).(*MyClass)567 data.name = value.ToString()568 info.ReturnValue().Set(value)569 },570 func(name string, info PropertyCallbackInfo) {571 //t.Logf("query %s", name)572 query_called = query_called || name == "abc"573 },574 func(name string, info PropertyCallbackInfo) {575 //t.Logf("delete %s", name)576 delete_called = delete_called || name == "abc"577 },578 func(info PropertyCallbackInfo) {579 //t.Log("enumerate")580 enum_called = true581 },582 nil,583 )584 obj_template.SetInternalFieldCount(1)585 engine.NewContext(nil).Scope(func(cs ContextScope) {586 cs.Global().SetProperty("MyClass", ftConstructor.NewFunction())587 if !cs.Eval("(new MyClass) instanceof MyClass").IsTrue() {588 t.Fatal("(new MyClass) instanceof MyClass == false")589 }590 object := cs.Eval(`591 var data = new MyClass;592 var temp = data.abc;593 data.abc = 1;594 delete data.abc;595 for (var p in data) {596 }597 data;598 `).ToObject()599 object.GetPropertyAttributes("abc")600 data := object.GetInternalField(0).(*MyClass)601 if data.name != "1" {602 t.Fatal("InternalField failed")603 }604 if !(get_called && set_called && query_called && delete_called && enum_called) {605 t.Fatal(get_called, set_called, query_called, delete_called, enum_called)606 }607 })608 runtime.GC()609}610func Test_Context(t *testing.T) {611 return612 //TODO: fix contexes613 /*614 script1 := engine.Compile([]byte("typeof(Test_Context) == 'undefined';"), nil)615 script2 := engine.Compile([]byte("Test_Context = 1;"), nil)616 script3 := engine.Compile([]byte("Test_Context = Test_Context + 7;"), nil)617 test_func := func(cs ContextScope) {618 if script1.Run().IsFalse() {619 t.Fatal(`script1.Run(c).IsFalse()`)620 }else{621 fmt.Println("testsfsdf")622 }623 if script2.Run().ToInteger() != 1 {624 t.Fatal(`script2.Run(c).ToInteger() != 1`)625 }626 if script3.Run().ToInteger() != 8 {627 t.Fatal(`script3.Run(c).ToInteger() != 8`)628 }629 }630 engine.NewContext(nil).Scope(func(cs ContextScope) {631 engine.NewContext(nil).Scope(test_func)632 engine.NewContext(nil).Scope(test_func)633 test_func(cs)634 })635 functionTemplate := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {636 for i := 0; i < info.Length(); i++ {637 println(info.Get(i).ToString())638 }639 }, nil)640 // Test Global Template641 globalTemplate := engine.NewObjectTemplate()642 globalTemplate.SetAccessor("log", func(name string, info AccessorCallbackInfo) {643 info.ReturnValue().Set(functionTemplate.NewFunction())644 }, nil, nil, PA_None)645 engine.NewContext(globalTemplate).Scope(func(cs ContextScope) {646 cs.Eval(`log("Hello World!")`)647 })648 // Test Global Object649 engine.NewContext(nil).Scope(func(cs ContextScope) {650 global := cs.Global()651 if !global.SetProperty("println", functionTemplate.NewFunction()) {652 }653 global = cs.Global()654 if !global.HasProperty("println") {655 t.Fatal(`!global.HasProperty("println")`)656 return657 }658 cs.Eval(`println("Hello World!")`)659 })660 runtime.GC()661 */662}663func Test_UnderscoreJS(t *testing.T) {664 engine.NewContext(nil).Scope(func(cs ContextScope) {665 code, err := ioutil.ReadFile("labs/underscore.js")666 if err != nil {667 return668 }669 script := engine.Compile(code, nil)670 script.Run()671 test := []byte(`672 _.find([1, 2, 3, 4, 5, 6], function(num) { 673 return num % 2 == 0; 674 });675 `)676 testScript := engine.Compile(test, nil)677 value := testScript.Run()678 if value == nil || value.IsNumber() == false {679 t.FailNow()680 }681 result := value.ToNumber()682 if result != 2 {683 t.FailNow()684 }685 })686 runtime.GC()687}688func Test_JSON(t *testing.T) {689 engine.NewContext(nil).Scope(func(cs ContextScope) {690 json := `{"a":1,"b":2,"c":"xyz","e":true,"f":false,"g":null,"h":[4,5,6]}`691 value := cs.ParseJSON(json)692 if value == nil {693 t.Fatal(`value == nil`)694 }695 if value.IsObject() == false {696 t.Fatal(`value == false`)697 }698 if string(ToJSON(value)) != json {699 t.Fatal(`string(ToJSON(value)) != json`)700 }701 object := value.ToObject()702 if object.GetProperty("a").ToInt32() != 1 {703 t.Fatal(`object.GetProperty("a").ToInt32() != 1`)704 }705 if object.GetProperty("b").ToInt32() != 2 {706 t.Fatal(`object.GetProperty("b").ToInt32() != 2`)707 }708 if object.GetProperty("c").ToString() != "xyz" {709 t.Fatal(`object.GetProperty("c").ToString() != "xyz"`)710 }711 if object.GetProperty("e").IsTrue() == false {712 t.Fatal(`object.GetProperty("e").IsTrue() == false`)713 }714 if object.GetProperty("f").IsFalse() == false {715 t.Fatal(`object.GetProperty("f").IsFalse() == false`)716 }717 if object.GetProperty("g").IsNull() == false {718 t.Fatal(`object.GetProperty("g").IsNull() == false`)719 }720 array := object.GetProperty("h").ToArray()721 if array.Length() != 3 {722 t.Fatal(`array.Length() != 3`)723 }724 if array.GetElement(0).ToInt32() != 4 {725 t.Fatal(`array.GetElement(0).ToInt32() != 4`)726 }727 if array.GetElement(1).ToInt32() != 5 {728 t.Fatal(`array.GetElement(1).ToInt32() != 5`)729 }730 if array.GetElement(2).ToInt32() != 6 {731 t.Fatal(`array.GetElement(2).ToInt32() != 6`)732 }733 json = `"\"\/\r\n\t\b\\"`734 if string(ToJSON(cs.ParseJSON(json))) != json {735 t.Fatal(`ToJSON(cs.ParseJSON(json)) != json`)736 }737 })738 runtime.GC()739}740func rand_sched(max int) {741 for j := rand.Intn(max); j > 0; j-- {742 runtime.Gosched()743 }744}745// use one engine in different threads746//747func Test_ThreadSafe1(t *testing.T) {748 fail := false749 wg := new(sync.WaitGroup)750 for i := 0; i < 100; i++ {751 wg.Add(1)752 go func() {753 engine.NewContext(nil).Scope(func(cs ContextScope) {754 script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)755 value := script.Run()756 result := value.ToString()757 fail = fail || result != "Hello World!"758 runtime.GC()759 wg.Done()760 })761 }()762 }763 wg.Wait()764 runtime.GC()765 if fail {766 t.FailNow()767 }768}769// use one context in different threads770//771func Test_ThreadSafe2(t *testing.T) {772 fail := false773 context := engine.NewContext(nil)774 wg := new(sync.WaitGroup)775 for i := 0; i < 100; i++ {776 wg.Add(1)777 go func() {778 context.Scope(func(cs ContextScope) {779 rand_sched(200)780 script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)781 value := script.Run()782 result := value.ToString()783 fail = fail || result != "Hello World!"784 runtime.GC()785 wg.Done()786 })787 }()788 }789 wg.Wait()790 runtime.GC()791 if fail {792 t.FailNow()793 }794}795// use one script in different threads796//797func Test_ThreadSafe3(t *testing.T) {798 fail := false799 script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)800 wg := new(sync.WaitGroup)801 for i := 0; i < 100; i++ {802 wg.Add(1)803 go func() {804 engine.NewContext(nil).Scope(func(cs ContextScope) {805 rand_sched(200)806 value := script.Run()807 result := value.ToString()808 fail = fail || result != "Hello World!"809 runtime.GC()810 wg.Done()811 })812 }()813 }814 wg.Wait()815 runtime.GC()816 if fail {817 t.FailNow()818 }819}820// use one context and one script in different threads821//822func Test_ThreadSafe4(t *testing.T) {823 fail := false824 script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)825 context := engine.NewContext(nil)826 wg := new(sync.WaitGroup)827 for i := 0; i < 100; i++ {828 wg.Add(1)829 go func() {830 context.Scope(func(cs ContextScope) {831 rand_sched(200)832 value := script.Run()833 result := value.ToString()834 fail = fail || result != "Hello World!"835 runtime.GC()836 wg.Done()837 })838 }()839 }840 wg.Wait()841 runtime.GC()842 if fail {843 t.FailNow()844 }845}846// ....847//848func Test_ThreadSafe6(t *testing.T) {849 var (850 fail = false851 gonum = 100852 scriptChan = make(chan *Script, gonum)853 contextChan = make(chan *Context, gonum)854 )855 for i := 0; i < gonum; i++ {856 go func() {857 rand_sched(200)858 scriptChan <- engine.Compile([]byte("'Hello ' + 'World!'"), nil)859 }()860 }861 for i := 0; i < gonum; i++ {862 go func() {863 rand_sched(200)864 contextChan <- engine.NewContext(nil)865 }()866 }867 for i := 0; i < gonum; i++ {868 go func() {869 rand_sched(200)870 context := <-contextChan871 script := <-scriptChan872 context.Scope(func(cs ContextScope) {873 result := script.Run().ToString()874 fail = fail || result != "Hello World!"875 })876 }()877 }878 runtime.GC()879 if fail {880 t.FailNow()881 }882}883func Benchmark_NewContext(b *testing.B) {884 for i := 0; i < b.N; i++ {885 engine.NewContext(nil)886 }887 b.StopTimer()888 runtime.GC()889 b.StartTimer()890}891func Benchmark_NewInteger(b *testing.B) {892 engine.NewContext(nil).Scope(func(cs ContextScope) {893 for i := 0; i < b.N; i++ {894 cs.NewInteger(int64(i))895 }896 })897 b.StopTimer()898 runtime.GC()899 b.StartTimer()900}901func Benchmark_NewString(b *testing.B) {902 engine.NewContext(nil).Scope(func(cs ContextScope) {903 for i := 0; i < b.N; i++ {904 cs.NewString("Hello World!")905 }906 })907 b.StopTimer()908 runtime.GC()909 b.StartTimer()910}911func Benchmark_NewObject(b *testing.B) {912 engine.NewContext(nil).Scope(func(cs ContextScope) {913 for i := 0; i < b.N; i++ {914 cs.NewObject()915 }916 })917 b.StopTimer()918 runtime.GC()919 b.StartTimer()920}921func Benchmark_NewArray0(b *testing.B) {922 engine.NewContext(nil).Scope(func(cs ContextScope) {923 for i := 0; i < b.N; i++ {924 cs.NewArray(0)925 }926 })927 b.StopTimer()928 runtime.GC()929 b.StartTimer()930}931func Benchmark_NewArray5(b *testing.B) {932 engine.NewContext(nil).Scope(func(cs ContextScope) {933 for i := 0; i < b.N; i++ {934 cs.NewArray(5)935 }936 })937 b.StopTimer()938 runtime.GC()939 b.StartTimer()940}941func Benchmark_NewArray20(b *testing.B) {942 engine.NewContext(nil).Scope(func(cs ContextScope) {943 for i := 0; i < b.N; i++ {944 cs.NewArray(20)945 }946 })947 b.StopTimer()948 runtime.GC()949 b.StartTimer()950}951func Benchmark_NewArray100(b *testing.B) {952 engine.NewContext(nil).Scope(func(cs ContextScope) {953 for i := 0; i < b.N; i++ {954 cs.NewArray(100)955 }956 })957 b.StopTimer()958 runtime.GC()959 b.StartTimer()960}961func Benchmark_Compile(b *testing.B) {962 b.StopTimer()963 code, err := ioutil.ReadFile("labs/underscore.js")964 if err != nil {965 return966 }967 b.StartTimer()968 for i := 0; i < b.N; i++ {969 engine.Compile(code, nil)970 }971 b.StopTimer()972 runtime.GC()973 b.StartTimer()974}975func Benchmark_RunScript(b *testing.B) {976 b.StopTimer()977 context := engine.NewContext(nil)978 script := engine.Compile([]byte("1+1"), nil)979 b.StartTimer()980 context.Scope(func(cs ContextScope) {981 for i := 0; i < b.N; i++ {982 script.Run()983 }984 })985 b.StopTimer()986 runtime.GC()987 b.StartTimer()988}989func Benchmark_JsFunction(b *testing.B) {990 b.StopTimer()991 script := engine.Compile([]byte(`992 a = function(){ 993 return 1; 994 }995 `), nil)996 engine.NewContext(nil).Scope(func(cs ContextScope) {997 value := script.Run()998 b.StartTimer()999 for i := 0; i < b.N; i++ {1000 value.ToFunction().Call()1001 }1002 })1003 b.StopTimer()1004 runtime.GC()1005 b.StartTimer()1006}1007func Benchmark_GoFunction(b *testing.B) {1008 engine.NewContext(nil).Scope(func(cs ContextScope) {1009 b.StopTimer()1010 value := engine.NewFunctionTemplate(func(info FunctionCallbackInfo) {1011 info.ReturnValue().SetInt32(123)1012 }, nil).NewFunction()1013 function := value.ToFunction()1014 b.StartTimer()1015 for i := 0; i < b.N; i++ {1016 function.Call()1017 }1018 })1019 b.StopTimer()1020 runtime.GC()1021 b.StartTimer()1022}1023func Benchmark_Getter(b *testing.B) {1024 engine.NewContext(nil).Scope(func(cs ContextScope) {1025 b.StopTimer()1026 var propertyValue int32 = 12341027 template := engine.NewObjectTemplate()1028 template.SetAccessor(1029 "abc",1030 func(name string, info AccessorCallbackInfo) {1031 data := info.Data().(*int32)1032 info.ReturnValue().SetInt32(*data)1033 },1034 func(name string, value *Value, info AccessorCallbackInfo) {1035 data := info.Data().(*int32)1036 *data = value.ToInt32()1037 },1038 &propertyValue,1039 PA_None,1040 )1041 object := template.NewObject().ToObject()1042 b.StartTimer()1043 for i := 0; i < b.N; i++ {1044 object.GetProperty("abc")1045 }1046 })1047 b.StopTimer()1048 runtime.GC()1049 b.StartTimer()1050}1051func Benchmark_Setter(b *testing.B) {1052 engine.NewContext(nil).Scope(func(cs ContextScope) {1053 b.StopTimer()1054 var propertyValue int32 = 12341055 template := engine.NewObjectTemplate()1056 template.SetAccessor(1057 "abc",1058 func(name string, info AccessorCallbackInfo) {1059 data := info.Data().(*int32)1060 info.ReturnValue().SetInt32(*data)1061 },1062 func(name string, value *Value, info AccessorCallbackInfo) {1063 data := info.Data().(*int32)1064 *data = value.ToInt32()1065 },1066 &propertyValue,1067 PA_None,1068 )1069 object := template.NewObject().ToObject()1070 b.StartTimer()1071 for i := 0; i < b.N; i++ {1072 object.SetProperty("abc", cs.NewInteger(5678))1073 }1074 })1075 b.StopTimer()1076 runtime.GC()1077 b.StartTimer()1078}1079func Benchmark_TryCatch(b *testing.B) {1080 engine.NewContext(nil).Scope(func(cs ContextScope) {1081 for i := 0; i < b.N; i++ {1082 cs.TryCatch(false, func() {1083 cs.Eval("a[=1;")1084 })1085 }1086 })1087}...
destroy.go
Source:destroy.go
1package cli2import (3 "strings"4 "github.com/subutai-io/agent/db"5 "github.com/subutai-io/agent/lib/container"6 "github.com/subutai-io/agent/lib/gpg"7 "github.com/subutai-io/agent/lib/net"8 prxy "github.com/subutai-io/agent/lib/proxy"9 "github.com/subutai-io/agent/log"10 "github.com/subutai-io/agent/agent/util"11 "github.com/pkg/errors"12 "fmt"13 "github.com/subutai-io/agent/lib/exec"14)15// LxcDestroy simply removes every resource associated with a Subutai container or template:16// data, network, configs, etc.17//18// The destroy command always runs each step in "force" mode to provide reliable deletion results;19// even if some instance components were already removed, the destroy command will continue to perform all operations20// once again while ignoring possible underlying errors: i.e. missing configuration files.21func Cleanup(vlan string) {22 list, err := db.FindContainers("", "", vlan)23 if !log.Check(log.WarnLevel, "Reading container metadata from db", err) {24 for _, c := range list {25 err = destroy(c.Name)26 if err != nil {27 log.Error(fmt.Sprintf("Error destroying container %s: %s", c.Name, err.Error()))28 }29 }30 log.Info("Vlan " + vlan + " is destroyed")31 }32 //todo check error here33 cleanupNet(vlan)34}35func LxcDestroy(ids ...string) {36 defer sendHeartbeat()37 if len(ids) == 1 {38 name := ids[0]39 if name == "everything" {40 //destroy all containers41 list, err := db.FindContainers("", "", "")42 if !log.Check(log.ErrorLevel, "Reading container metadata from db", err) {43 for _, cont := range list {44 err = destroy(cont.Name)45 log.Check(log.ErrorLevel, "Destroying container", err)46 if cont.Vlan != "" {47 //todo check error here48 cleanupNet(cont.Vlan)49 }50 }51 }52 } else if strings.HasPrefix(name, "id:") {53 //destroy container by id54 contId := strings.ToUpper(strings.TrimPrefix(name, "id:"))55 for _, c := range container.Containers() {56 if contId == gpg.GetFingerprint(c) {57 err := destroy(c)58 log.Check(log.ErrorLevel, "Destroying container", err)59 break60 }61 }62 } else {63 //destroy container by name64 err := destroy(name)65 log.Check(log.ErrorLevel, "Destroying container", err)66 }67 } else if len(ids) > 1 {68 //destroy a set of containers/templates69 for _, name := range ids {70 err := destroy(name)71 log.Check(log.WarnLevel, "Destroying "+name, err)72 }73 }74}75//destroys template or container by name76func destroy(name string) error {77 if container.IsTemplate(name) {78 err := container.DestroyTemplate(name)79 if err != nil {80 return errors.New(fmt.Sprintf("Error destroying template: %s", err.Error()))81 }82 log.Info("Template " + name + " is destroyed")83 } else {84 c, err := db.FindContainerByName(name)85 log.Check(log.WarnLevel, "Reading container metadata from db", err)86 if c != nil {87 //destroy container that has metadata88 err = removeContainerPortMappings(name)89 if err != nil {90 return errors.New(fmt.Sprintf("Error removing port mapping: %s", err.Error()))91 }92 //todo check error here93 net.DelIface(c.Interface)94 err = container.DestroyContainer(name)95 if err != nil {96 return errors.New(fmt.Sprintf("Error destroying container: %s", err.Error()))97 }98 } else if container.IsContainer(name) {99 //destroy container with missing metadata100 err = container.DestroyContainer(name)101 if err != nil {102 return errors.New(fmt.Sprintf("Error destroying container: %s", err.Error()))103 }104 } else {105 return errors.New(name + " not found")106 }107 if name == container.Management {108 //todo check error here109 deleteManagement()110 }111 log.Info("Container " + name + " is destroyed")112 }113 return nil114}115func deleteManagement() {116 exec.Exec("ovs-vsctl", "del-port", "wan", container.Management)117 exec.Exec("ovs-vsctl", "del-port", "wan", "mng-gw")118}119func cleanupNet(id string) {120 net.DelIface("gw-" + id)121 net.RemoveP2pIface("p2p" + id)122 cleanupNetStat(id)123}124// cleanupNetStat drops data from database about network trafic for specified VLAN125func cleanupNetStat(vlan string) {126 c, err := util.InfluxDbClient()127 if err == nil {128 defer c.Close()129 }130 queryInfluxDB(c, `drop series from host_net where iface = 'p2p`+vlan+`'`)131 queryInfluxDB(c, `drop series from host_net where iface = 'gw-`+vlan+`'`)132}133func removeContainerPortMappings(name string) error {134 containerIp := container.GetIp(name)135 servers, err := db.FindProxiedServers("", "")136 if !log.Check(log.WarnLevel, "Fetching port mappings", err) {137 var removedServers []db.ProxiedServer138 for _, server := range servers {139 sock := strings.Split(server.Socket, ":")140 if sock[0] == containerIp {141 err = prxy.RemoveProxiedServer(server.ProxyTag, server.Socket)142 if err != nil {143 log.Error("Error removing server ", err)144 }145 removedServers = append(removedServers, server)146 }147 }148 //remove proxies for management container149 if name == container.Management {150 for _, server := range removedServers {151 err = prxy.RemoveProxy(server.ProxyTag)152 if err != nil {153 log.Error("Error removing proxy ", err)154 }155 }156 }157 }158 return err159}160type gradedTemplate struct {161 reference string162 grade int163}164//Prune destroys templates that don't have child containers165//It destroys unused templates by hierarchy, first destroying child templates and then parents166//this is imposed by underlying zfs file system that prohibits destruction of datasets that have child datasets167func Prune() {168 var templatesInUse []string169 //filter out all templates that have child containers170 for _, c := range container.Containers() {171 cont := c172 self := strings.ToLower(strings.TrimSpace(container.GetProperty(cont, "subutai.template")) + ":" +173 strings.TrimSpace(container.GetProperty(cont, "subutai.template.owner")) + ":" +174 strings.TrimSpace(container.GetProperty(cont, "subutai.template.version")))175 parent := strings.ToLower(strings.TrimSpace(container.GetProperty(cont, "subutai.parent")) + ":" +176 strings.TrimSpace(container.GetProperty(cont, "subutai.parent.owner")) + ":" +177 strings.TrimSpace(container.GetProperty(cont, "subutai.parent.version")))178 for self != parent || container.IsContainer(cont) {179 templatesInUse = append(templatesInUse, parent)180 cont = parent181 self = strings.ToLower(strings.TrimSpace(container.GetProperty(cont, "subutai.template")) + ":" +182 strings.TrimSpace(container.GetProperty(cont, "subutai.template.owner")) + ":" +183 strings.TrimSpace(container.GetProperty(cont, "subutai.template.version")))184 parent = strings.ToLower(strings.TrimSpace(container.GetProperty(cont, "subutai.parent")) + ":" +185 strings.TrimSpace(container.GetProperty(cont, "subutai.parent.owner")) + ":" +186 strings.TrimSpace(container.GetProperty(cont, "subutai.parent.version")))187 }188 }189 allTemplates := container.Templates()190 //figure out unused templates191 unusedTemplates := difference(allTemplates, templatesInUse)192 //grade templates by hierarchy193 var gradedTemplates = make(map[string]gradedTemplate)194 maxGrade := 0195 iterations := 0196 for len(gradedTemplates) < len(allTemplates) && iterations < len(allTemplates) {197 iterations++198 for _, t := range allTemplates {199 self := strings.ToLower(strings.TrimSpace(container.GetProperty(t, "subutai.template")) + ":" +200 strings.TrimSpace(container.GetProperty(t, "subutai.template.owner")) + ":" +201 strings.TrimSpace(container.GetProperty(t, "subutai.template.version")))202 parent := strings.ToLower(strings.TrimSpace(container.GetProperty(t, "subutai.parent")) + ":" +203 strings.TrimSpace(container.GetProperty(t, "subutai.parent.owner")) + ":" +204 strings.TrimSpace(container.GetProperty(t, "subutai.parent.version")))205 if self == parent {206 gradedTemplates[self] = gradedTemplate{reference: self, grade: 0}207 } else {208 if gradedParent, ok := gradedTemplates[parent]; ok {209 grade := gradedParent.grade + 1210 gradedTemplates[self] = gradedTemplate{reference: self, grade: grade}211 if grade > maxGrade {212 maxGrade = grade213 }214 }215 }216 }217 }218 //destroy templates starting with highest grade first219 for grade := maxGrade; grade >= 0; grade-- {220 for _, name := range unusedTemplates {221 if t, ok := gradedTemplates[name]; ok && t.grade == grade {222 log.Info("Destroying " + t.reference)223 err := container.DestroyTemplate(t.reference)224 if err != nil {225 log.Error("Error destroying template "+t.reference, err)226 }227 }228 }229 }230}231func difference(a, b []string) []string {232 mb := map[string]bool{}233 for _, x := range b {234 mb[x] = true235 }236 var ab []string237 for _, x := range a {238 if _, ok := mb[x]; !ok {239 ab = append(ab, x)240 }241 }242 return ab243}...
template.go
Source:template.go
...124 return f.Format(all)125}126func defaults() *templates {127 prop := map[string]*config.Property{128 "dotnet": getProperty("template-dotnet", "dotnet"),129 "java": getProperty("template-java", "java"),130 "java_gradle": getProperty("template-java-gradle", "java_gradle"),131 "java_maven": getProperty("template-java-maven", "java_maven"),132 "java_maven_selenium": getProperty("template-java-maven-selenium", "java_maven_selenium"),133 "js": getProperty("template-js", "js"),134 "js_simple": getProperty("template-js-simple", "js_simple"),135 "python": getProperty("template-python", "python"),136 "python_selenium": getProperty("template-python-selenium", "python_selenium"),137 "ruby": getProperty("template-ruby", "ruby"),138 "ruby_selenium": getProperty("template-ruby-selenium", "ruby_selenium"),139 "ts": getProperty("template-ts", "ts"),140 }141 return &templates{t: prop, names: getKeys(prop)}142}143func getKeys(prop map[string]*config.Property) []string {144 var keys []string145 for k := range prop {146 keys = append(keys, k)147 }148 sort.Strings(keys)149 return keys150}151func getTemplates() (*templates, error) {152 prop, err := common.GetGaugeConfigurationFor(templateProperties)153 if err != nil {154 return nil, err155 }156 t := &templates{t: make(map[string]*config.Property), names: []string{}}157 for k, v := range prop {158 if err := t.update(k, v, false); err != nil {159 return nil, err160 }161 }162 return t, nil163}164func getProperty(repoName, templateName string) *config.Property {165 f := "https://github.com/getgauge/%s/releases/latest/download/%s.zip"166 templateURL := fmt.Sprintf(f, repoName, templateName)167 desc := fmt.Sprintf("Template for gauge %s projects", templateName)168 return config.NewProperty(templateName, templateURL, desc)169}...
getProperty
Using AI Code Generation
1import (2func main() {3 tmpl, err := template.New("test").Parse("{{.Name}}'s email is {{.Email}}")4 if err != nil {5 panic(err)6 }7 err = tmpl.Execute(os.Stdout, map[string]string{
getProperty
Using AI Code Generation
1import (2func main() {3 t, err := template.New("foo").Parse("{{.Name}}")4 if err != nil {5 panic(err)6 }7 err = t.Execute(os.Stdout, map[string]string{"Name": "John"})8 if err != nil {9 panic(err)10 }11}12t.Funcs(template.FuncMap{13 "hello": func() string {14 },15})16import (17func main() {18 t, err := template.New("foo").Funcs(template.FuncMap{19 "hello": func() string {20 },21 }).Parse("{{hello}}")22 if err != nil {23 panic(err)24 }25 err = t.Execute(os.Stdout, nil)26 if err != nil {27 panic(err)28 }29}30t, err := template.ParseFiles("template1.html", "template2.html")31import (32func main() {33 t, err := template.ParseFiles("template.html")34 if err != nil {35 panic(err)36 }37 err = t.Execute(os.Stdout, nil)38 if err != nil {39 panic(err)40 }41}
getProperty
Using AI Code Generation
1import (2func main() {3 t := template.New("test")4 t = t.Funcs(template.FuncMap{"getProperty": getProperty})5 t.Parse("{{ getProperty . \"Name\" }}")6 p := Person{"Harsh", 24}7 t.Execute(os.Stdout, p)8}9func getProperty(obj interface{}, field string) interface{} {10 r := reflect.ValueOf(obj)11 f := reflect.Indirect(r).FieldByName(field)12 return f.Interface()13}14import (15type Person struct {16}17func (p Person) getProperty(field string) interface{} {18 r := reflect.ValueOf(p)19 f := reflect.Indirect(r).FieldByName(field)20 return f.Interface()21}22func main() {23 t := template.New("test")24 t = t.Funcs(template.FuncMap{"getProperty": Person.getProperty})25 t.Parse("{{ getProperty . \"Name\" }}")26 p := Person{"Harsh", 24}27 t.Execute(os.Stdout, p)28}
getProperty
Using AI Code Generation
1import (2func main() {3 t, err := template.NewTemplate("template.html")4 if err != nil {5 panic(err)6 }7 val := t.GetProperty("title")8 fmt.Println(val)9}10 <title>{{.title}}</title>11 <h1>{{.title}}</h1>12 <p>{{.content}}</p>13 <title>{{.title}}</title>14 <h1>{{.title}}</h1>15 <p>{{.content}}</p>16import (17func main() {18 t, err := template.NewTemplate("template.html")19 if err != nil {20 panic(err)21 }22 t.SetProperty("title", "My Title")23 t.SetProperty("content", "My Content")24 err = t.Execute()25 if err != nil {26 panic(err)27 }28}29import (30func main() {31 t, err := template.NewTemplate("template.html")32 if err != nil {33 panic(err)34 }35 t.SetProperty("title", "My Title")36 t.SetProperty("content", "My Content")37 err = t.Execute()38 if err != nil {39 panic(err)40 }41}
getProperty
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p := Person{Name: "John", Age: 25}6 t := reflect.TypeOf(p)7 fmt.Println(t.Name())8 fmt.Println(t.Kind())9 fmt.Println(t.NumField())10 fmt.Println(t.Field(0).Name)11 fmt.Println(t.Field(0).Type)12 fmt.Println(t.Field(1).Name)13 fmt.Println(t.Field(1).Type)14}
getProperty
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", index)4 http.ListenAndServe(":8080", nil)5}6func index(w http.ResponseWriter, r *http.Request) {7 tpl, err := template.ParseFiles("index.html")8 if err != nil {9 log.Fatalln(err)10 }11 ac := accounting.Accounting{Symbol: "$", Precision: 2}12 tpl.ExecuteTemplate(w, "index.html", ac)13}14 <h1>{{.FormatMoney}}</h1>
getProperty
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 vm.Run(`5 var template = {6 }7 value, _ := vm.Get("template")8 name, _ := value.Object().Get("name")9 fmt.Println(name)10}11templateObj.GetOwnPropertyNames()12import (13func main() {14 vm := otto.New()15 vm.Run(`16 var template = {17 }18 value, _ := vm.Get("template")19 name, _ := value.Object().GetOwnPropertyNames()20 fmt.Println(name)21}22templateObj.Set(key, value)23import (24func main() {25 vm := otto.New()26 vm.Run(`27 var template = {28 }29 value, _ := vm.Get("template")30 value.Object().Set("name", "test1")31 name, _ := value.Object().Get("name")32 fmt.Println(name)33}34templateObj.SetCall(key, value)35import (36func main() {37 vm := otto.New()38 vm.Run(`39 var template = {
getProperty
Using AI Code Generation
1func main() {2 t := template.New("template1")3 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")4 p := Person{Name: "Bob", Age: 32}5 t.Execute(os.Stdout, p)6}7func main() {8 t := template.New("template1")9 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")10 p := Person{Name: "Bob", Age: 32}11 t.ExecuteTemplate(os.Stdout, "template1", p)12}13func main() {14 t := template.New("template1")15 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")16 p := Person{Name: "Bob", Age: 32}17 t.ExecuteTemplate(os.Stdout, "template1", p)18}19func main() {20 t := template.New("template1")21 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")22 p := Person{Name: "Bob", Age: 32}23 t.ExecuteTemplate(os.Stdout, "template1", p)24}25func main() {26 t := template.New("template1")27 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")28 p := Person{Name: "Bob", Age: 32}29 t.ExecuteTemplate(os.Stdout, "template1", p)30}31func main() {32 t := template.New("template1")33 t, _ = t.Parse("{{.Name}}'s age is {{.Age}}")34 p := Person{Name: "Bob", Age: 32}35 t.ExecuteTemplate(os.Stdout, "template1", p)36}37func main() {38 t := template.New("template1")
getProperty
Using AI Code Generation
1import (2func main() {3 tmpl := template.Must(template.New("test").Parse("{{.Name}}"))4 data := map[string]string{"Name": "Akash"}5 tmpl.Execute(os.Stdout, data)6}7import (8func main() {9 tmpl := template.Must(template.New("test").Parse("{{.Name}}"))10 type Data struct {11 }12 data := Data{"Akash"}13 tmpl.Execute(os.Stdout, data)14}15import (16func main() {17 tmpl := template.Must(template.New("test").Parse("{{.Name}}"))18 type Data struct {19 }20 data := Data{Name: "Akash"}21 tmpl.Execute(os.Stdout, data)22}23import (24func main() {25 tmpl := template.Must(template.New("test").Parse("{{.Name}}"))26 type Data struct {27 }28 data := Data{Name: "Akash"}29 tmpl.Execute(os.Stdout, data)30}31import (32func main() {33 tmpl := template.Must(template.New("test").Parse("{{.Name}}"))34 type Data struct {35 }36 data := Data{Name: "Akash"}
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!!