Best Gauge code snippet using filter.applyFilters
hooks_test.go
Source:hooks_test.go
1package hooks_test2import (3 "fmt"4 "reflect"5 "testing"6 hooks "github.com/Golang-Hooks/Golang-Hooks"7)8var h hooks.Core9var actionValue string10type Arg1 struct {11 a int12}13type Arg2 struct {14 b int15}16func filterA(i ...interface{}) interface{} {17 arg1 := i[0]18 if p, ok := arg1.(string); ok {19 return p + "a"20 }21 return nil22}23func filterB(i ...interface{}) interface{} {24 arg1 := i[0]25 if p, ok := arg1.(string); ok {26 return p + "b"27 }28 return nil29}30func filterC(i ...interface{}) interface{} {31 arg1 := i[0]32 if p, ok := arg1.(string); ok {33 return p + "c"34 }35 return nil36}37func filterCRemovesSelf(i ...interface{}) interface{} {38 h.RemoveFilter("test.filter", "my_callback_filter_c_removes_self")39 arg1 := i[0]40 if p, ok := arg1.(string); ok {41 return p + "b"42 }43 return nil44}45func filterRemovesB(i ...interface{}) interface{} {46 h.RemoveFilter("test.filter", "my_callback_filter_b")47 arg1 := i[0]48 if p, ok := arg1.(string); ok {49 return p50 }51 return nil52}53func filterRemovesC(i ...interface{}) interface{} {54 h.RemoveFilter("test.filter", "my_callback_filter_c")55 arg1 := i[0]56 if p, ok := arg1.(string); ok {57 return p58 }59 return nil60}61func actionA(i ...interface{}) interface{} {62 actionValue += "a"63 return nil64}65func actionB(i ...interface{}) interface{} {66 actionValue += "b"67 return nil68}69func actionC(i ...interface{}) interface{} {70 actionValue += "c"71 return nil72}73// Almost the same as setupSuite, but this one is for single test instead of collection of tests74func setupTest(tb testing.TB) func(tb testing.TB) {75 // Setup76 h = hooks.CreateHooks()77 actionValue = ""78 return func(tb testing.TB) {79 // Teardown80 actionValue = ""81 h = hooks.CreateHooks()82 }83}84// Run a filter with no callbacks85func TestFilterNoCallbacks(t *testing.T) {86 teardownTest := setupTest(t)87 defer teardownTest(t)88 expected := 4289 v := h.ApplyFilters("test.filter", 42)90 if v != expected {91 t.Errorf("Expected %d to be equal to %d", v, expected)92 }93}94// Add and remove a filter95func TestAddRemoveFilter(t *testing.T) {96 teardownTest := setupTest(t)97 defer teardownTest(t)98 expected := "42"99 h.AddFilter("test.filter", "my_callback", filterA, 10)100 removeAllFilters := h.RemoveAllFilters("test.filter", "my_callback")101 removeAllFiltersExpected := 1102 if removeAllFilters != removeAllFiltersExpected {103 t.Errorf("Expected %d to be equal to %d", removeAllFilters, removeAllFiltersExpected)104 }105 v := h.ApplyFilters("test.filter", "test")106 expected = "test"107 if v != expected {108 t.Errorf("Expected %s to be equal to %s", v, expected)109 }110 v2 := h.RemoveAllFilters("test.filter", "my_callback")111 expected2 := 0112 if v2 != expected2 {113 t.Errorf("Expected %d to be equal to %d", v2, expected2)114 }115}116// Add a filter and run it117func TestAddFilterRun(t *testing.T) {118 teardownTest := setupTest(t)119 defer teardownTest(t)120 expected := "testa"121 h.AddFilter("test.filter", "my_callback", filterA, 10)122 v := h.ApplyFilters("test.filter", "test")123 if v != expected {124 t.Errorf("Expected %s to be equal to %s", v, expected)125 }126}127// Add 2 filters in a row and run them128func TestAdd2FiltersRun(t *testing.T) {129 teardownTest := setupTest(t)130 defer teardownTest(t)131 expected := "testab"132 h.AddFilter("test.filter", "my_callback", filterA, 10)133 h.AddFilter("test.filter", "my_callback", filterB, 10)134 v := h.ApplyFilters("test.filter", "test")135 if v != expected {136 t.Errorf("Expected %s to be equal to %s", v, expected)137 }138}139// Remove a non-existent filter140func TestRemoveNonExistentFilter(t *testing.T) {141 teardownTest := setupTest(t)142 defer teardownTest(t)143 expected := 0144 v := h.RemoveFilter("test.filter", "my_callback")145 if v != expected {146 t.Errorf("Expected %d to be equal to %d", v, expected)147 }148 v = h.RemoveAllFilters("test.filter", "my_callback")149 if v != expected {150 t.Errorf("Expected %d to be equal to %d", v, expected)151 }152}153// Add 3 filters with different priorities and run them154func TestAdd3FiltersRun(t *testing.T) {155 teardownTest := setupTest(t)156 defer teardownTest(t)157 expected := "testbca"158 h.AddFilter("test.filter", "my_callback", filterA, 10)159 h.AddFilter("test.filter", "my_callback", filterB, 2)160 h.AddFilter("test.filter", "my_callback", filterC, 8)161 v := h.ApplyFilters("test.filter", "test")162 if v != expected {163 t.Errorf("Expected %s to be equal to %s", v, expected)164 }165}166// Filters with the same and different priorities167func TestAdd3FiltersSamePriorityRun(t *testing.T) {168 teardownTest := setupTest(t)169 defer teardownTest(t)170 callbacks := make(map[string]func(...interface{}) interface{})171 for p := 1; p < 5; p++ {172 pv := p173 s := []string{"a", "b", "c", "d"}174 for _, v := range s {175 sv := v176 callbacks[fmt.Sprintf("fn_%d%s", pv, sv)] = func(i ...interface{}) interface{} {177 arg1 := i[0]178 if par, ok := arg1.([]string); ok {179 return append(par, fmt.Sprintf("%d%s", pv, sv))180 }181 return nil182 }183 }184 }185 h.AddFilter("test_order", "my_callback_fn_3a", callbacks["fn_3a"], 3)186 h.AddFilter("test_order", "my_callback_fn_3b", callbacks["fn_3b"], 3)187 h.AddFilter("test_order", "my_callback_fn_3c", callbacks["fn_3c"], 3)188 h.AddFilter("test_order", "my_callback_fn_2a", callbacks["fn_2a"], 2)189 h.AddFilter("test_order", "my_callback_fn_2b", callbacks["fn_2b"], 2)190 h.AddFilter("test_order", "my_callback_fn_2c", callbacks["fn_2c"], 2)191 v := h.ApplyFilters("test_order", []string{})192 expected := []string{"2a", "2b", "2c", "3a", "3b", "3c"}193 if !reflect.DeepEqual(v, expected) {194 t.Errorf("Expected %s to be equal to %s", v, expected)195 }196 h.RemoveFilter("test_order", "my_callback_fn_2b")197 h.RemoveFilter("test_order", "my_callback_fn_3a")198 v = h.ApplyFilters("test_order", []string{})199 expected = []string{"2a", "2c", "3b", "3c"}200 if !reflect.DeepEqual(v, expected) {201 t.Errorf("Expected %s to be equal to %s", v, expected)202 }203 h.AddFilter("test_order", "my_callback_fn_4a", callbacks["fn_4a"], 4)204 h.AddFilter("test_order", "my_callback_fn_4b", callbacks["fn_4b"], 4)205 h.AddFilter("test_order", "my_callback_fn_1a", callbacks["fn_1a"], 1)206 h.AddFilter("test_order", "my_callback_fn_4c", callbacks["fn_4c"], 4)207 h.AddFilter("test_order", "my_callback_fn_1b", callbacks["fn_1b"], 1)208 h.AddFilter("test_order", "my_callback_fn_3d", callbacks["fn_3d"], 3)209 h.AddFilter("test_order", "my_callback_fn_4d", callbacks["fn_4d"], 4)210 h.AddFilter("test_order", "my_callback_fn_1c", callbacks["fn_1c"], 1)211 h.AddFilter("test_order", "my_callback_fn_2d", callbacks["fn_2d"], 2)212 h.AddFilter("test_order", "my_callback_fn_1d", callbacks["fn_1d"], 1)213 v = h.ApplyFilters("test_order", []string{})214 expected = []string{"1a", "1b", "1c", "1d", "2a", "2c", "2d", "3b", "3c", "3d", "4a", "4b", "4c", "4d"}215 if !reflect.DeepEqual(v, expected) {216 t.Errorf("Expected %s to be equal to %s", v, expected)217 }218}219// Add and remove an action220func TestAddRemoveAction(t *testing.T) {221 teardownTest := setupTest(t)222 defer teardownTest(t)223 expected := 1224 h.AddAction("test.action", "my_callback", actionA, 10)225 v := h.RemoveAllActions("test.action", "my_callback")226 if v != expected {227 t.Errorf("Expected %d to be equal to %d", v, expected)228 }229 v2 := h.DoAction("test.action")230 if v2 != nil {231 t.Errorf("Expected %p to be equal to %p", v2, interface{}(nil))232 }233 if actionValue != "" {234 t.Errorf("Expected %s to be equal to %s", actionValue, "")235 }236}237// Add an action and run it238func TestAddActionRun(t *testing.T) {239 teardownTest := setupTest(t)240 defer teardownTest(t)241 expected := "a"242 h.AddAction("test.action", "my_callback", actionA, 10)243 h.DoAction("test.action")244 if actionValue != expected {245 t.Errorf("Expected %s to be equal to %s", actionValue, expected)246 }247}248// Add 2 actions in a row and then run them249func TestAdd2ActionsRun(t *testing.T) {250 teardownTest := setupTest(t)251 defer teardownTest(t)252 expected := "ab"253 h.AddAction("test.action", "my_callback", actionA, 10)254 h.AddAction("test.action", "my_callback", actionB, 10)255 h.DoAction("test.action")256 if actionValue != expected {257 t.Errorf("Expected %s to be equal to %s", actionValue, expected)258 }259}260// Add 3 actions with different priorities and run them261func TestAdd3ActionsRun(t *testing.T) {262 teardownTest := setupTest(t)263 defer teardownTest(t)264 expected := "bca"265 h.AddAction("test.action", "my_callback", actionA, 10)266 h.AddAction("test.action", "my_callback", actionB, 2)267 h.AddAction("test.action", "my_callback", actionC, 8)268 h.DoAction("test.action")269 if actionValue != expected {270 t.Errorf("Expected %s to be equal to %s", actionValue, expected)271 }272}273// Pass in two arguments to an action274func TestAddActionArgs(t *testing.T) {275 teardownTest := setupTest(t)276 defer teardownTest(t)277 arg1 := Arg1{a: 1}278 arg2 := Arg2{b: 1}279 h.AddAction("test.action", "my_callback", func(i ...interface{}) interface{} {280 if p, ok := i[0].(Arg1); ok {281 expected := 1282 if p.a != expected {283 t.Errorf("Expected %d to be equal to %d", p.a, expected)284 }285 } else {286 t.Errorf("Expected %d to be equal to %d", p, Arg1{})287 }288 if p, ok := i[1].(Arg2); ok {289 expected := 1290 if p.b != expected {291 t.Errorf("Expected %d to be equal to %d", p.b, expected)292 }293 } else {294 t.Errorf("Expected %d to be equal to %d", p, Arg2{})295 }296 return nil297 }, 10)298 h.DoAction("test.action", arg1, arg2)299}300// Fire action multiple times301func TestAddActionFire(t *testing.T) {302 teardownTest := setupTest(t)303 defer teardownTest(t)304 act1 := func(i ...interface{}) interface{} {305 if true != true {306 t.Errorf("Expected %t to be equal to %t", true, true)307 }308 return nil309 }310 h.AddAction("test.action", "my_callback", act1, 10)311 h.DoAction("test.action")312 h.DoAction("test.action")313}314// Add a filter before the one currently executing315func TestAddFilterBefore(t *testing.T) {316 teardownTest := setupTest(t)317 defer teardownTest(t)318 h.AddFilter("test.filter", "my_callback", func(i ...interface{}) interface{} {319 h.AddFilter("test.filter", "my_callback", func(j ...interface{}) interface{} {320 if p, ok := j[0].(string); ok {321 return p + "a"322 }323 return nil324 }, 1)325 if p, ok := i[0].(string); ok {326 return p + "b"327 }328 return nil329 }, 2)330 expected := "test_b"331 v := h.ApplyFilters("test.filter", "test_")332 if v != expected {333 t.Errorf("Expected %s to be equal to %s", v, expected)334 }335}336// Add a filter after the one currently executing337func TestAddFilterAfter(t *testing.T) {338 teardownTest := setupTest(t)339 defer teardownTest(t)340 h.AddFilter("test.filter", "my_callback", func(i ...interface{}) interface{} {341 h.AddFilter("test.filter", "my_callback", func(j ...interface{}) interface{} {342 if p, ok := j[0].(string); ok {343 return p + "b"344 }345 return nil346 }, 2)347 if p, ok := i[0].(string); ok {348 return p + "a"349 }350 return nil351 }, 1)352 expected := "test_ab"353 v := h.ApplyFilters("test.filter", "test_")354 if v != expected {355 t.Errorf("Expected %s to be equal to %s", v, expected)356 }357}358// Add a filter immediately after the one currently executing359func TestAddFilterImmediatelyAfter(t *testing.T) {360 teardownTest := setupTest(t)361 defer teardownTest(t)362 h.AddFilter("test.filter", "my_callback", func(i ...interface{}) interface{} {363 h.AddFilter("test.filter", "my_callback", func(j ...interface{}) interface{} {364 if p, ok := j[0].(string); ok {365 return p + "b"366 }367 return nil368 }, 1)369 if p, ok := i[0].(string); ok {370 return p + "a"371 }372 return nil373 }, 1)374 expected := "test_ab"375 v := h.ApplyFilters("test.filter", "test_")376 if v != expected {377 t.Errorf("Expected %s to be equal to %s", v, expected)378 }379}380// Remove specific action callback381func TestRemoveActionCallback(t *testing.T) {382 teardownTest := setupTest(t)383 defer teardownTest(t)384 h.AddAction("test.action", "my_callback_action_a", actionA, 10)385 h.AddAction("test.action", "my_callback_action_b", actionB, 2)386 h.AddAction("test.action", "my_callback_action_b", actionC, 8)387 expected := 1388 ra := h.RemoveAction("test.action", "my_callback_action_b")389 if ra != expected {390 t.Errorf("Expected %d to be equal to %d", ra, expected)391 }392 h.DoAction("test.action")393 expected2 := "ca"394 if actionValue != expected2 {395 t.Errorf("Expected %s to be equal to %s", actionValue, expected2)396 }397}398// Remove all action callbacks399func TestRemoveActionAll(t *testing.T) {400 teardownTest := setupTest(t)401 defer teardownTest(t)402 h.AddAction("test.action", "my_callback_action_a", actionA, 10)403 h.AddAction("test.action", "my_callback_action_b", actionB, 2)404 h.AddAction("test.action", "my_callback_action_c", actionC, 8)405 expected := 3406 ra := h.RemoveAllActions("test.action", "")407 if ra != expected {408 t.Errorf("Expected %d to be equal to %d", ra, expected)409 }410 h.DoAction("test.action")411 expected2 := ""412 if actionValue != expected2 {413 t.Errorf("Expected %s to be equal to %s", actionValue, expected2)414 }415}416// Remove specific filter callback417func TestRemoveFilterCallback(t *testing.T) {418 teardownTest := setupTest(t)419 defer teardownTest(t)420 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 10)421 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 2)422 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 8)423 expected := 1424 ra := h.RemoveFilter("test.filter", "my_callback_filter_b")425 if ra != expected {426 t.Errorf("Expected %d to be equal to %d", ra, expected)427 }428 v := h.ApplyFilters("test.filter", "test")429 expected2 := "testca"430 if v != expected2 {431 t.Errorf("Expected %s to be equal to %s", v, expected2)432 }433}434// Filter removes a callback that has already executed435func TestRemoveFilterCallbackAfter(t *testing.T) {436 teardownTest := setupTest(t)437 defer teardownTest(t)438 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)439 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 3)440 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 5)441 h.AddFilter("test.filter", "my_callback_filter_removes_b", filterRemovesB, 4)442 v := h.ApplyFilters("test.filter", "test")443 expected := "testabc"444 if v != expected {445 t.Errorf("Expected %s to be equal to %s", v, expected)446 }447}448// Filter removes a callback that has already executed (same priority)449func TestRemoveFilterCallbackAfter2(t *testing.T) {450 teardownTest := setupTest(t)451 defer teardownTest(t)452 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)453 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 2)454 h.AddFilter("test.filter", "my_callback_filter_removes_b", filterRemovesB, 2)455 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 4)456 v := h.ApplyFilters("test.filter", "test")457 expected := "testabc"458 if v != expected {459 t.Errorf("Expected %s to be equal to %s", v, expected)460 }461}462// Filter removes the current callback463func TestRemoveFilterCallbackCurrent(t *testing.T) {464 teardownTest := setupTest(t)465 defer teardownTest(t)466 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)467 h.AddFilter("test.filter", "my_callback_filter_c_removes_self", filterCRemovesSelf, 3)468 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 5)469 v := h.ApplyFilters("test.filter", "test")470 expected := "testabc"471 if v != expected {472 t.Errorf("Expected %s to be equal to %s", v, expected)473 }474}475// Filter removes a callback that has not yet executed (last)476func TestRemoveFilterCallbackLast(t *testing.T) {477 teardownTest := setupTest(t)478 defer teardownTest(t)479 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)480 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 3)481 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 5)482 h.AddFilter("test.filter", "my_callback_filter_removes_c", filterRemovesC, 4)483 v := h.ApplyFilters("test.filter", "test")484 expected := "testab"485 if v != expected {486 t.Errorf("Expected %s to be equal to %s", v, expected)487 }488}489// Filter removes a callback that has not yet executed (middle)490func TestRemoveFilterCallbackMiddle(t *testing.T) {491 teardownTest := setupTest(t)492 defer teardownTest(t)493 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)494 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 3)495 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 4)496 h.AddFilter("test.filter", "my_callback_filter_removes_b", filterRemovesB, 2)497 v := h.ApplyFilters("test.filter", "test")498 expected := "testac"499 if v != expected {500 t.Errorf("Expected %s to be equal to %s", v, expected)501 }502}503// Filter removes a callback that has not yet executed (same priority)504func TestRemoveFilterCallbackSamePriority(t *testing.T) {505 teardownTest := setupTest(t)506 defer teardownTest(t)507 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 1)508 h.AddFilter("test.filter", "my_callback_filter_removes_b", filterRemovesB, 2)509 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 2)510 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 4)511 v := h.ApplyFilters("test.filter", "test")512 expected := "testac"513 if v != expected {514 t.Errorf("Expected %s to be equal to %s", v, expected)515 }516}517// Remove all filter callbacks518func TestRemoveAllFilterCallbacks(t *testing.T) {519 teardownTest := setupTest(t)520 defer teardownTest(t)521 h.AddFilter("test.filter", "my_callback_filter_a", filterA, 10)522 h.AddFilter("test.filter", "my_callback_filter_b", filterB, 2)523 h.AddFilter("test.filter", "my_callback_filter_c", filterC, 8)524 expected := 3525 ra := h.RemoveAllFilters("test.filter", "")526 if ra != expected {527 t.Errorf("Expected %d to be equal to %d", ra, expected)528 }529 v := h.ApplyFilters("test.filter", "test")530 expected2 := "test"531 if v != expected2 {532 t.Errorf("Expected %s to be equal to %s", v, expected2)533 }534}535// Test DoingAction, DidAction, HasAction.536func TestDoingActionDidActionHasAction(t *testing.T) {537 teardownTest := setupTest(t)538 defer teardownTest(t)539 actionCalls := 0540 h.AddAction("another.action", "my_callback", func(j ...interface{}) interface{} { return nil }, 10)541 h.DoAction("another.action")542 // Verify no action is running yet.543 if h.DoingAction("test.action") {544 t.Errorf("Expected action to not be running.")545 }546 if h.DidAction("test.action") != 0 {547 t.Errorf("Expected no action run.")548 }549 if h.HasAction("test.action") {550 t.Errorf("Expected action to not exist.")551 }552 h.AddAction("test.action", "my_callback", func(j ...interface{}) interface{} {553 actionCalls++554 // Expected current action to be test.action555 if hi, _ := h.CurrentAction(); hi.Name != "test.action" {556 t.Errorf("Expected current action to be test.action.")557 }558 if !h.DoingAction("") {559 t.Errorf("Expected action to be running.")560 }561 if !h.DoingAction("test.action") {562 t.Errorf("Expected test.action action to be running.")563 }564 return nil565 }, 10)566 // Verify action added, not running yet.567 if h.DoingAction("test.action") {568 t.Errorf("Expected action to not be running.")569 }570 if h.DidAction("test.action") != 0 {571 fmt.Println(h.DidAction("test.action"))572 t.Errorf("Expected no action run.")573 }574 if !h.HasAction("test.action") {575 t.Errorf("Expected action to be exist.")576 }577 // Run action.578 h.DoAction("test.action")579 // Verify action added and running.580 if actionCalls != 1 {581 t.Errorf("Expected action to be called once.")582 }583 if h.DoingAction("test.action") {584 t.Errorf("Expected action to not be running.")585 }586 // DidAction should return 1587 if h.DidAction("test.action") != 1 {588 t.Errorf("Expected action to be called once.")589 }590 // HasAction should return true591 if !h.HasAction("test.action") {592 t.Errorf("Expected action to be exist.")593 }594 // DoingAction with empty string should return false595 if h.DoingAction("") {596 t.Errorf("Expected action to not be running.")597 }598 // No action with "notatest.action" name is running599 if h.DoingAction("notatest.action") {600 t.Errorf("Expected notatest.action action to not be running.")601 }602 if _, err := h.CurrentAction(); err == nil {603 t.Errorf("Expected no current action.")604 }605 h.DoAction("test.action")606 // Verify actionCalls607 expected := 2608 if actionCalls != expected {609 t.Errorf("Expected actionCalls to be %d.", expected)610 }611 // Verify DidAction612 expected = 2613 if h.DidAction("test.action") != expected {614 t.Errorf("Expected DidAction to be %d.", expected)615 }616 v := h.RemoveAllActions("test.action", "")617 expected = 1618 if v != expected {619 t.Errorf("Expected %d to be equal to %d", v, expected)620 }621 // Verify state is reset appropriately.622 if h.DoingAction("test.action") {623 t.Errorf("Expected action to not be running.")624 }625 expected = 2626 if v := h.DidAction("test.action"); v != expected {627 t.Errorf("Expected %d to be equal to %d", v, expected)628 }629 if !h.HasAction("test.action") {630 t.Errorf("Expected action to be exist.")631 }632 h.DoAction("another.action")633 if h.DoingAction("test.action") {634 t.Errorf("Expected action to not be running.")635 }636 // Verify an action with no handlers is still counted637 if h.DidAction("unattached.action") != 0 {638 t.Errorf("Expected unattached.action action to not be run.")639 }640 h.DoAction("unattached.action")641 if h.DoingAction("unattached.action") {642 t.Errorf("Expected unattached.action action to not be running.")643 }644 if h.DidAction("unattached.action") != 1 {645 t.Errorf("Expected unattached.action action to be run.")646 }647 h.DoAction("unattached.action")648 if h.DoingAction("unattached.action") {649 t.Errorf("Expected unattached.action action to not be running.")650 }651 expected = 2652 if h.DidAction("unattached.action") != expected {653 t.Errorf("Expected unattached.action action to be run %d times.", expected)654 }655 // Verify hasAction returns false when no matching action.656 if h.HasAction("notatest.action") {657 t.Errorf("Expected notatest.action action to not exist.")658 }659}660// Verify doingFilter, didFilter and hasFilter.661func TestDoingFilterDidFilterHasFilter(t *testing.T) {662 teardownTest := setupTest(t)663 defer teardownTest(t)664 filterCalls := 0665 h.AddFilter("runtest.filter", "my_callback", func(arg ...interface{}) interface{} {666 filterCalls++667 if hi, _ := h.CurrentFilter(); hi.Name != "runtest.filter" {668 t.Errorf("Expected current filter to be runtest.filter.")669 }670 if !h.DoingFilter("") {671 t.Errorf("Expected filter to be running.")672 }673 if !h.DoingFilter("runtest.filter") {674 t.Errorf("Expected runtest.filter filter to be running.")675 }676 return arg[0]677 }, 10)678 // Verify filter added and running.679 test := h.ApplyFilters("runtest.filter", "someValue")680 if test != "someValue" {681 t.Errorf("Expected filter to return someValue.")682 }683 if filterCalls != 1 {684 t.Errorf("Expected filter to be called once.")685 }686 if h.DidFilter("runtest.filter") != 1 {687 t.Errorf("Expected DidFilter to be 1.")688 }689 if !h.HasFilter("runtest.filter") {690 t.Errorf("Expected filter to be exist.")691 }692 if h.HasFilter("notatest.filter") {693 t.Errorf("Expected notatest.filter filter to not exist.")694 }695 if h.DoingFilter("") {696 t.Errorf("Expected filter to not be running.")697 }698 if h.DoingFilter("runtest.filter") {699 t.Errorf("Expected runtest.filter filter to not be running.")700 }701 if h.DoingFilter("notatest.filter") {702 t.Errorf("Expected notatest.filter filter to not be running.")703 }704 if _, err := h.CurrentFilter(); err == nil {705 t.Errorf("Expected no current filter.")706 }707 expected := 1708 if v := h.RemoveAllFilters("runtest.filter", ""); v != expected {709 t.Errorf("Expected %d to be equal to %d", v, expected)710 }711 if !h.HasFilter("runtest.filter") {712 t.Errorf("Expected runtest.filter filter to not exist.")713 }714 expected = 1715 if v := h.DidFilter("runtest.filter"); v != expected {716 t.Errorf("Expected DidFilter to be %d.", expected)717 }718}719// Recursively calling a filter720func TestFilterRecursion(t *testing.T) {721 teardownTest := setupTest(t)722 defer teardownTest(t)723 h.AddFilter("test.filter", "my_callback", func(args ...interface{}) interface{} {724 arg1 := args[0]725 if p, ok := arg1.(string); ok {726 if len(p) == 7 {727 return args[0]728 }729 return h.ApplyFilters("test.filter", p+"X")730 }731 return nil732 }, 10)733 expected := "testXXX"734 test := h.ApplyFilters("test.filter", "testXXX")735 if test != expected {736 t.Errorf("Expected %s to be equal to %s", test, expected)737 }738}739// Current filter when multiple filters are running740func TestCurretFilterWithMultipleFiltersRunning(t *testing.T) {741 teardownTest := setupTest(t)742 defer teardownTest(t)743 h.AddFilter("test.filter1", "my_callback", func(args ...interface{}) interface{} {744 arg1 := args[0]745 if p, ok := arg1.([]string); ok {746 cf, _ := h.CurrentFilter()747 return h.ApplyFilters("test.filter2", append(p, cf.Name))748 }749 return nil750 }, 10)751 h.AddFilter("test.filter2", "my_callback", func(args ...interface{}) interface{} {752 arg1 := args[0]753 if p, ok := arg1.([]string); ok {754 cf, _ := h.CurrentFilter()755 return append(p, cf.Name)756 }757 return nil758 }, 10)759 if _, err := h.CurrentFilter(); err == nil {760 t.Errorf("Expected no current filter.")761 }762 v := h.ApplyFilters("test.filter1", []string{"test"})763 expected := []string{"test", "test.filter1", "test.filter2"}764 if !reflect.DeepEqual(v, expected) {765 t.Errorf("Expected %v to be equal to %v", v, expected)766 }767 if _, err := h.CurrentFilter(); err == nil {768 t.Errorf("Expected no current filter.")769 }770}771// Adding and removing filters with recursion772func TestAddRemoveFiltersWithRecursion(t *testing.T) {773 teardownTest := setupTest(t)774 defer teardownTest(t)775 var removeRecurseAndAdd2 func(...interface{}) interface{}776 removeRecurseAndAdd2 = func(val ...interface{}) interface{} {777 expected := 1778 v := h.RemoveFilter("remove_and_add", "my_callback_recurse")779 if v != expected {780 t.Errorf("Expected %d to be equal to %d", v, expected)781 }782 arg1 := val[0]783 if p, ok := arg1.(string); ok {784 fv := h.ApplyFilters("remove_and_add", "")785 p2, ok2 := fv.(string)786 if !ok2 {787 return nil788 }789 p += "-" + p2 + "-"790 h.AddFilter("remove_and_add", "my_callback_recurse", removeRecurseAndAdd2, 10)791 return p + "2"792 }793 return nil794 }795 h.AddFilter("remove_and_add", "my_callback", func(i ...interface{}) interface{} {796 arg1 := i[0]797 if p, ok := arg1.(string); ok {798 return p + "1"799 }800 return nil801 }, 11)802 h.AddFilter("remove_and_add", "my_callback_recurse", removeRecurseAndAdd2, 12)803 h.AddFilter("remove_and_add", "my_callback", func(i ...interface{}) interface{} {804 arg1 := i[0]805 if p, ok := arg1.(string); ok {806 return p + "3"807 }808 return nil809 }, 13)810 h.AddFilter("remove_and_add", "my_callback", func(i ...interface{}) interface{} {811 arg1 := i[0]812 if p, ok := arg1.(string); ok {813 return p + "4"814 }815 return nil816 }, 14)817 expected := "1-134-234"818 test := h.ApplyFilters("remove_and_add", "")819 if test != expected {820 t.Errorf("Expected %s to be equal to %s", test, expected)821 }822}823// Actions preserve arguments across handlers without return value824func TestActionsPreserveArguments(t *testing.T) {825 teardownTest := setupTest(t)826 defer teardownTest(t)827 arg1 := Arg1{a: 10}828 arg2 := Arg2{b: 20}829 h.AddAction("test.action", "my_callback1", func(i ...interface{}) interface{} {830 if p, ok := i[0].(Arg1); ok {831 expected := 10832 if p.a != expected {833 t.Errorf("Expected %d to be equal to %d", p.a, expected)834 }835 } else {836 t.Errorf("Expected %d to be equal to %d", p, Arg1{})837 }838 if p, ok := i[1].(Arg2); ok {839 expected := 20840 if p.b != expected {841 t.Errorf("Expected %d to be equal to %d", p.b, expected)842 }843 } else {844 t.Errorf("Expected %d to be equal to %d", p, Arg2{})845 }846 return nil847 }, 10)848 h.AddAction("test.action", "my_callback2", func(i ...interface{}) interface{} {849 if p, ok := i[0].(Arg1); ok {850 expected := 10851 if p.a != expected {852 t.Errorf("Expected %d to be equal to %d", p.a, expected)853 }854 } else {855 t.Errorf("Expected %d to be equal to %d", p, Arg1{})856 }857 if p, ok := i[1].(Arg2); ok {858 expected := 20859 if p.b != expected {860 t.Errorf("Expected %d to be equal to %d", p.b, expected)861 }862 } else {863 t.Errorf("Expected %d to be equal to %d", p, Arg2{})864 }865 return nil866 }, 10)867 h.DoAction("test.action", arg1, arg2)868}869// Filters pass first argument across handlers870func TestFiltersPassArguments(t *testing.T) {871 teardownTest := setupTest(t)872 defer teardownTest(t)873 h.AddFilter("test.filter", "my_callback1", func(i ...interface{}) interface{} {874 if p, ok := i[0].(int); ok {875 return p + 1876 }877 return nil878 }, 10)879 h.AddFilter("test.filter", "my_callback2", func(i ...interface{}) interface{} {880 if p, ok := i[0].(int); ok {881 return p + 1882 }883 return nil884 }, 10)885 expected := 2886 test := h.ApplyFilters("test.filter", 0)887 if test != expected {888 t.Errorf("Expected %d to be equal to %d", test, expected)889 }890}891// Adding an action triggers a hookAdded action892func TestAddActionTriggersHookAdded(t *testing.T) {893 teardownTest := setupTest(t)894 defer teardownTest(t)895 numberOfCalls := 0896 fn := func(i ...interface{}) interface{} {897 numberOfCalls++898 return nil899 }900 h.AddAction("HookAdded", "my_callback", fn, 10)901 h.AddAction("testAction", "my_callback2", actionA, 9)902 expected := 1903 if numberOfCalls != expected {904 t.Errorf("Expected %d to be equal to %d", numberOfCalls, expected)905 }906}907// Adding a filter triggers a hookAdded action908func TestAddFilterTriggersHookAdded(t *testing.T) {909 teardownTest := setupTest(t)910 defer teardownTest(t)911 numberOfCalls := 0912 fn := func(i ...interface{}) interface{} {913 numberOfCalls++914 return nil915 }916 h.AddAction("HookAdded", "my_callback", fn, 10)917 h.AddFilter("testFilter", "my_callback2", filterA, 8)918 expected := 1919 if numberOfCalls != expected {920 t.Errorf("Expected %d to be equal to %d", numberOfCalls, expected)921 }922}923// Removing an action triggers a hookRemoved action924func TestRemoveActionTriggersHookRemoved(t *testing.T) {925 teardownTest := setupTest(t)926 defer teardownTest(t)927 numberOfCalls := 0928 fn := func(i ...interface{}) interface{} {929 numberOfCalls++930 return nil931 }932 h.AddAction("HookRemoved", "my_callback", fn, 10)933 h.AddAction("testAction", "my_callback2", actionA, 9)934 h.RemoveAction("testAction", "my_callback2")935 expected := 1936 if numberOfCalls != expected {937 t.Errorf("Expected %d to be equal to %d", numberOfCalls, expected)938 }939}940// Removing a filter triggers a hookRemoved action941func TestRemoveFilterTriggersHookRemoved(t *testing.T) {942 teardownTest := setupTest(t)943 defer teardownTest(t)944 numberOfCalls := 0945 fn := func(i ...interface{}) interface{} {946 numberOfCalls++947 return nil948 }949 h.AddAction("HookRemoved", "my_callback", fn, 10)950 h.AddFilter("testFilter", "my_callback3", filterA, 8)951 h.RemoveFilter("testFilter", "my_callback3")952 expected := 1953 if numberOfCalls != expected {954 t.Errorf("Expected %d to be equal to %d", numberOfCalls, expected)955 }956}...
filters_test.go
Source:filters_test.go
1// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved.2// Licensed under the Mozilla Public License v2.03package oci4import (5 "strconv"6 "strings"7 "testing"8 "reflect"9 "github.com/hashicorp/terraform-plugin-sdk/helper/schema"10 oci_core "github.com/oracle/oci-go-sdk/v46/core"11)12// Not supplying filters should not restrict results13// issue-routing-tag: terraform/default14func TestUnitApplyFilters_passThrough(t *testing.T) {15 items := []map[string]interface{}{16 {},17 {},18 {},19 }20 testSchema := map[string]*schema.Schema{21 "letter": {22 Type: schema.TypeString,23 },24 }25 res := ApplyFilters(nil, items, testSchema)26 if len(res) != 3 {27 t.Errorf("Expected 3 results, got %d", len(res))28 }29}30// Filtering against a nonexistent property should throw no errors and return no results31// issue-routing-tag: terraform/default32func TestUnitApplyFilters_nonExistentProperty(t *testing.T) {33 items := []map[string]interface{}{34 {"letter": "a"},35 }36 testSchema := map[string]*schema.Schema{37 "letter": {38 Type: schema.TypeString,39 },40 }41 filters := &schema.Set{F: func(interface{}) int { return 1 }}42 filters.Add(map[string]interface{}{43 "name": "number",44 "values": []interface{}{"1"},45 })46 res := ApplyFilters(filters, items, testSchema)47 if len(res) > 0 {48 t.Errorf("Expected 0 results, got %d", len(res))49 }50}51// Filtering against an empty resource set should not throw errors52// issue-routing-tag: terraform/default53func TestUnitApplyFilters_noResources(t *testing.T) {54 items := []map[string]interface{}{}55 testSchema := map[string]*schema.Schema{56 "number": {57 Type: schema.TypeString,58 },59 }60 filters := &schema.Set{F: func(interface{}) int { return 1 }}61 filters.Add(map[string]interface{}{62 "name": "number",63 "values": []interface{}{"1"},64 })65 res := ApplyFilters(filters, items, testSchema)66 if len(res) != 0 {67 t.Errorf("Expected 0 results, got %d", len(res))68 }69}70// issue-routing-tag: terraform/default71func TestUnitApplyFilters_basic(t *testing.T) {72 items := []map[string]interface{}{73 {"letter": "a"},74 {"letter": "b"},75 {"letter": "c"},76 }77 testSchema := map[string]*schema.Schema{78 "letter": {79 Type: schema.TypeString,80 },81 }82 filters := &schema.Set{F: func(interface{}) int { return 1 }}83 filters.Add(map[string]interface{}{84 "name": "letter",85 "values": []interface{}{"b"},86 })87 res := ApplyFilters(filters, items, testSchema)88 if len(res) != 1 {89 t.Errorf("Expected 1 result, got %d", len(res))90 }91}92// issue-routing-tag: terraform/default93func TestUnitApplyFilters_duplicates(t *testing.T) {94 items := []map[string]interface{}{95 {"letter": "a"},96 {"letter": "a"},97 {"letter": "c"},98 }99 testSchema := map[string]*schema.Schema{100 "letter": {101 Type: schema.TypeString,102 },103 }104 filters := &schema.Set{F: func(v interface{}) int {105 return schema.HashString(v.(map[string]interface{})["name"])106 }}107 filters.Add(map[string]interface{}{108 "name": "letter",109 "values": []interface{}{"a"},110 })111 res := ApplyFilters(filters, items, testSchema)112 if len(res) != 2 {113 t.Errorf("Expected 2 results, got %d", len(res))114 }115}116// issue-routing-tag: terraform/default117func TestUnitApplyFilters_OR(t *testing.T) {118 items := []map[string]interface{}{119 {"letter": "a"},120 {"letter": "b"},121 {"letter": "c"},122 }123 testSchema := map[string]*schema.Schema{124 "letter": {125 Type: schema.TypeString,126 },127 }128 filters := &schema.Set{129 F: func(v interface{}) int {130 elems := v.(map[string]interface{})["values"].([]interface{})131 res := make([]string, len(elems))132 for i, v := range elems {133 res[i] = v.(string)134 }135 return schema.HashString(strings.Join(res, ""))136 },137 }138 filters.Add(map[string]interface{}{139 "name": "letter",140 "values": []interface{}{"a", "b"},141 })142 res := ApplyFilters(filters, items, testSchema)143 if len(res) != 2 {144 t.Errorf("Expected 2 results, got %d", len(res))145 }146}147// issue-routing-tag: terraform/default148func TestUnitApplyFilters_cascadeAND(t *testing.T) {149 items := []map[string]interface{}{150 {"letter": "a"},151 {"letter": "b"},152 {"letter": "c"},153 }154 testSchema := map[string]*schema.Schema{155 "letter": {156 Type: schema.TypeString,157 },158 }159 filters := &schema.Set{160 F: func(v interface{}) int {161 elems := v.(map[string]interface{})["values"].([]interface{})162 res := make([]string, len(elems))163 for i, v := range elems {164 res[i] = v.(string)165 }166 return schema.HashString(strings.Join(res, ""))167 },168 }169 filters.Add(map[string]interface{}{170 "name": "letter",171 "values": []interface{}{"a", "b"},172 })173 filters.Add(map[string]interface{}{174 "name": "letter",175 "values": []interface{}{"c"},176 })177 res := ApplyFilters(filters, items, testSchema)178 if len(res) != 0 {179 t.Errorf("Expected 0 results, got %d", len(res))180 }181}182// issue-routing-tag: terraform/default183func TestUnitApplyFilters_regex(t *testing.T) {184 items := []map[string]interface{}{185 {"string": "xblx:PHX-AD-1"},186 {"string": "xblx:PHX-AD-2"},187 {"string": "xblx:PHX-AD-3"},188 }189 testSchema := map[string]*schema.Schema{190 "string": {191 Type: schema.TypeString,192 },193 }194 filters := &schema.Set{F: func(v interface{}) int {195 return schema.HashString(v.(map[string]interface{})["name"])196 }}197 filters.Add(map[string]interface{}{198 "name": "string",199 "values": []interface{}{"\\w*:PHX-AD-2"},200 "regex": true,201 })202 res := ApplyFilters(filters, items, testSchema)203 if len(res) != 1 {204 t.Errorf("Expected 1 result, got %d", len(res))205 }206}207// Filters should test against an array of strings208// issue-routing-tag: terraform/default209func TestUnitApplyFilters_arrayOfStrings(t *testing.T) {210 items := []map[string]interface{}{211 {"letters": []string{"a"}},212 {"letters": []string{"b", "c"}},213 {"letters": []string{"c", "d", "e"}},214 {"letters": []string{"e", "f"}},215 }216 testSchema := map[string]*schema.Schema{217 "letters": {218 Type: schema.TypeList,219 Elem: schema.TypeString,220 },221 }222 filters := &schema.Set{F: func(interface{}) int { return 1 }}223 filters.Add(map[string]interface{}{224 "name": "letters",225 "values": []interface{}{"a", "c"},226 })227 res := ApplyFilters(filters, items, testSchema)228 if len(res) != 3 {229 t.Errorf("Expected 3 result, got %d", len(res))230 }231 filters = &schema.Set{F: func(interface{}) int { return 1 }}232 filters.Add(map[string]interface{}{233 "name": "letters",234 "values": []interface{}{"a", "f"},235 })236 res = ApplyFilters(filters, items, testSchema)237 if len(res) != 2 {238 t.Errorf("Expected 2 result, got %d", len(res))239 }240}241type CustomStringTypeA string242type CustomStringTypeB CustomStringTypeA243type CustomEnumType oci_core.VcnLifecycleStateEnum244// issue-routing-tag: terraform/default245func TestUnitApplyFilters_underlyingStringTypes(t *testing.T) {246 items := []map[string]interface{}{247 {248 "letters": []CustomStringTypeA{"a"},249 "number": CustomStringTypeB("1"),250 "state": oci_core.SecurityListLifecycleStateAvailable,251 "custom": CustomEnumType(oci_core.VcnLifecycleStateTerminated),252 },253 {254 "letters": []CustomStringTypeA{"a"},255 "number": CustomStringTypeB("1"),256 "state": oci_core.SecurityListLifecycleStateProvisioning,257 "custom": CustomEnumType(oci_core.VcnLifecycleStateTerminating),258 },259 {260 "letters": []CustomStringTypeA{"b", "c"},261 "number": CustomStringTypeB("2"),262 "state": oci_core.SecurityListLifecycleStateTerminating,263 "custom": CustomEnumType(oci_core.VcnLifecycleStateProvisioning),264 },265 {266 "letters": []CustomStringTypeA{"c", "d", "e"},267 "number": CustomStringTypeB("3"),268 "state": oci_core.SecurityListLifecycleStateTerminated,269 "custom": CustomEnumType(oci_core.VcnLifecycleStateAvailable),270 },271 {272 "letters": []CustomStringTypeA{"e", "f"},273 "number": CustomStringTypeB("5"),274 "state": oci_core.SecurityListLifecycleStateAvailable,275 "custom": CustomEnumType(oci_core.VcnLifecycleStateTerminated),276 },277 }278 testSchema := map[string]*schema.Schema{279 "letters": {280 Type: schema.TypeList,281 Elem: schema.TypeString,282 },283 "number": {284 Type: schema.TypeString,285 },286 "state": {287 Type: schema.TypeString,288 },289 "custom": {290 Type: schema.TypeString,291 },292 }293 filters := &schema.Set{294 F: func(v interface{}) int {295 return schema.HashString(v.(map[string]interface{})["name"])296 },297 }298 filters.Add(map[string]interface{}{299 "name": "letters",300 "values": []interface{}{"a", "c"},301 })302 res := ApplyFilters(filters, items, testSchema)303 if len(res) != 4 {304 t.Errorf("Expected 4 result, got %d", len(res))305 }306 filters1 := &schema.Set{307 F: func(v interface{}) int {308 return schema.HashString(v.(map[string]interface{})["name"])309 },310 }311 filters1.Add(map[string]interface{}{312 "name": "letters",313 "values": []interface{}{"a", "b", "e"},314 })315 filters1.Add(map[string]interface{}{316 "name": "number",317 "values": []interface{}{"1", "notANumber"},318 })319 res = ApplyFilters(filters1, items, testSchema)320 if len(res) != 2 {321 t.Errorf("Expected 2 result, got %d", len(res))322 }323 filters2 := &schema.Set{324 F: func(v interface{}) int {325 return schema.HashString(v.(map[string]interface{})["name"])326 },327 }328 filters2.Add(map[string]interface{}{329 "name": "letters",330 "values": []interface{}{"a", "b", "e"},331 })332 filters2.Add(map[string]interface{}{333 "name": "number",334 "values": []interface{}{"1", "2", "3", "5"},335 })336 filters2.Add(map[string]interface{}{337 "name": "state",338 "values": []interface{}{string(oci_core.SecurityListLifecycleStateAvailable), string(oci_core.SecurityListLifecycleStateTerminating)},339 })340 filters2.Add(map[string]interface{}{341 "name": "custom",342 "values": []interface{}{string(oci_core.VcnLifecycleStateProvisioning)},343 })344 res = ApplyFilters(filters2, items, testSchema)345 if len(res) != 1 {346 t.Errorf("Expected 1 result, got %d", len(res))347 }348}349// Test fields that aren't supported: list of non-strings or structured objects350// issue-routing-tag: terraform/default351func TestUnitApplyFilters_unsupportedTypes(t *testing.T) {352 items := []map[string]interface{}{353 {354 "nums": []int{1, 2, 3},355 },356 {357 "nums": []int{3, 4, 5},358 },359 {360 "nums": []int{5, 6, 7},361 },362 }363 testSchema := map[string]*schema.Schema{364 "nums": {365 Type: schema.TypeList,366 Elem: schema.TypeInt,367 },368 }369 filters := &schema.Set{370 F: func(v interface{}) int {371 return schema.HashString(v.(map[string]interface{})["name"])372 },373 }374 intArrayFilter := map[string]interface{}{375 "name": "nums",376 "values": []interface{}{"1", "3", "5"},377 }378 filters.Add(intArrayFilter)379 res := ApplyFilters(filters, items, testSchema)380 if len(res) != 0 {381 t.Errorf("Expected 0 result, got %d", len(res))382 }383}384// issue-routing-tag: terraform/default385func TestUnitApplyFilters_booleanTypes(t *testing.T) {386 items := []map[string]interface{}{387 {388 "enabled": true,389 },390 {391 "enabled": "true",392 },393 {394 "enabled": "1",395 },396 {397 "enabled": false,398 },399 {400 "enabled": "false",401 },402 {403 "enabled": "0",404 },405 }406 testSchema := map[string]*schema.Schema{407 "enabled": {408 Type: schema.TypeBool,409 },410 }411 filters := &schema.Set{412 F: func(v interface{}) int {413 return schema.HashString(v.(map[string]interface{})["name"])414 },415 }416 truthyBooleanFilter := map[string]interface{}{417 "name": "enabled",418 "values": []interface{}{"true", "1"}, // while we can pass an actual boolean true here in the test, terraform419 // doesnt, so keep coercion logic simple in filters.go420 }421 filters.Add(truthyBooleanFilter)422 res := ApplyFilters(filters, items, testSchema)423 for _, i := range res {424 switch enabled := i["enabled"].(type) {425 case bool:426 if !enabled {427 t.Errorf("Expected a truthy value, got %t", enabled)428 }429 case string:430 enabledBool, _ := strconv.ParseBool(enabled)431 if !enabledBool {432 t.Errorf("Expected a truthy value, got %s", enabled)433 }434 }435 }436 if len(res) != 3 {437 t.Errorf("Expected 3 results, got %d", len(res))438 }439 filters.Remove(truthyBooleanFilter)440 falsyBooleanFilter := map[string]interface{}{441 "name": "enabled",442 "values": []interface{}{"false", "0"},443 }444 filters.Add(falsyBooleanFilter)445 res = ApplyFilters(filters, items, testSchema)446 for _, i := range res {447 switch enabled := i["enabled"].(type) {448 case bool:449 if enabled {450 t.Errorf("Expected a falsy value, got %t", enabled)451 }452 case string:453 enabledBool, _ := strconv.ParseBool(enabled)454 if enabledBool {455 t.Errorf("Expected a falsy value, got %s", enabled)456 }457 }458 }459 if len(res) != 3 {460 t.Errorf("Expected 3 results, got %d", len(res))461 }462 filters.Remove(falsyBooleanFilter)463}464// issue-routing-tag: terraform/default465func TestUnitApplyFilters_numberTypes(t *testing.T) {466 items := []map[string]interface{}{467 {468 "integer": 1,469 "float": 1.1,470 },471 {472 "integer": 2,473 "float": 2.2,474 },475 {476 "integer": 3,477 "float": 3.3,478 },479 }480 testSchema := map[string]*schema.Schema{481 "integer": {482 Type: schema.TypeInt,483 },484 "float": {485 Type: schema.TypeFloat,486 },487 }488 filters := &schema.Set{489 F: func(v interface{}) int {490 return schema.HashString(v.(map[string]interface{})["name"])491 },492 }493 // int filter with single target value494 intFilter := map[string]interface{}{495 "name": "integer",496 "values": []interface{}{"2"},497 }498 filters.Add(intFilter)499 res := ApplyFilters(filters, items, testSchema)500 if len(res) != 1 {501 t.Errorf("Expected 1 result, got %d", len(res))502 }503 filters.Remove(intFilter)504 // test filter with multiple target value505 intsFilter := map[string]interface{}{506 "name": "integer",507 "values": []interface{}{"1", "3"},508 }509 filters.Add(intsFilter)510 res = ApplyFilters(filters, items, testSchema)511 if len(res) != 2 {512 t.Errorf("Expected 2 results, got %d", len(res))513 }514 filters.Remove(intsFilter)515 // test float filter516 floatFilter := map[string]interface{}{517 "name": "float",518 "values": []interface{}{"1.1", "3.3"},519 }520 filters.Add(floatFilter)521 res = ApplyFilters(filters, items, testSchema)522 if len(res) != 2 {523 t.Errorf("Expected 2 results, got %d", len(res))524 }525 filters.Remove(floatFilter)526}527// issue-routing-tag: terraform/default528func TestUnitApplyFilters_multiProperty(t *testing.T) {529 items := []map[string]interface{}{530 {531 "letter": "a",532 "number": "1",533 "symbol": "!",534 },535 {536 "letter": "b",537 "number": "2",538 "symbol": "@",539 },540 {541 "letter": "c",542 "number": "3",543 "symbol": "#",544 },545 {546 "letter": "d",547 "number": "4",548 "symbol": "$",549 },550 }551 testSchema := map[string]*schema.Schema{552 "letter": {553 Type: schema.TypeString,554 },555 "number": {556 Type: schema.TypeInt,557 },558 "symbol": {559 Type: schema.TypeString,560 },561 }562 filters := &schema.Set{563 F: func(v interface{}) int {564 return schema.HashString(v.(map[string]interface{})["name"])565 },566 }567 filters.Add(map[string]interface{}{568 "name": "letter",569 "values": []interface{}{"a", "b", "c"},570 })571 filters.Add(map[string]interface{}{572 "name": "number",573 "values": []interface{}{"2", "3", "4"},574 })575 filters.Add(map[string]interface{}{576 "name": "symbol",577 "values": []interface{}{"#", "$"},578 })579 res := ApplyFilters(filters, items, testSchema)580 if len(res) != 1 {581 t.Errorf("Expected 1 result, got %d", len(res))582 }583}584// Test to validate that the Apply filters do not impact the original item order585// issue-routing-tag: terraform/default586func TestUnitApplyFilters_ElementOrder(t *testing.T) {587 items := []map[string]interface{}{588 {"letter": "a"},589 {"letter": "b"},590 {"letter": "c"},591 {"letter": "d"},592 }593 testSchema := map[string]*schema.Schema{594 "letter": {595 Type: schema.TypeString,596 },597 }598 filters := &schema.Set{F: func(interface{}) int { return 1 }}599 filters.Add(map[string]interface{}{600 "name": "letter",601 "values": []interface{}{"a", "d"},602 })603 res := ApplyFilters(filters, items, testSchema)604 if len(res) != 2 {605 t.Errorf("Expected 2 result, got %d", len(res))606 }607 if res[0]["letter"] != "a" || res[1]["letter"] != "d" {608 t.Errorf("Expected sort order not retained, got %s %s", res[0]["letter"], res[1]["letter"])609 }610}611// issue-routing-tag: terraform/default612func TestUnitGetValue_EmptyMap(t *testing.T) {613 item := map[string]interface{}{}614 _, singleLevelGetOk := getValueFromPath(item, []string{"path"})615 _, multiLevelGetOk := getValueFromPath(item, []string{"path", "to", "target"})616 if singleLevelGetOk || multiLevelGetOk {617 t.Error("Expected non OK result")618 }619}620// issue-routing-tag: terraform/default621func TestUnitGetValue_MultiLevelMap(t *testing.T) {622 item := map[string]interface{}{623 "level1": map[string]interface{}{624 "level2": map[string]interface{}{625 "level3": "value",626 },627 },628 }629 singleLevelGet, singleLevelGetOk := getValueFromPath(item, []string{"level1"})630 multiLevelGet, multiLevelGetOk := getValueFromPath(item, []string{"level1", "level2", "level3"})631 if !singleLevelGetOk || !multiLevelGetOk {632 t.Errorf("Expected OK result for topLevel %v multi level %v", singleLevelGetOk, multiLevelGetOk)633 }634 if multiLevelGet != "value" {635 t.Errorf("Expected = value, Got = %s", multiLevelGet)636 }637 if len(singleLevelGet.(map[string]interface{})) != 1 {638 t.Error("Expected size of map is 1")639 }640}641// issue-routing-tag: terraform/default642func TestUnitGetPathElements_EmptyFilterName(t *testing.T) {643 if _, error := getFieldPathElements(CoreInstanceResource().Schema, ""); error == nil {644 t.Error("expected non nil error")645 }646}647// issue-routing-tag: terraform/default648func TestUnitGetPathElements_NonExistentPropertyTopLevel(t *testing.T) {649 if _, error := getFieldPathElements(CoreInstanceResource().Schema, "non_existent"); error == nil {650 t.Error("expected non nil error")651 }652}653// issue-routing-tag: terraform/default654func TestUnitGetPathElements_NonExistentPropertyNestedLevel(t *testing.T) {655 if _, error := getFieldPathElements(CoreInstanceResource().Schema, "create_vnic_details.non_existent"); error == nil {656 t.Error("expected non nil error")657 }658}659// issue-routing-tag: terraform/default660func TestUnitGetPathElements_TopLevelPrimitive(t *testing.T) {661 if path, error := getFieldPathElements(CoreInstanceResource().Schema, "boot_volume_id"); error != nil || !reflect.DeepEqual(path, []string{"boot_volume_id"}) {662 t.Errorf("unexpected path value %s found", path)663 }664}665// issue-routing-tag: terraform/default666func TestUnitGetPathElements_MultiLevelMap(t *testing.T) {667 if path, error := getFieldPathElements(CoreInstanceResource().Schema, "create_vnic_details.defined_tags.namespace.key"); error != nil || !reflect.DeepEqual(path, []string{"create_vnic_details", "defined_tags", "namespace.key"}) {668 t.Errorf("unexpected path value %s found", path)669 }670}671// issue-routing-tag: terraform/default672func TestUnitGetPathElements_MultiLevelNonMap(t *testing.T) {673 if path, error := getFieldPathElements(CoreInstanceResource().Schema, "launch_options.firmware"); error != nil || !reflect.DeepEqual(path, []string{"launch_options", "firmware"}) {674 t.Errorf("unexpected path value %s found", path)675 }676 if _, error := getFieldPathElements(CoreInstanceResource().Schema, "launch_options.firmware.XYZ"); error == nil {677 t.Errorf("Expected Error")678 }679}680// issue-routing-tag: terraform/default681func TestUnitNestedMap(t *testing.T) {682 item := map[string]interface{}{683 "level1": map[string]interface{}{684 "level2": map[string]interface{}{685 "level3": "value",686 "level3_1": []string{"A", "B", "C"},687 "level3_2": []int{2, 3, 4},688 "level3_3": []float64{2.1, 3.1, 4.1},689 "level3_4": []interface{}{2, 3, 4},690 },691 },692 }693 services := genericMapToJsonMap(item)694 if len(services) != 1 {695 t.Errorf("unexpected number of values returned in map")696 }697}...
filter_test.go
Source:filter_test.go
1package statuspage2import (3 "encoding/json"4 "reflect"5 "strconv"6 "strings"7 "testing"8 "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"9)10// Not supplying filters should not restrict results11func TestUnitApplyFilters_passThrough(t *testing.T) {12 items := []map[string]interface{}{13 {},14 {},15 {},16 }17 testSchema := map[string]*schema.Schema{18 "letter": {19 Type: schema.TypeString,20 },21 }22 res := ApplyFilters(nil, items, testSchema)23 if len(res) != 3 {24 t.Errorf("Expected 3 results, got %d", len(res))25 }26}27// Filtering against a nonexistent property should throw no errors and return no results28func TestUnitApplyFilters_nonExistentProperty(t *testing.T) {29 items := []map[string]interface{}{30 {"letter": "a"},31 }32 testSchema := map[string]*schema.Schema{33 "letter": {34 Type: schema.TypeString,35 },36 }37 filters := &schema.Set{F: func(interface{}) int { return 1 }}38 filters.Add(map[string]interface{}{39 "name": "number",40 "values": []interface{}{"1"},41 })42 res := ApplyFilters(filters, items, testSchema)43 if len(res) > 0 {44 t.Errorf("Expected 0 results, got %d", len(res))45 }46}47// Filtering against an empty resource set should not throw errors48func TestUnitApplyFilters_noResources(t *testing.T) {49 items := []map[string]interface{}{}50 testSchema := map[string]*schema.Schema{51 "number": {52 Type: schema.TypeString,53 },54 }55 filters := &schema.Set{F: func(interface{}) int { return 1 }}56 filters.Add(map[string]interface{}{57 "name": "number",58 "values": []interface{}{"1"},59 })60 res := ApplyFilters(filters, items, testSchema)61 if len(res) != 0 {62 t.Errorf("Expected 0 results, got %d", len(res))63 }64}65func TestUnitApplyFilters_basic(t *testing.T) {66 items := []map[string]interface{}{67 {"letter": "a"},68 {"letter": "b"},69 {"letter": "c"},70 }71 testSchema := map[string]*schema.Schema{72 "letter": {73 Type: schema.TypeString,74 },75 }76 filters := &schema.Set{F: func(interface{}) int { return 1 }}77 filters.Add(map[string]interface{}{78 "name": "letter",79 "values": []interface{}{"b"},80 })81 res := ApplyFilters(filters, items, testSchema)82 if len(res) != 1 {83 t.Errorf("Expected 1 result, got %d", len(res))84 }85}86func TestUnitApplyFilters_duplicates(t *testing.T) {87 items := []map[string]interface{}{88 {"letter": "a"},89 {"letter": "a"},90 {"letter": "c"},91 }92 testSchema := map[string]*schema.Schema{93 "letter": {94 Type: schema.TypeString,95 },96 }97 filters := &schema.Set{F: func(v interface{}) int {98 return schema.HashString(v.(map[string]interface{})["name"])99 }}100 filters.Add(map[string]interface{}{101 "name": "letter",102 "values": []interface{}{"a"},103 })104 res := ApplyFilters(filters, items, testSchema)105 if len(res) != 2 {106 t.Errorf("Expected 2 results, got %d", len(res))107 }108}109func TestUnitApplyFilters_OR(t *testing.T) {110 items := []map[string]interface{}{111 {"letter": "a"},112 {"letter": "b"},113 {"letter": "c"},114 }115 testSchema := map[string]*schema.Schema{116 "letter": {117 Type: schema.TypeString,118 },119 }120 filters := &schema.Set{121 F: func(v interface{}) int {122 elems := v.(map[string]interface{})["values"].([]interface{})123 res := make([]string, len(elems))124 for i, v := range elems {125 res[i] = v.(string)126 }127 return schema.HashString(strings.Join(res, ""))128 },129 }130 filters.Add(map[string]interface{}{131 "name": "letter",132 "values": []interface{}{"a", "b"},133 })134 res := ApplyFilters(filters, items, testSchema)135 if len(res) != 2 {136 t.Errorf("Expected 2 results, got %d", len(res))137 }138}139func TestUnitApplyFilters_cascadeAND(t *testing.T) {140 items := []map[string]interface{}{141 {"letter": "a"},142 {"letter": "b"},143 {"letter": "c"},144 }145 testSchema := map[string]*schema.Schema{146 "letter": {147 Type: schema.TypeString,148 },149 }150 filters := &schema.Set{151 F: func(v interface{}) int {152 elems := v.(map[string]interface{})["values"].([]interface{})153 res := make([]string, len(elems))154 for i, v := range elems {155 res[i] = v.(string)156 }157 return schema.HashString(strings.Join(res, ""))158 },159 }160 filters.Add(map[string]interface{}{161 "name": "letter",162 "values": []interface{}{"a", "b"},163 })164 filters.Add(map[string]interface{}{165 "name": "letter",166 "values": []interface{}{"c"},167 })168 res := ApplyFilters(filters, items, testSchema)169 if len(res) != 0 {170 t.Errorf("Expected 0 results, got %d", len(res))171 }172}173func TestUnitApplyFilters_regex(t *testing.T) {174 items := []map[string]interface{}{175 {"string": "xblx:PHX-AD-1"},176 {"string": "xblx:PHX-AD-2"},177 {"string": "xblx:PHX-AD-3"},178 }179 testSchema := map[string]*schema.Schema{180 "string": {181 Type: schema.TypeString,182 },183 }184 filters := &schema.Set{F: func(v interface{}) int {185 return schema.HashString(v.(map[string]interface{})["name"])186 }}187 filters.Add(map[string]interface{}{188 "name": "string",189 "values": []interface{}{"\\w*:PHX-AD-2"},190 "regex": true,191 })192 res := ApplyFilters(filters, items, testSchema)193 if len(res) != 1 {194 t.Errorf("Expected 1 result, got %d", len(res))195 }196}197// Filters should test against an array of strings198func TestUnitApplyFilters_arrayOfStrings(t *testing.T) {199 items := []map[string]interface{}{200 {"letters": []string{"a"}},201 {"letters": []string{"b", "c"}},202 {"letters": []string{"c", "d", "e"}},203 {"letters": []string{"e", "f"}},204 }205 testSchema := map[string]*schema.Schema{206 "letters": {207 Type: schema.TypeList,208 Elem: schema.TypeString,209 },210 }211 filters := &schema.Set{F: func(interface{}) int { return 1 }}212 filters.Add(map[string]interface{}{213 "name": "letters",214 "values": []interface{}{"a", "c"},215 })216 res := ApplyFilters(filters, items, testSchema)217 if len(res) != 3 {218 t.Errorf("Expected 3 result, got %d", len(res))219 }220 filters = &schema.Set{F: func(interface{}) int { return 1 }}221 filters.Add(map[string]interface{}{222 "name": "letters",223 "values": []interface{}{"a", "f"},224 })225 res = ApplyFilters(filters, items, testSchema)226 if len(res) != 2 {227 t.Errorf("Expected 2 result, got %d", len(res))228 }229}230type CustomStringTypeA string231type CustomStringTypeB CustomStringTypeA232// Test fields that aren't supported: list of non-strings or structured objects233func TestUnitApplyFilters_unsupportedTypes(t *testing.T) {234 items := []map[string]interface{}{235 {236 "nums": []int{1, 2, 3},237 },238 {239 "nums": []int{3, 4, 5},240 },241 {242 "nums": []int{5, 6, 7},243 },244 }245 testSchema := map[string]*schema.Schema{246 "nums": {247 Type: schema.TypeList,248 Elem: schema.TypeInt,249 },250 }251 filters := &schema.Set{252 F: func(v interface{}) int {253 return schema.HashString(v.(map[string]interface{})["name"])254 },255 }256 intArrayFilter := map[string]interface{}{257 "name": "nums",258 "values": []interface{}{"1", "3", "5"},259 }260 filters.Add(intArrayFilter)261 res := ApplyFilters(filters, items, testSchema)262 if len(res) != 0 {263 t.Errorf("Expected 0 result, got %d", len(res))264 }265}266func TestUnitApplyFilters_booleanTypes(t *testing.T) {267 items := []map[string]interface{}{268 {269 "enabled": true,270 },271 {272 "enabled": "true",273 },274 {275 "enabled": "1",276 },277 {278 "enabled": false,279 },280 {281 "enabled": "false",282 },283 {284 "enabled": "0",285 },286 }287 testSchema := map[string]*schema.Schema{288 "enabled": {289 Type: schema.TypeBool,290 },291 }292 filters := &schema.Set{293 F: func(v interface{}) int {294 return schema.HashString(v.(map[string]interface{})["name"])295 },296 }297 truthyBooleanFilter := map[string]interface{}{298 "name": "enabled",299 "values": []interface{}{"true", "1"}, // while we can pass an actual boolean true here in the test, terraform300 // doesnt, so keep coercion logic simple in filters.go301 }302 filters.Add(truthyBooleanFilter)303 res := ApplyFilters(filters, items, testSchema)304 for _, i := range res {305 switch enabled := i["enabled"].(type) {306 case bool:307 if !enabled {308 t.Errorf("Expected a truthy value, got %t", enabled)309 }310 case string:311 enabledBool, _ := strconv.ParseBool(enabled)312 if !enabledBool {313 t.Errorf("Expected a truthy value, got %s", enabled)314 }315 }316 }317 if len(res) != 3 {318 t.Errorf("Expected 3 results, got %d", len(res))319 }320 filters.Remove(truthyBooleanFilter)321 falsyBooleanFilter := map[string]interface{}{322 "name": "enabled",323 "values": []interface{}{"false", "0"},324 }325 filters.Add(falsyBooleanFilter)326 res = ApplyFilters(filters, items, testSchema)327 for _, i := range res {328 switch enabled := i["enabled"].(type) {329 case bool:330 if enabled {331 t.Errorf("Expected a falsy value, got %t", enabled)332 }333 case string:334 enabledBool, _ := strconv.ParseBool(enabled)335 if enabledBool {336 t.Errorf("Expected a falsy value, got %s", enabled)337 }338 }339 }340 if len(res) != 3 {341 t.Errorf("Expected 3 results, got %d", len(res))342 }343 filters.Remove(falsyBooleanFilter)344}345func TestUnitApplyFilters_numberTypes(t *testing.T) {346 items := []map[string]interface{}{347 {348 "integer": 1,349 "float": 1.1,350 },351 {352 "integer": 2,353 "float": 2.2,354 },355 {356 "integer": 3,357 "float": 3.3,358 },359 }360 testSchema := map[string]*schema.Schema{361 "integer": {362 Type: schema.TypeInt,363 },364 "float": {365 Type: schema.TypeFloat,366 },367 }368 filters := &schema.Set{369 F: func(v interface{}) int {370 return schema.HashString(v.(map[string]interface{})["name"])371 },372 }373 // int filter with single target value374 intFilter := map[string]interface{}{375 "name": "integer",376 "values": []interface{}{"2"},377 }378 filters.Add(intFilter)379 res := ApplyFilters(filters, items, testSchema)380 if len(res) != 1 {381 t.Errorf("Expected 1 result, got %d", len(res))382 }383 filters.Remove(intFilter)384 // test filter with multiple target value385 intsFilter := map[string]interface{}{386 "name": "integer",387 "values": []interface{}{"1", "3"},388 }389 filters.Add(intsFilter)390 res = ApplyFilters(filters, items, testSchema)391 if len(res) != 2 {392 t.Errorf("Expected 2 results, got %d", len(res))393 }394 filters.Remove(intsFilter)395 // test float filter396 floatFilter := map[string]interface{}{397 "name": "float",398 "values": []interface{}{"1.1", "3.3"},399 }400 filters.Add(floatFilter)401 res = ApplyFilters(filters, items, testSchema)402 if len(res) != 2 {403 t.Errorf("Expected 2 results, got %d", len(res))404 }405 filters.Remove(floatFilter)406}407func TestUnitApplyFilters_multiProperty(t *testing.T) {408 items := []map[string]interface{}{409 {410 "letter": "a",411 "number": "1",412 "symbol": "!",413 },414 {415 "letter": "b",416 "number": "2",417 "symbol": "@",418 },419 {420 "letter": "c",421 "number": "3",422 "symbol": "#",423 },424 {425 "letter": "d",426 "number": "4",427 "symbol": "$",428 },429 }430 testSchema := map[string]*schema.Schema{431 "letter": {432 Type: schema.TypeString,433 },434 "number": {435 Type: schema.TypeInt,436 },437 "symbol": {438 Type: schema.TypeString,439 },440 }441 filters := &schema.Set{442 F: func(v interface{}) int {443 return schema.HashString(v.(map[string]interface{})["name"])444 },445 }446 filters.Add(map[string]interface{}{447 "name": "letter",448 "values": []interface{}{"a", "b", "c"},449 })450 filters.Add(map[string]interface{}{451 "name": "number",452 "values": []interface{}{"2", "3", "4"},453 })454 filters.Add(map[string]interface{}{455 "name": "symbol",456 "values": []interface{}{"#", "$"},457 })458 res := ApplyFilters(filters, items, testSchema)459 if len(res) != 1 {460 t.Errorf("Expected 1 result, got %d", len(res))461 }462}463// Test to validate that the Apply filters do not impact the original item order464func TestUnitApplyFilters_ElementOrder(t *testing.T) {465 items := []map[string]interface{}{466 {"letter": "a"},467 {"letter": "b"},468 {"letter": "c"},469 {"letter": "d"},470 }471 testSchema := map[string]*schema.Schema{472 "letter": {473 Type: schema.TypeString,474 },475 }476 filters := &schema.Set{F: func(interface{}) int { return 1 }}477 filters.Add(map[string]interface{}{478 "name": "letter",479 "values": []interface{}{"a", "d"},480 })481 res := ApplyFilters(filters, items, testSchema)482 if len(res) != 2 {483 t.Errorf("Expected 2 result, got %d", len(res))484 }485 if res[0]["letter"] != "a" || res[1]["letter"] != "d" {486 t.Errorf("Expected sort order not retained, got %s %s", res[0]["letter"], res[1]["letter"])487 }488}489func TestUnitGetValue_EmptyMap(t *testing.T) {490 item := map[string]interface{}{}491 _, singleLevelGetOk := getValueFromPath(item, []string{"path"})492 _, multiLevelGetOk := getValueFromPath(item, []string{"path", "to", "target"})493 if singleLevelGetOk || multiLevelGetOk {494 t.Error("Expected non OK result")495 }496}497func TestUnitGetValue_MultiLevelMap(t *testing.T) {498 item := map[string]interface{}{499 "level1": map[string]interface{}{500 "level2": map[string]interface{}{501 "level3": "value",502 },503 },504 }505 singleLevelGet, singleLevelGetOk := getValueFromPath(item, []string{"level1"})506 multiLevelGet, multiLevelGetOk := getValueFromPath(item, []string{"level1", "level2", "level3"})507 if !singleLevelGetOk || !multiLevelGetOk {508 t.Errorf("Expected OK result for topLevel %v multi level %v", singleLevelGetOk, multiLevelGetOk)509 }510 if multiLevelGet != "value" {511 t.Errorf("Expected = value, Got = %s", multiLevelGet)512 }513 if len(singleLevelGet.(map[string]interface{})) != 1 {514 t.Error("Expected size of map is 1")515 }516}517func TestUnitNestedMap(t *testing.T) {518 item := map[string]interface{}{519 "level1": map[string]interface{}{520 "level2": map[string]interface{}{521 "level3": "value",522 "level3_1": []string{"A", "B", "C"},523 "level3_2": []int{2, 3, 4},524 "level3_3": []float64{2.1, 3.1, 4.1},525 "level3_4": []interface{}{2, 3, 4},526 },527 },528 }529 services := genericMapToJsonMap(item)530 if len(services) != 1 {531 t.Errorf("unexpected number of values returned in map")532 }533}534// Helper to marshal JSON objects from service into strings that can be stored in state.535// This limitation exists because Terraform doesn't support maps of nested objects and so we use JSON strings representation536// as a workaround.537func genericMapToJsonMap(genericMap map[string]interface{}) map[string]interface{} {538 result := map[string]interface{}{}539 for key, value := range genericMap {540 switch v := value.(type) {541 case string:542 result[key] = v543 default:544 bytes, err := json.Marshal(v)545 if err != nil {546 continue547 }548 result[key] = string(bytes)549 }550 }551 return result552}553func Test_convertToObjectMap(t *testing.T) {554 m := make(map[string]string)555 m["key1"] = "value1"556 m1 := make(map[string]string)557 m1["key1"] = ""558 type args struct {559 stringTostring map[string]string560 }561 tests := []struct {562 name string563 args args564 want map[string]interface{}565 }{566 {name: "stringNoEmpty", args: args{m}, want: map[string]interface{}{"key1": "value1"}},567 {name: "stringEmpty", args: args{m1}, want: map[string]interface{}{"key1": ""}},568 }569 for _, tt := range tests {570 t.Run(tt.name, func(t *testing.T) {571 if got := convertToObjectMap(tt.args.stringTostring); !reflect.DeepEqual(got, tt.want) {572 t.Errorf("convertToObjectMap() = %v, want %v", got, tt.want)573 }574 })575 }576}577func Test_checkAndConvertMap(t *testing.T) {578 m := make(map[string]string)579 m["key1"] = "value1"580 m1 := make(map[string]interface{})581 m1["key1"] = "value1"582 m2 := make(map[string]int)583 m2["key1"] = 1584 type args struct {585 element interface{}586 }587 tests := []struct {588 name string589 args args590 want map[string]interface{}591 want1 bool592 }{593 {name: "string", args: args{m}, want: map[string]interface{}{"key1": "value1"}, want1: true},594 {name: "interface", args: args{m1}, want: map[string]interface{}{"key1": "value1"}, want1: true},595 {name: "int", args: args{m2}, want: nil, want1: false},596 }597 for _, tt := range tests {598 t.Run(tt.name, func(t *testing.T) {599 got, got1 := checkAndConvertMap(tt.args.element)600 if !reflect.DeepEqual(got, tt.want) {601 t.Errorf("checkAndConvertMap() got = %v, want %v", got, tt.want)602 }603 if got1 != tt.want1 {604 t.Errorf("checkAndConvertMap() got1 = %v, want %v", got1, tt.want1)605 }606 })607 }608}609func Test_checkAndConvertNestedStructure(t *testing.T) {610 var m []interface{}611 m = append(m, map[string]interface{}{"key1": "value1"})612 var m1 []interface{}613 m1 = append(m, map[string]interface{}{"key1": "value1"})614 m1 = append(m, map[string]interface{}{"key2": "value2"})615 type args struct {616 element interface{}617 }618 tests := []struct {619 name string620 args args621 want map[string]interface{}622 want1 bool623 }{624 {name: "array_single_value", args: args{m}, want: map[string]interface{}{"key1": "value1"}, want1: true},625 {name: "array_mutiple_values", args: args{m1}, want: nil, want1: false},626 }627 for _, tt := range tests {628 t.Run(tt.name, func(t *testing.T) {629 got, got1 := checkAndConvertNestedStructure(tt.args.element)630 if !reflect.DeepEqual(got, tt.want) {631 t.Errorf("checkAndConvertNestedStructure() got = %v, want %v", got, tt.want)632 }633 if got1 != tt.want1 {634 t.Errorf("checkAndConvertNestedStructure() got1 = %v, want %v", got1, tt.want1)635 }636 })637 }638}...
applyFilters
Using AI Code Generation
1import (2func main() {3 f := filter{}4 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)5}6import (7func main() {8 f := filter{}9 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)10}11import (12func main() {13 f := filter{}14 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)15}16import (17func main() {18 f := filter{}19 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)20}21import (22func main() {23 f := filter{}24 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)25}26import (27func main() {28 f := filter{}29 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)30}31import (32func main() {33 f := filter{}34 f.applyFilters(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)35}36import (37func main() {
applyFilters
Using AI Code Generation
1func main() {2 filter := filter.New()3 filter.ApplyFilters()4}5func main() {6 filter := filter.New()7 filter.ApplyFilters()8}9func main() {10 filter := filter.New()11 filter.ApplyFilters()12}13func main() {14 filter := filter.New()15 filter.ApplyFilters()16}17func main() {18 filter := filter.New()19 filter.ApplyFilters()20}21func main() {22 filter := filter.New()23 filter.ApplyFilters()24}25func main() {26 filter := filter.New()27 filter.ApplyFilters()28}29func main() {30 filter := filter.New()31 filter.ApplyFilters()32}33func main() {34 filter := filter.New()35 filter.ApplyFilters()36}37func main() {38 filter := filter.New()39 filter.ApplyFilters()40}41func main() {42 filter := filter.New()43 filter.ApplyFilters()44}45func main() {46 filter := filter.New()47 filter.ApplyFilters()48}49func main() {50 filter := filter.New()51 filter.ApplyFilters()52}53func main() {54 filter := filter.New()55 filter.ApplyFilters()56}57func main() {58 filter := filter.New()59 filter.ApplyFilters()60}
applyFilters
Using AI Code Generation
1import "fmt"2func main() {3 filters := []func(int) int{4 }5 numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}6 for _, filter := range filters {7 numbers = filter(numbers)8 }9 fmt.Println(numbers)10}11import "fmt"12func main() {13 filters := []func(int) int{14 }15 numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}16 f := filter{}17 numbers = f.applyFilters(filters, numbers)18 fmt.Println(numbers)19}
applyFilters
Using AI Code Generation
1func main() {2 filter := filter.NewFilter()3 filter.ApplyFilters()4}5func main() {6 filter := filter.NewFilter()7 filter.ApplyFilters()8}9func main() {10 filter := filter.NewFilter()11 filter.ApplyFilters()12}13func main() {14 filter := filter.NewFilter()15 filter.ApplyFilters()16}17func main() {18 filter := filter.NewFilter()19 filter.ApplyFilters()20}21func main() {22 filter := filter.NewFilter()23 filter.ApplyFilters()24}25func main() {26 filter := filter.NewFilter()27 filter.ApplyFilters()28}29func main() {30 filter := filter.NewFilter()31 filter.ApplyFilters()32}33func main() {34 filter := filter.NewFilter()35 filter.ApplyFilters()36}37func main() {38 filter := filter.NewFilter()39 filter.ApplyFilters()40}41func main() {42 filter := filter.NewFilter()43 filter.ApplyFilters()44}45func main() {
applyFilters
Using AI Code Generation
1import "fmt"2func main() {3 filters = &FilterImpl{}4 filters.applyFilters()5}6type Filter interface {7 applyFilters()8}9type FilterImpl struct {10}11func (f *FilterImpl) applyFilters() {12 fmt.Println("Applying filters")13}14import "fmt"15func main() {16 person = &Student{}17 person.displayPersonDetails()18 person = &Employee{}19 person.displayPersonDetails()20}21type Person interface {22 displayPersonDetails()23}24import "fmt"25type Student struct {26}27func (s *Student) displayPersonDetails() {28 fmt.Println("I am a student")29}30import "fmt"31type Employee struct {32}33func (e *Employee) displayPersonDetails() {34 fmt.Println("I am an employee")35}36import "fmt"37func main() {38 shape = &Circle{}39 shape.calculateArea()40 shape = &Rectangle{}41 shape.calculateArea()42}43type Shape interface {44 calculateArea()45}46import "fmt"47type Circle struct {48}49func (c *Circle) calculateArea() {50 fmt.Println("Calculating area of circle")51}52import "fmt
applyFilters
Using AI Code Generation
1import (2func main() {3 file, err := os.Open("image.jpg")4 if err != nil {5 fmt.Println(err)6 os.Exit(1)7 }8 defer file.Close()9 img, err := jpeg.Decode(file)10 if err != nil {11 fmt.Println(err)12 os.Exit(1)13 }14 bounds := img.Bounds()15 newImage := image.NewRGBA(bounds)16 for y := bounds.Min.Y; y < bounds.Max.Y; y++ {17 for x := bounds.Min.X; x < bounds.Max.X; x++ {18 oldColor := img.At(x, y)19 r, g, b, a := oldColor.RGBA()20 newColor := color.RGBA{21 uint8(r / 256),22 uint8(g / 256),23 uint8(b / 256),24 uint8(a / 256),25 }26 newImage.Set(x, y, newColor)27 }28 }29 newFile, err := os.Create("newImage.jpg")30 if err != nil {31 fmt.Println(err)32 os.Exit(1)33 }34 defer newFile.Close()35 jpeg.Encode(newFile, newImage, nil)36}37import (38func main() {39 file, err := os.Open("image.jpg")
applyFilters
Using AI Code Generation
1import "sync"2func main() {3 wg.Add(3)4 go func() {5 defer wg.Done()6 }()7 go func() {8 defer wg.Done()9 }()10 go func() {11 defer wg.Done()12 }()13 wg.Wait()14}
applyFilters
Using AI Code Generation
1import (2func main() {3 f := filter{}4 strs := []string{"hello", "filter", "world", "filter"}5 f.applyFilters(strs, func(s string) bool {6 return strings.Contains(s, "filter")7 })8}
applyFilters
Using AI Code Generation
1import "fmt"2func main() {3 filter := new(Filter)4 names := []string{"Sam", "Peter", "David"}5 filter.applyFilters(names, startsWithS, lengthGreaterThan5)6}7import "fmt"8func main() {9 filter := new(Filter)10 names := []string{"Sam", "Peter", "David"}11 filter.applyFilters(names, startsWithS, lengthGreaterThan5)12}13import "fmt"14func main() {15 filter := new(Filter)16 names := []string{"Sam", "Peter", "David"}17 filter.applyFilters(names, startsWithS, lengthGreaterThan5)18}19import "fmt"20func main() {21 filter := new(Filter)22 names := []string{"Sam", "Peter", "David"}23 filter.applyFilters(names, startsWithS, lengthGreaterThan5)24}25import "fmt"26func main() {27 filter := new(Filter)28 names := []string{"Sam", "Peter", "David"}29 filter.applyFilters(names, startsWithS, lengthGreaterThan5)30}31import "fmt"32func main() {33 filter := new(Filter)34 names := []string{"Sam", "Peter", "David"}35 filter.applyFilters(names, startsWithS, lengthGreaterThan5)36}
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!!