How to use newOperator method of json Package

Best Go-testdeep code snippet using json.newOperator

operator_test.go

Source:operator_test.go Github

copy

Full Screen

1package rule2import (3 "encoding/json"4 "fmt"5 "net"6 "testing"7 "time"8 "github.com/evilsocket/opensnitch/daemon/conman"9 "github.com/evilsocket/opensnitch/daemon/core"10 "github.com/evilsocket/opensnitch/daemon/netstat"11 "github.com/evilsocket/opensnitch/daemon/procmon"12)13var (14 defaultProcPath = "/usr/bin/opensnitchd"15 defaultProcArgs = "-rules-path /etc/opensnitchd/rules/"16 defaultDstHost = "opensnitch.io"17 defaultDstPort = uint(443)18 defaultDstIP = "185.53.178.14"19 defaultUserID = 66620 netEntry = &netstat.Entry{21 UserId: defaultUserID,22 }23 proc = &procmon.Process{24 ID: 12345,25 Path: defaultProcPath,26 Args: []string{"-rules-path", "/etc/opensnitchd/rules/"},27 }28 conn = &conman.Connection{29 Protocol: "TCP",30 SrcPort: 66666,31 SrcIP: net.ParseIP("192.168.1.111"),32 DstIP: net.ParseIP(defaultDstIP),33 DstPort: defaultDstPort,34 DstHost: defaultDstHost,35 Process: proc,36 Entry: netEntry,37 }38)39func compileListOperators(list *[]Operator, t *testing.T) {40 op := *list41 for i := 0; i < len(*list); i++ {42 if err := op[i].Compile(); err != nil {43 t.Error("NewOperator List, Compile() subitem error:", err)44 }45 }46}47func unmarshalListData(data string, t *testing.T) (op *[]Operator) {48 if err := json.Unmarshal([]byte(data), &op); err != nil {49 t.Error("Error unmarshalling list data:", err, data)50 return nil51 }52 return op53}54func restoreConnection() {55 conn.Process.Path = defaultProcPath56 conn.DstHost = defaultDstHost57 conn.DstPort = defaultDstPort58 conn.Entry.UserId = defaultUserID59}60func TestNewOperatorSimple(t *testing.T) {61 t.Log("Test NewOperator() simple")62 var list []Operator63 opSimple, err := NewOperator(Simple, false, OpTrue, "", list)64 if err != nil {65 t.Error("NewOperator simple.err should be nil: ", err)66 t.Fail()67 }68 if err = opSimple.Compile(); err != nil {69 t.Fail()70 }71 if opSimple.Match(nil) == false {72 t.Error("Test NewOperator() simple.case-insensitive doesn't match")73 t.Fail()74 }75 t.Run("Operator Simple proc.id", func(t *testing.T) {76 // proc.id not sensitive77 opSimple, err = NewOperator(Simple, false, OpProcessID, "12345", list)78 if err != nil {79 t.Error("NewOperator simple.case-insensitive.proc.id err should be nil: ", err)80 t.Fail()81 }82 if err = opSimple.Compile(); err != nil {83 t.Error("NewOperator simple.case-insensitive.proc.id Compile() err:", err)84 t.Fail()85 }86 if opSimple.Match(conn) == false {87 t.Error("Test NewOperator() simple proc.id doesn't match")88 t.Fail()89 }90 })91 opSimple, err = NewOperator(Simple, false, OpProcessPath, defaultProcPath, list)92 t.Run("Operator Simple proc.path case-insensitive", func(t *testing.T) {93 // proc path not sensitive94 if err != nil {95 t.Error("NewOperator simple proc.path err should be nil: ", err)96 t.Fail()97 }98 if err = opSimple.Compile(); err != nil {99 t.Error("NewOperator simple.case-insensitive.proc.path Compile() err:", err)100 t.Fail()101 }102 if opSimple.Match(conn) == false {103 t.Error("Test NewOperator() simple proc.path doesn't match")104 t.Fail()105 }106 })107 t.Run("Operator Simple proc.path sensitive", func(t *testing.T) {108 // proc path sensitive109 opSimple.Sensitive = true110 conn.Process.Path = "/usr/bin/OpenSnitchd"111 if opSimple.Match(conn) == true {112 t.Error("Test NewOperator() simple proc.path sensitive match")113 t.Fail()114 }115 })116 opSimple, err = NewOperator(Simple, false, OpDstHost, defaultDstHost, list)117 t.Run("Operator Simple con.dstHost case-insensitive", func(t *testing.T) {118 // proc dst host not sensitive119 if err != nil {120 t.Error("NewOperator simple proc.path err should be nil: ", err)121 t.Fail()122 }123 if err = opSimple.Compile(); err != nil {124 t.Error("NewOperator simple.case-insensitive.dstHost Compile() err:", err)125 t.Fail()126 }127 if opSimple.Match(conn) == false {128 t.Error("Test NewOperator() simple.conn.dstHost.not-sensitive doesn't match")129 t.Fail()130 }131 })132 t.Run("Operator Simple con.dstHost case-insensitive different host", func(t *testing.T) {133 conn.DstHost = "www.opensnitch.io"134 if opSimple.Match(conn) == true {135 t.Error("Test NewOperator() simple.conn.dstHost.not-sensitive doesn't MATCH")136 t.Fail()137 }138 })139 t.Run("Operator Simple con.dstHost sensitive", func(t *testing.T) {140 // proc dst host sensitive141 opSimple, err = NewOperator(Simple, true, OpDstHost, "OpEnsNitCh.io", list)142 if err != nil {143 t.Error("NewOperator simple.dstHost.sensitive err should be nil: ", err)144 t.Fail()145 }146 if err = opSimple.Compile(); err != nil {147 t.Error("NewOperator simple.dstHost.sensitive Compile() err:", err)148 t.Fail()149 }150 conn.DstHost = "OpEnsNitCh.io"151 if opSimple.Match(conn) == false {152 t.Error("Test NewOperator() simple.dstHost.sensitive doesn't match")153 t.Fail()154 }155 })156 t.Run("Operator Simple proc.args case-insensitive", func(t *testing.T) {157 // proc args case-insensitive158 opSimple, err = NewOperator(Simple, false, OpProcessCmd, defaultProcArgs, list)159 if err != nil {160 t.Error("NewOperator simple proc.args err should be nil: ", err)161 t.Fail()162 }163 if err = opSimple.Compile(); err != nil {164 t.Error("NewOperator simple proc.args Compile() err: ", err)165 t.Fail()166 }167 if opSimple.Match(conn) == false {168 t.Error("Test NewOperator() simple proc.args doesn't match")169 t.Fail()170 }171 })172 t.Run("Operator Simple con.dstIp case-insensitive", func(t *testing.T) {173 // proc dstIp case-insensitive174 opSimple, err = NewOperator(Simple, false, OpDstIP, defaultDstIP, list)175 if err != nil {176 t.Error("NewOperator simple conn.dstip.err should be nil: ", err)177 t.Fail()178 }179 if err = opSimple.Compile(); err != nil {180 t.Error("NewOperator simple con.dstIp Compile() err: ", err)181 t.Fail()182 }183 if opSimple.Match(conn) == false {184 t.Error("Test NewOperator() simple conn.dstip doesn't match")185 t.Fail()186 }187 })188 t.Run("Operator Simple UserId case-insensitive", func(t *testing.T) {189 // conn.uid case-insensitive190 opSimple, err = NewOperator(Simple, false, OpUserID, fmt.Sprint(defaultUserID), list)191 if err != nil {192 t.Error("NewOperator simple conn.userid.err should be nil: ", err)193 t.Fail()194 }195 if err = opSimple.Compile(); err != nil {196 t.Error("NewOperator simple UserId Compile() err: ", err)197 t.Fail()198 }199 if opSimple.Match(conn) == false {200 t.Error("Test NewOperator() simple conn.userid doesn't match")201 t.Fail()202 }203 })204 restoreConnection()205}206func TestNewOperatorNetwork(t *testing.T) {207 t.Log("Test NewOperator() network")208 var dummyList []Operator209 opSimple, err := NewOperator(Network, false, OpDstNetwork, "185.53.178.14/24", dummyList)210 if err != nil {211 t.Error("NewOperator network.err should be nil: ", err)212 t.Fail()213 }214 if err = opSimple.Compile(); err != nil {215 t.Fail()216 }217 if opSimple.Match(conn) == false {218 t.Error("Test NewOperator() network doesn't match")219 t.Fail()220 }221 opSimple, err = NewOperator(Network, false, OpDstNetwork, "8.8.8.8/24", dummyList)222 if err != nil {223 t.Error("NewOperator network.err should be nil: ", err)224 t.Fail()225 }226 if err = opSimple.Compile(); err != nil {227 t.Fail()228 }229 if opSimple.Match(conn) == true {230 t.Error("Test NewOperator() network doesn't match:", conn.DstIP)231 t.Fail()232 }233 restoreConnection()234}235func TestNewOperatorRegexp(t *testing.T) {236 t.Log("Test NewOperator() regexp")237 var dummyList []Operator238 opRE, err := NewOperator(Regexp, false, OpProto, "^TCP$", dummyList)239 if err != nil {240 t.Error("NewOperator regexp.err should be nil: ", err)241 t.Fail()242 }243 if err = opRE.Compile(); err != nil {244 t.Fail()245 }246 if opRE.Match(conn) == false {247 t.Error("Test NewOperator() regexp doesn't match")248 t.Fail()249 }250 restoreConnection()251}252func TestNewOperatorInvalidRegexp(t *testing.T) {253 t.Log("Test NewOperator() invalid regexp")254 var dummyList []Operator255 opRE, err := NewOperator(Regexp, false, OpProto, "^TC(P$", dummyList)256 if err != nil {257 t.Error("NewOperator regexp.err should be nil: ", err)258 t.Fail()259 }260 if err = opRE.Compile(); err == nil {261 t.Error("NewOperator() invalid regexp. It should fail: ", err)262 t.Fail()263 }264 restoreConnection()265}266func TestNewOperatorRegexpSensitive(t *testing.T) {267 t.Log("Test NewOperator() regexp sensitive")268 var dummyList []Operator269 var sensitive Sensitive270 sensitive = true271 conn.Process.Path = "/tmp/cUrL"272 opRE, err := NewOperator(Regexp, sensitive, OpProcessPath, "^/tmp/cUrL$", dummyList)273 if err != nil {274 t.Error("NewOperator regexp.case-sensitive.err should be nil: ", err)275 t.Fail()276 }277 if err = opRE.Compile(); err != nil {278 t.Fail()279 }280 if opRE.Match(conn) == false {281 t.Error("Test NewOperator() RE sensitive doesn't match:", conn.Process.Path)282 t.Fail()283 }284 t.Run("Operator regexp proc.path case-sensitive", func(t *testing.T) {285 conn.Process.Path = "/tmp/curl"286 if opRE.Match(conn) == true {287 t.Error("Test NewOperator() RE sensitive match:", conn.Process.Path)288 t.Fail()289 }290 })291 opRE, err = NewOperator(Regexp, !sensitive, OpProcessPath, "^/tmp/cUrL$", dummyList)292 if err != nil {293 t.Error("NewOperator regexp.case-insensitive.err should be nil: ", err)294 t.Fail()295 }296 if err = opRE.Compile(); err != nil {297 t.Fail()298 }299 if opRE.Match(conn) == false {300 t.Error("Test NewOperator() RE not sensitive match:", conn.Process.Path)301 t.Fail()302 }303 restoreConnection()304}305func TestNewOperatorList(t *testing.T) {306 t.Log("Test NewOperator() List")307 var list []Operator308 listData := `[{"type": "simple", "operand": "dest.ip", "data": "185.53.178.14", "sensitive": false}, {"type": "simple", "operand": "dest.port", "data": "443", "sensitive": false}]`309 // simple list310 opList, err := NewOperator(List, false, OpProto, listData, list)311 t.Run("Operator List simple case-insensitive", func(t *testing.T) {312 if err != nil {313 t.Error("NewOperator list.regexp.err should be nil: ", err)314 t.Fail()315 }316 if err = opList.Compile(); err != nil {317 t.Fail()318 }319 opList.List = *unmarshalListData(opList.Data, t)320 compileListOperators(&opList.List, t)321 if opList.Match(conn) == false {322 t.Error("Test NewOperator() list simple doesn't match")323 t.Fail()324 }325 })326 t.Run("Operator List regexp case-insensitive", func(t *testing.T) {327 // list with regexp, case-insensitive328 listData = `[{"type": "regexp", "operand": "process.path", "data": "^/usr/bin/.*", "sensitive": false},{"type": "simple", "operand": "dest.ip", "data": "185.53.178.14", "sensitive": false}, {"type": "simple", "operand": "dest.port", "data": "443", "sensitive": false}]`329 opList.List = *unmarshalListData(listData, t)330 compileListOperators(&opList.List, t)331 if err = opList.Compile(); err != nil {332 t.Fail()333 }334 if opList.Match(conn) == false {335 t.Error("Test NewOperator() list regexp doesn't match")336 t.Fail()337 }338 })339 t.Run("Operator List regexp case-sensitive", func(t *testing.T) {340 // list with regexp, case-sensitive341 // "data": "^/usr/BiN/.*" must match conn.Process.Path (sensitive)342 listData = `[{"type": "regexp", "operand": "process.path", "data": "^/usr/BiN/.*", "sensitive": false},{"type": "simple", "operand": "dest.ip", "data": "185.53.178.14", "sensitive": false}, {"type": "simple", "operand": "dest.port", "data": "443", "sensitive": false}]`343 opList.List = *unmarshalListData(listData, t)344 compileListOperators(&opList.List, t)345 conn.Process.Path = "/usr/BiN/opensnitchd"346 opList.Sensitive = true347 if err = opList.Compile(); err != nil {348 t.Fail()349 }350 if opList.Match(conn) == false {351 t.Error("Test NewOperator() list.regexp.sensitive doesn't match:", conn.Process.Path)352 t.Fail()353 }354 })355 t.Run("Operator List regexp case-insensitive 2", func(t *testing.T) {356 // "data": "^/usr/BiN/.*" must not match conn.Process.Path (insensitive)357 opList.Sensitive = false358 conn.Process.Path = "/USR/BiN/opensnitchd"359 if err = opList.Compile(); err != nil {360 t.Fail()361 }362 if opList.Match(conn) == false {363 t.Error("Test NewOperator() list.regexp.insensitive match:", conn.Process.Path)364 t.Fail()365 }366 })367 t.Run("Operator List regexp case-insensitive 3", func(t *testing.T) {368 // "data": "^/usr/BiN/.*" must match conn.Process.Path (insensitive)369 opList.Sensitive = false370 conn.Process.Path = "/USR/bin/opensnitchd"371 if err = opList.Compile(); err != nil {372 t.Fail()373 }374 if opList.Match(conn) == false {375 t.Error("Test NewOperator() list.regexp.insensitive match:", conn.Process.Path)376 t.Fail()377 }378 })379 restoreConnection()380}381func TestNewOperatorListsSimple(t *testing.T) {382 t.Log("Test NewOperator() Lists simple")383 var dummyList []Operator384 opLists, err := NewOperator(Lists, false, OpDomainsLists, "testdata/lists/domains/", dummyList)385 if err != nil {386 t.Error("NewOperator Lists, shouldn't be nil: ", err)387 t.Fail()388 }389 if err = opLists.Compile(); err != nil {390 t.Error("NewOperator Lists, Compile() error:", err)391 }392 time.Sleep(time.Second)393 t.Log("testing Lists, DstHost:", conn.DstHost)394 // The list contains 4 lines, 1 is a comment and there's a domain duplicated.395 // We should only load lines that start with 0.0.0.0 or 127.0.0.1396 if len(opLists.lists) != 2 {397 t.Error("NewOperator Lists, number of domains error:", opLists.lists, len(opLists.lists))398 }399 if opLists.Match(conn) == false {400 t.Error("Test NewOperator() lists doesn't match")401 }402 opLists.StopMonitoringLists()403 time.Sleep(time.Second)404 opLists.Lock()405 if len(opLists.lists) != 0 {406 t.Error("NewOperator Lists, number should be 0 after stop:", opLists.lists, len(opLists.lists))407 }408 opLists.Unlock()409 restoreConnection()410}411func TestNewOperatorListsIPs(t *testing.T) {412 t.Log("Test NewOperator() Lists domains_regexp")413 var subOp *Operator414 var list []Operator415 listData := `[{"type": "simple", "operand": "user.id", "data": "666", "sensitive": false}, {"type": "lists", "operand": "lists.ips", "data": "testdata/lists/ips/", "sensitive": false}]`416 opLists, err := NewOperator(List, false, OpList, listData, list)417 if err != nil {418 t.Error("NewOperator Lists domains_regexp, shouldn't be nil: ", err)419 t.Fail()420 }421 if err := opLists.Compile(); err != nil {422 t.Error("NewOperator Lists domains_regexp, Compile() error:", err)423 }424 opLists.List = *unmarshalListData(opLists.Data, t)425 for i := 0; i < len(opLists.List); i++ {426 if err := opLists.List[i].Compile(); err != nil {427 t.Error("NewOperator Lists domains_regexp, Compile() subitem error:", err)428 }429 if opLists.List[i].Type == Lists {430 subOp = &opLists.List[i]431 }432 }433 time.Sleep(time.Second)434 if opLists.Match(conn) == false {435 t.Error("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)436 }437 subOp.Lock()438 listslen := len(subOp.lists)439 subOp.Unlock()440 if listslen != 2 {441 t.Error("NewOperator Lists domains_regexp, number of domains error:", subOp.lists)442 }443 //t.Log("checking lists.domains_regexp:", tries, conn.DstHost)444 if opLists.Match(conn) == false {445 // we don't care about if it matches, we're testing race conditions446 t.Log("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)447 }448 subOp.StopMonitoringLists()449 time.Sleep(time.Second)450 subOp.Lock()451 if len(subOp.lists) != 0 {452 t.Error("NewOperator Lists number should be 0:", subOp.lists, len(subOp.lists))453 }454 subOp.Unlock()455 restoreConnection()456}457func TestNewOperatorListsNETs(t *testing.T) {458 t.Log("Test NewOperator() Lists domains_regexp")459 var subOp *Operator460 var list []Operator461 listData := `[{"type": "simple", "operand": "user.id", "data": "666", "sensitive": false}, {"type": "lists", "operand": "lists.nets", "data": "testdata/lists/nets/", "sensitive": false}]`462 opLists, err := NewOperator(List, false, OpList, listData, list)463 if err != nil {464 t.Error("NewOperator Lists domains_regexp, shouldn't be nil: ", err)465 t.Fail()466 }467 if err := opLists.Compile(); err != nil {468 t.Error("NewOperator Lists domains_regexp, Compile() error:", err)469 }470 opLists.List = *unmarshalListData(opLists.Data, t)471 for i := 0; i < len(opLists.List); i++ {472 if err := opLists.List[i].Compile(); err != nil {473 t.Error("NewOperator Lists domains_regexp, Compile() subitem error:", err)474 }475 if opLists.List[i].Type == Lists {476 subOp = &opLists.List[i]477 }478 }479 time.Sleep(time.Second)480 if opLists.Match(conn) == false {481 t.Error("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)482 }483 subOp.Lock()484 listslen := len(subOp.lists)485 subOp.Unlock()486 if listslen != 2 {487 t.Error("NewOperator Lists domains_regexp, number of domains error:", subOp.lists)488 }489 //t.Log("checking lists.domains_regexp:", tries, conn.DstHost)490 if opLists.Match(conn) == false {491 // we don't care about if it matches, we're testing race conditions492 t.Log("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)493 }494 subOp.StopMonitoringLists()495 time.Sleep(time.Second)496 subOp.Lock()497 if len(subOp.lists) != 0 {498 t.Error("NewOperator Lists number should be 0:", subOp.lists, len(subOp.lists))499 }500 subOp.Unlock()501 restoreConnection()502}503func TestNewOperatorListsComplex(t *testing.T) {504 t.Log("Test NewOperator() Lists complex")505 var subOp *Operator506 var list []Operator507 listData := `[{"type": "simple", "operand": "user.id", "data": "666", "sensitive": false}, {"type": "lists", "operand": "lists.domains", "data": "testdata/lists/domains/", "sensitive": false}]`508 opLists, err := NewOperator(List, false, OpList, listData, list)509 if err != nil {510 t.Error("NewOperator Lists complex, shouldn't be nil: ", err)511 t.Fail()512 }513 if err := opLists.Compile(); err != nil {514 t.Error("NewOperator Lists complex, Compile() error:", err)515 }516 opLists.List = *unmarshalListData(opLists.Data, t)517 for i := 0; i < len(opLists.List); i++ {518 if err := opLists.List[i].Compile(); err != nil {519 t.Error("NewOperator Lists complex, Compile() subitem error:", err)520 }521 if opLists.List[i].Type == Lists {522 subOp = &opLists.List[i]523 }524 }525 time.Sleep(time.Second)526 subOp.Lock()527 if len(subOp.lists) != 2 {528 t.Error("NewOperator Lists complex, number of domains error:", subOp.lists)529 }530 subOp.Unlock()531 if opLists.Match(conn) == false {532 t.Error("Test NewOperator() Lists complex, doesn't match")533 }534 subOp.StopMonitoringLists()535 time.Sleep(time.Second)536 subOp.Lock()537 if len(subOp.lists) != 0 {538 t.Error("NewOperator Lists number should be 0:", subOp.lists, len(subOp.lists))539 }540 subOp.Unlock()541 restoreConnection()542}543func TestNewOperatorListsDomainsRegexp(t *testing.T) {544 t.Log("Test NewOperator() Lists domains_regexp")545 var subOp *Operator546 var list []Operator547 listData := `[{"type": "simple", "operand": "user.id", "data": "666", "sensitive": false}, {"type": "lists", "operand": "lists.domains_regexp", "data": "testdata/lists/regexp/", "sensitive": false}]`548 opLists, err := NewOperator(List, false, OpList, listData, list)549 if err != nil {550 t.Error("NewOperator Lists domains_regexp, shouldn't be nil: ", err)551 t.Fail()552 }553 if err := opLists.Compile(); err != nil {554 t.Error("NewOperator Lists domains_regexp, Compile() error:", err)555 }556 opLists.List = *unmarshalListData(opLists.Data, t)557 for i := 0; i < len(opLists.List); i++ {558 if err := opLists.List[i].Compile(); err != nil {559 t.Error("NewOperator Lists domains_regexp, Compile() subitem error:", err)560 }561 if opLists.List[i].Type == Lists {562 subOp = &opLists.List[i]563 }564 }565 time.Sleep(time.Second)566 if opLists.Match(conn) == false {567 t.Error("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)568 }569 subOp.Lock()570 listslen := len(subOp.lists)571 subOp.Unlock()572 if listslen != 2 {573 t.Error("NewOperator Lists domains_regexp, number of domains error:", subOp.lists)574 }575 //t.Log("checking lists.domains_regexp:", tries, conn.DstHost)576 if opLists.Match(conn) == false {577 // we don't care about if it matches, we're testing race conditions578 t.Log("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)579 }580 subOp.StopMonitoringLists()581 time.Sleep(time.Second)582 subOp.Lock()583 if len(subOp.lists) != 0 {584 t.Error("NewOperator Lists number should be 0:", subOp.lists, len(subOp.lists))585 }586 subOp.Unlock()587 restoreConnection()588}589// Must be launched with -race to test that we don't cause leaks590// Race occured on operator.go:241 reListCmp().MathString()591// fixed here: 53419fe592func TestRaceNewOperatorListsDomainsRegexp(t *testing.T) {593 t.Log("Test NewOperator() Lists domains_regexp")594 var subOp *Operator595 var list []Operator596 listData := `[{"type": "simple", "operand": "user.id", "data": "666", "sensitive": false}, {"type": "lists", "operand": "lists.domains_regexp", "data": "testdata/lists/regexp/", "sensitive": false}]`597 opLists, err := NewOperator(List, false, OpList, listData, list)598 if err != nil {599 t.Error("NewOperator Lists domains_regexp, shouldn't be nil: ", err)600 t.Fail()601 }602 if err := opLists.Compile(); err != nil {603 t.Error("NewOperator Lists domains_regexp, Compile() error:", err)604 }605 opLists.List = *unmarshalListData(opLists.Data, t)606 for i := 0; i < len(opLists.List); i++ {607 if err := opLists.List[i].Compile(); err != nil {608 t.Error("NewOperator Lists domains_regexp, Compile() subitem error:", err)609 }610 if opLists.List[i].Type == Lists {611 subOp = &opLists.List[i]612 }613 }614 // touch domains list in background, to force a reload.615 go func() {616 touches := 1000617 for {618 if touches < 0 {619 break620 }621 core.Exec("/bin/touch", []string{"testdata/lists/regexp/domainsregexp.txt"})622 touches--623 time.Sleep(100 * time.Millisecond)624 //t.Log("touching:", touches)625 }626 }()627 time.Sleep(time.Second)628 subOp.Lock()629 listslen := len(subOp.lists)630 subOp.Unlock()631 if listslen != 2 {632 t.Error("NewOperator Lists domains_regexp, number of domains error:", subOp.lists)633 }634 tries := 10000635 for {636 if tries < 0 {637 break638 }639 //t.Log("checking lists.domains_regexp:", tries, conn.DstHost)640 if opLists.Match(conn) == false {641 // we don't care about if it matches, we're testing race conditions642 t.Log("Test NewOperator() Lists domains_regexp, doesn't match:", conn.DstHost)643 }644 tries--645 time.Sleep(10 * time.Millisecond)646 }647 subOp.StopMonitoringLists()648 time.Sleep(time.Second)649 subOp.Lock()650 if len(subOp.lists) != 0 {651 t.Error("NewOperator Lists number should be 0:", subOp.lists, len(subOp.lists))652 }653 subOp.Unlock()654 restoreConnection()655}...

Full Screen

Full Screen

slang_test.go

Source:slang_test.go Github

copy

Full Screen

1package tests2import (3 "testing"4 "github.com/Bitspark/slang/pkg/core"5 "github.com/Bitspark/slang/tests/assertions"6 "github.com/stretchr/testify/require"7)8func TestOperator_ReadOperator_1_OuterOperator(t *testing.T) {9 a := assertions.New(t)10 o, err := Test.CompileFile("test_data/voidOp.json", nil, nil)11 a.NoError(err)12 a.True(o.Main().In().Connected(o.Main().Out()))13 o.Main().Out().Bufferize()14 o.Main().In().Push("hallo")15 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out())16}17func TestOperator_ReadOperator_1_BuiltinOperator_Eval(t *testing.T) {18 a := assertions.New(t)19 o, err := Test.CompileFile("test_data/usingBuiltinOp.json", nil, nil)20 a.NoError(err)21 oPasser := o.Child("passer")22 a.NotNil(oPasser)23 a.False(o.Main().In().Connected(oPasser.Main().In()))24 a.True(oPasser.Main().Out().Connected(o.Main().Out()))25 o.Main().Out().Bufferize()26 o.Main().In().Push(map[string]interface{}{"a": "hallo"})27 o.Start()28 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out())29}30func TestOperator_ReadOperator_NestedOperator_1_Child(t *testing.T) {31 a := assertions.New(t)32 o, err := Test.CompileFile("test_data/nested_op/usingCustomOp1.json", nil, nil)33 a.NoError(err)34 o.Main().Out().Bufferize()35 o.Main().In().Push("hallo")36 o.Start()37 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out())38}39func TestOperator_ReadOperator_NestedOperator_N_Child(t *testing.T) {40 a := assertions.New(t)41 o, err := Test.CompileFile("test_data/nested_op/usingCustomOpN.json", nil, nil)42 a.NoError(err)43 o.Main().Out().Bufferize()44 o.Main().In().Push("hallo")45 o.Start()46 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out())47}48func TestOperator_ReadOperator_NestedOperator_SubChild(t *testing.T) {49 a := assertions.New(t)50 o, err := Test.CompileFile("test_data/nested_op/usingSubCustomOpDouble.json", nil, nil)51 a.NoError(err)52 o.Main().Out().Bufferize()53 o.Main().In().Push("hallo")54 o.Main().In().Push(2.0)55 o.Start()56 a.PortPushesAll([]interface{}{"hallohallo", 4.0}, o.Main().Out())57}58func TestOperator_ReadOperator_NestedOperator_Cwd(t *testing.T) {59 a := assertions.New(t)60 o, err := Test.CompileFile("test_data/cwdOp.json", nil, nil)61 a.NoError(err)62 o.Main().Out().Bufferize()63 o.Main().In().Push("hey")64 o.Main().In().Push(false)65 o.Start()66 a.PortPushesAll([]interface{}{"hey", false}, o.Main().Out())67}68func TestOperator_ReadOperator__Recursion(t *testing.T) {69 a := assertions.New(t)70 o, err := Test.CompileFile("test_data/recOp1.json", nil, nil)71 a.Error(err)72 a.Nil(o)73}74func TestOperator_ReadOperator_NestedGeneric(t *testing.T) {75 a := assertions.New(t)76 o, err := Test.CompileFile("test_data/nested_generic/main.json", nil, nil)77 require.NoError(t, err)78 o.Main().Out().Bufferize()79 o.Main().In().Push("hallo")80 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out().Map("left"))81 a.PortPushesAll([]interface{}{"hallo"}, o.Main().Out().Map("right"))82}83func TestParsePortReference__NilOperator(t *testing.T) {84 a := assertions.New(t)85 p, err := core.ParsePortReference("test.in", nil)86 a.Error(err)87 a.Nil(p)88}89func TestParsePortReference__NilConnection(t *testing.T) {90 a := assertions.New(t)91 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})92 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})93 o2.SetParent(o1)94 p, err := core.ParsePortReference("", o1)95 a.Error(err)96 a.Nil(p)97}98func TestParsePortReference__SelfIn(t *testing.T) {99 a := assertions.New(t)100 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})101 p, err := core.ParsePortReference("(", o1)102 a.NoError(err)103 a.Equal(o1.Main().In(), p, "wrong port")104}105func TestParsePortReference__SelfOut(t *testing.T) {106 a := assertions.New(t)107 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})108 p, err := core.ParsePortReference(")", o1)109 a.NoError(err)110 a.Equal(o1.Main().Out(), p, "wrong port")111}112func TestParsePortReference__SingleIn(t *testing.T) {113 a := assertions.New(t)114 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})115 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})116 o2.SetParent(o1)117 p, err := core.ParsePortReference("(o2", o1)118 a.NoError(err)119 a.Equal(o2.Main().In(), p, "wrong port")120}121func TestParsePortReference__SingleOut(t *testing.T) {122 a := assertions.New(t)123 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})124 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})125 o2.SetParent(o1)126 p, err := core.ParsePortReference("o2)", o1)127 a.NoError(err)128 a.Equal(o2.Main().Out(), p, "wrong port")129}130func TestParsePortReference__Map(t *testing.T) {131 a := assertions.New(t)132 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})133 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "map", Map: map[string]*core.TypeDef{"a": {Type: "number"}}}, Out: core.TypeDef{Type: "number"}}}})134 o2.SetParent(o1)135 p, err := core.ParsePortReference("a(o2", o1)136 a.NoError(err)137 a.Equal(o2.Main().In().Map("a"), p, "wrong port")138}139func TestParsePortReference__Map__UnknownKey(t *testing.T) {140 a := assertions.New(t)141 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})142 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "map", Map: map[string]*core.TypeDef{"a": {Type: "number"}}}, Out: core.TypeDef{Type: "number"}}}})143 o2.SetParent(o1)144 p, err := core.ParsePortReference("b(o2", o1)145 a.Error(err)146 a.Nil(p)147}148func TestParsePortReference__Map__DescendingTooDeep(t *testing.T) {149 a := assertions.New(t)150 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})151 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "map", Map: map[string]*core.TypeDef{"a": {Type: "number"}}}, Out: core.TypeDef{Type: "number"}}}})152 o2.SetParent(o1)153 p, err := core.ParsePortReference("b.c(o2", o1)154 a.Error(err)155 a.Nil(p)156}157func TestParsePortReference__NestedMap(t *testing.T) {158 a := assertions.New(t)159 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})160 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "map", Map: map[string]*core.TypeDef{"a": {Type: "map", Map: map[string]*core.TypeDef{"b": {Type: "number"}}}}}, Out: core.TypeDef{Type: "number"}}}})161 o2.SetParent(o1)162 p, err := core.ParsePortReference("a.b(o2", o1)163 a.NoError(err)164 a.Equal(o2.Main().In().Map("a").Map("b"), p, "wrong port")165}166func TestParsePortReference__Stream(t *testing.T) {167 a := assertions.New(t)168 o1, _ := core.NewOperator("o1", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})169 o2, _ := core.NewOperator("o2", nil, nil, nil, nil, core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "stream", Stream: &core.TypeDef{Type: "number"}}, Out: core.TypeDef{Type: "number"}}}})170 o2.SetParent(o1)171 p, err := core.ParsePortReference("~(o2", o1)172 a.NoError(err)173 a.Equal(o2.Main().In().Stream(), p, "wrong port")174}175func TestParsePortReference__StreamMap(t *testing.T) {176 a := assertions.New(t)177 o1, _ := core.NewOperator("o1", nil, nil, nil, nil,178 core.Blueprint{ServiceDefs: map[string]*core.ServiceDef{core.MAIN_SERVICE: {In: core.TypeDef{Type: "number"}, Out: core.TypeDef{Type: "number"}}}})179 o2, _ := core.NewOperator("o2", nil, nil, nil, nil,180 core.Blueprint{181 ServiceDefs: map[string]*core.ServiceDef{182 core.MAIN_SERVICE: {183 In: core.TypeDef{184 Type: "stream",185 Stream: &core.TypeDef{186 Type: "map",187 Map: map[string]*core.TypeDef{188 "a": {189 Type: "stream",190 Stream: &core.TypeDef{191 Type: "map",192 Map: map[string]*core.TypeDef{193 "a": {194 Type: "stream",195 Stream: &core.TypeDef{196 Type: "boolean",197 },198 },199 },200 },201 },202 },203 },204 },205 Out: core.TypeDef{Type: "number"},206 },207 },208 },209 )210 o2.SetParent(o1)211 p, err := core.ParsePortReference("~.a.~.a.~(o2", o1)212 a.NoError(err)213 a.Equal(o2.Main().In().Stream().Map("a").Stream().Map("a").Stream(), p, "wrong port")214}215func TestParsePortReference__Delegates_In(t *testing.T) {216 a := assertions.New(t)217 o, _ := core.NewOperator(218 "o1",219 nil, nil, nil, nil,220 core.Blueprint{221 ServiceDefs: map[string]*core.ServiceDef{222 core.MAIN_SERVICE: {223 In: core.TypeDef{Type: "number"},224 Out: core.TypeDef{Type: "number"},225 },226 },227 DelegateDefs: map[string]*core.DelegateDef{228 "test": {229 In: core.TypeDef{Type: "number"},230 Out: core.TypeDef{Type: "number"},231 },232 },233 })234 p, err := core.ParsePortReference("(.test", o)235 a.NoError(err)236 a.Equal(o.Delegate("test").In(), p, "wrong port")237}238func TestParsePortReference__Delegates_Out(t *testing.T) {239 a := assertions.New(t)240 o, _ := core.NewOperator(241 "o1",242 nil, nil, nil, nil,243 core.Blueprint{244 ServiceDefs: map[string]*core.ServiceDef{245 core.MAIN_SERVICE: {246 In: core.TypeDef{Type: "number"},247 Out: core.TypeDef{Type: "number"},248 },249 },250 DelegateDefs: map[string]*core.DelegateDef{251 "test": {252 In: core.TypeDef{Type: "number"},253 Out: core.TypeDef{Type: "number"},254 },255 },256 },257 )258 p, err := core.ParsePortReference(".test)", o)259 a.NoError(err)260 a.Equal(o.Delegate("test").Out(), p, "wrong port")261}262func TestParsePortReference__Delegates_SingleIn(t *testing.T) {263 a := assertions.New(t)264 o1, _ := core.NewOperator(265 "o1",266 nil, nil, nil, nil,267 core.Blueprint{268 ServiceDefs: map[string]*core.ServiceDef{269 core.MAIN_SERVICE: {270 In: core.TypeDef{Type: "number"},271 Out: core.TypeDef{Type: "number"},272 },273 },274 },275 )276 o2, _ := core.NewOperator(277 "o2",278 nil, nil, nil, nil,279 core.Blueprint{280 ServiceDefs: map[string]*core.ServiceDef{281 core.MAIN_SERVICE: {282 In: core.TypeDef{Type: "number"},283 Out: core.TypeDef{Type: "number"},284 },285 },286 DelegateDefs: map[string]*core.DelegateDef{287 "test": {288 In: core.TypeDef{Type: "number"},289 Out: core.TypeDef{Type: "number"}},290 },291 },292 )293 o2.SetParent(o1)294 p, err := core.ParsePortReference("(o2.test", o1)295 a.NoError(err)296 a.Equal(o2.Delegate("test").In(), p, "wrong port")297}298func TestParsePortReference__Delegates_SingleOut(t *testing.T) {299 a := assertions.New(t)300 o1, _ := core.NewOperator(301 "o1",302 nil, nil, nil, nil,303 core.Blueprint{304 ServiceDefs: map[string]*core.ServiceDef{305 core.MAIN_SERVICE: {306 In: core.TypeDef{Type: "number"},307 Out: core.TypeDef{Type: "number"},308 },309 },310 },311 )312 o2, _ := core.NewOperator(313 "o2",314 nil, nil, nil, nil,315 core.Blueprint{316 ServiceDefs: map[string]*core.ServiceDef{317 core.MAIN_SERVICE: {318 In: core.TypeDef{Type: "number"},319 Out: core.TypeDef{Type: "number"},320 },321 },322 DelegateDefs: map[string]*core.DelegateDef{323 "test": {324 In: core.TypeDef{Type: "number"},325 Out: core.TypeDef{Type: "number"},326 },327 },328 },329 )330 o2.SetParent(o1)331 p, err := core.ParsePortReference("o2.test)", o1)332 a.NoError(err)333 a.Equal(o2.Delegate("test").Out(), p, "wrong port")334}335func TestParsePortReference__Delegates_Map(t *testing.T) {336 a := assertions.New(t)337 o1, _ := core.NewOperator(338 "o1", nil, nil, nil, nil,339 core.Blueprint{340 ServiceDefs: map[string]*core.ServiceDef{341 core.MAIN_SERVICE: {342 In: core.TypeDef{Type: "number"},343 Out: core.TypeDef{Type: "number"},344 },345 },346 },347 )348 o2, _ := core.NewOperator(349 "o2",350 nil, nil, nil, nil,351 core.Blueprint{352 ServiceDefs: map[string]*core.ServiceDef{353 core.MAIN_SERVICE: {354 In: core.TypeDef{Type: "number"},355 Out: core.TypeDef{Type: "number"},356 },357 },358 DelegateDefs: map[string]*core.DelegateDef{359 "test": {360 In: core.TypeDef{Type: "map", Map: map[string]*core.TypeDef{"a": {Type: "number"}}},361 Out: core.TypeDef{Type: "number"}},362 },363 },364 )365 o2.SetParent(o1)366 p, err := core.ParsePortReference("a(o2.test", o1)367 a.NoError(err)368 a.Equal(o2.Delegate("test").In().Map("a"), p, "wrong port")369}370func TestParsePortReference__Services_In(t *testing.T) {371 a := assertions.New(t)372 o, _ := core.NewOperator(373 "o1",374 nil, nil, nil, nil,375 core.Blueprint{376 ServiceDefs: map[string]*core.ServiceDef{377 "srv1": {378 In: core.TypeDef{Type: "number"},379 Out: core.TypeDef{Type: "number"},380 },381 },382 },383 )384 p, err := core.ParsePortReference("(srv1@", o)385 a.NoError(err)386 a.Equal(o.Service("srv1").In(), p, "wrong port")387}388func TestParsePortReference__Services_Out(t *testing.T) {389 a := assertions.New(t)390 o, _ := core.NewOperator(391 "o1",392 nil, nil, nil, nil,393 core.Blueprint{394 ServiceDefs: map[string]*core.ServiceDef{395 "srv1": {396 In: core.TypeDef{Type: "number"},397 Out: core.TypeDef{Type: "number"},398 },399 },400 },401 )402 p, err := core.ParsePortReference("srv1@)", o)403 a.NoError(err)404 a.Equal(o.Service("srv1").Out(), p, "wrong port")405}406func TestParsePortReference__Services_SingleIn(t *testing.T) {407 a := assertions.New(t)408 o1, _ := core.NewOperator(409 "o1",410 nil, nil, nil, nil,411 core.Blueprint{412 ServiceDefs: map[string]*core.ServiceDef{413 core.MAIN_SERVICE: {414 In: core.TypeDef{Type: "number"},415 Out: core.TypeDef{Type: "number"},416 },417 },418 },419 )420 o2, _ := core.NewOperator(421 "o2",422 nil, nil, nil, nil,423 core.Blueprint{424 ServiceDefs: map[string]*core.ServiceDef{425 "srv2": {426 In: core.TypeDef{Type: "number"},427 Out: core.TypeDef{Type: "number"},428 },429 },430 },431 )432 o2.SetParent(o1)433 p, err := core.ParsePortReference("(srv2@o2", o1)434 a.NoError(err)435 a.Equal(o2.Service("srv2").In(), p, "wrong port")436}...

Full Screen

Full Screen

command.go

Source:command.go Github

copy

Full Screen

...60 logger.Info("command was successfully executed")61}62func installFlow() pipeline.Flow {63 return pipeline.Flow{64 newOperator("processed flags", processedInstallFlags, nil),65 newOperator("validate", validateToInstall, nil),66 newOperator("install tap", installTap, removeTap),67 newOperator("create config", createConfig, removeConfig),68 newOperator("record ports.txt", recordPortsToOpen, removePortsFile),69 newOperator("create service", createService, removeService),70 newOperator("create env", createEnv, removeEnv),71 newOperator("change owner", changeOwner, nil),72 newOperator("start services", startServices, nil),73 newOperator("finalize", finalize, nil),74 }75}76func removeFlow() pipeline.Flow {77 return pipeline.Flow{78 newOperator("processed flags", processedCommonFlags, nil),79 newOperator("validate", checkInstallation, nil),80 newOperator("stop service", stopService, nil),81 newOperator("remove tap", removeTap, nil),82 newOperator("remove service", removeService, nil),83 newOperator("remove config", removeConfig, nil),84 newOperator("remove env", removeEnv, nil),85 }86}87func updateFlow() pipeline.Flow {88 return pipeline.Flow{89 newOperator("processed flags", processedCommonFlags, nil),90 newOperator("validate", checkInstallation, nil),91 newOperator("update", update, nil),92 }93}94func startFlow() pipeline.Flow {95 return pipeline.Flow{96 newOperator("processed flags", processedCommonFlags, nil),97 newOperator("validate", checkInstallation, nil),98 newOperator("start service", startService, nil),99 }100}101func stopFlow() pipeline.Flow {102 return pipeline.Flow{103 newOperator("processed flags", processedCommonFlags, nil),104 newOperator("validate", checkInstallation, nil),105 newOperator("stop service", stopService, nil),106 }107}108func runFlow() pipeline.Flow {109 return pipeline.Flow{110 newOperator("processed flags", processedCommonFlags, nil),111 newOperator("validate", checkInstallation, nil),112 newOperator("run service", runService, nil),113 }114}115func runAdapterFlow() pipeline.Flow {116 return pipeline.Flow{117 newOperator("processed flags", processedCommonFlags, nil),118 newOperator("validate", checkInstallation, nil),119 newOperator("run adapter", runAdapter, nil),120 }121}...

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var jsonBlob = []byte(`[4 {"Name": "Platypus", "Order": "Monotremata"},5 {"Name": "Quoll", "Order": "Dasyuromorphia"}6 type Animal struct {7 }8 err := json.Unmarshal(jsonBlob, &animals)9 if err != nil {10 fmt.Println("error:", err)11 }12 fmt.Printf("%+v", animals)13}14[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]15Example 3: Using json.Unmarshal() method to decode JSON data16import (17func main() {18 var jsonBlob = []byte(`[19 {"Name": "Platypus", "Order": "Monotremata"},20 {"Name": "Quoll", "Order": "Dasyuromorphia"}21 type Animal struct {22 }23 err := json.Unmarshal(jsonBlob, &animals)24 if err != nil {25 fmt.Println("error:", err)26 }27}28Example 4: Using json.Unmarshal() method to decode JSON data29import (30func main() {31 var jsonBlob = []byte(`[32 {"Name": "Platypus", "Order": "Monotremata"},33 {"Name": "Quoll", "Order": "Dasyuromorphia"}34 type Animal struct {35 }36 err := json.Unmarshal(jsonBlob, &animals)37 if err != nil {38 fmt.Println("error:", err)

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var jsonBlob = []byte(`[4 {"Name": "Platypus", "Order": "Monotremata"},5 {"Name": "Quoll", "Order": "Dasyuromorphia"}6 type Animal struct {7 }8 err := json.Unmarshal(jsonBlob, &animals)9 if err != nil {10 fmt.Println("error:", err)11 }12 fmt.Printf("%+v", animals)13}14[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 p1 := Person{"John", 35, "USA"}6 p2 := Person{"Peter", 22, "UK"}7 people := []Person{p1, p2}8 fmt.Println(people)9 newOperator, _ := json.Marshal(people)10 fmt.Println(string(newOperator))11}12[{{John 35 USA} {Peter 22 UK}}]13[{"Name":"John","Age":35,"Address":"USA"},{"Name":"Peter","Age":22,"Address":"UK"}]14import (15type Person struct {16}17func main() {18 json := `[{"Name":"John","Age":35,"Address":"USA"},{"Name":"Peter","Age":22,"Address":"UK"}]`19 json.Unmarshal([]byte(json), &people)20 fmt.Println(people)21}22[{{John 35 USA} {Peter 22 UK}}]

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 j = []byte(`{ "name": "John", "age": 30, "city": "New York" }`)4 var f interface{}5 json.Unmarshal(j, &f)6 m := f.(map[string]interface{})7 fmt.Println(m["name"])8}9import (10type Person struct {11}12func main() {13 j = []byte(`{ "name": "John", "age": 30, "city": "New York"

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import (2type jsonStruct struct {3}4func main() {5 j := jsonStruct{"John", 23, 5}6 fmt.Println(j)7 b, err := json.Marshal(j)8 if err != nil {9 fmt.Println("error:", err)10 }11 fmt.Println(b)12 fmt.Println(string(b))13}14{John 23 5}15{"Name":"John","Age":23,"Height":5}

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import java.util.*;2import java.lang.*;3import java.io.*;4import com.ibm.json.java.*;5import com.ibm.json.java.JSONArray;6import com.ibm.json.java.JSONObject;7{8 public static void main (String[] args) throws java.lang.Exception9 {10 JSONObject json = JSONObject.newOperator();11 json.set("name", "John");12 System.out.println(json);13 }14}15{ "name" : "John" }16import java.util.*;17import java.lang.*;18import java.io.*;19import com.ibm.json.java.*;20import com.ibm.json.java.JSONArray;21import com.ibm.json.java.JSONObject;22{23 public static void main (String[] args) throws java.lang.Exception24 {25 JSONArray json = JSONArray.newOperator();26 json.add("John");27 json.add(25);28 System.out.println(json);29 }30}31{32}33import java.util.*;34import java.lang.*;35import java.io

Full Screen

Full Screen

newOperator

Using AI Code Generation

copy

Full Screen

1import java.util.*;2import java.io.*;3import java.lang.*;4class Main {5 public static void main(String[] args) throws IOException {6 Json json = Json.newOperator();7 json.parse("2.json");8 json.stringify();9 }10}11import java.util.*;12import java.io.*;13import java.lang.*;14class Main {15 public static void main(String[] args) throws IOException {16 Json json = Json.newOperator();17 json.parse("3.json");18 json.stringify();19 }20}21import java.util.*;22import java.io.*;23import java.lang.*;24class Main {25 public static void main(String[] args) throws IOException {26 Json json = Json.newOperator();27 json.parse("4.json");28 json.stringify();29 }30}31import java.util.*;32import java.io.*;33import java.lang.*;34class Main {35 public static void main(String[] args) throws IOException {36 Json json = Json.newOperator();37 json.parse("5.json");

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful