Best Got code snippet using diff.Concat
parser_test.go
Source:parser_test.go
1package query2import (3 "encoding/json"4 "errors"5 "fmt"6 "strings"7 "testing"8 "github.com/google/go-cmp/cmp"9)10func TestParseParameterList(t *testing.T) {11 cases := []struct {12 Name string13 Input string14 Want string15 WantLabels labels16 WantRange string17 }{18 {19 Name: "Normal field:value",20 Input: `file:README.md`,21 Want: `{"field":"file","value":"README.md","negated":false}`,22 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":14}}`,23 WantLabels: None,24 },25 {26 Name: "First char is colon",27 Input: `:foo`,28 Want: `{"value":":foo","negated":false}`,29 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":4}}`,30 WantLabels: Regexp,31 },32 {33 Name: "Last char is colon",34 Input: `foo:`,35 Want: `{"value":"foo:","negated":false}`,36 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":4}}`,37 WantLabels: Regexp,38 },39 {40 Name: "Match first colon",41 Input: `file:bar:baz`,42 Want: `{"field":"file","value":"bar:baz","negated":false}`,43 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":12}}`,44 WantLabels: None,45 },46 {47 Name: "No field, start with minus",48 Input: `-:foo`,49 Want: `{"value":"-:foo","negated":false}`,50 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":5}}`,51 WantLabels: Regexp,52 },53 {54 Name: "Minus prefix on field",55 Input: `-file:README.md`,56 Want: `{"field":"file","value":"README.md","negated":true}`,57 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":15}}`,58 WantLabels: Regexp,59 },60 {61 Name: "Double minus prefix on field",62 Input: `--foo:bar`,63 Want: `{"value":"--foo:bar","negated":false}`,64 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":9}}`,65 WantLabels: Regexp,66 },67 {68 Name: "Minus in the middle is not a valid field",69 Input: `fie-ld:bar`,70 Want: `{"value":"fie-ld:bar","negated":false}`,71 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":10}}`,72 WantLabels: Regexp,73 },74 {75 Name: "Preserve escaped whitespace",76 Input: `a\ pattern`,77 Want: `{"value":"a\\ pattern","negated":false}`,78 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":10}}`,79 WantLabels: Regexp,80 },81 {82 Input: `"quoted"`,83 Want: `{"value":"quoted","negated":false}`,84 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":8}}`,85 WantLabels: Literal | Quoted,86 },87 {88 Input: `'\''`,89 Want: `{"value":"'","negated":false}`,90 WantRange: `{"start":{"line":0,"column":0},"end":{"line":0,"column":4}}`,91 WantLabels: Literal | Quoted,92 },93 }94 for _, tt := range cases {95 t.Run(tt.Name, func(t *testing.T) {96 parser := &parser{buf: []byte(tt.Input)}97 result, err := parser.parseLeavesRegexp()98 if err != nil {99 t.Fatal(fmt.Sprintf("Unexpected error: %s", err))100 }101 resultNode := result[0]102 got, _ := json.Marshal(resultNode)103 // Check parsed values.104 if diff := cmp.Diff(tt.Want, string(got)); diff != "" {105 t.Error(diff)106 }107 // Check ranges.108 switch n := resultNode.(type) {109 case Pattern:110 rangeStr := n.Annotation.Range.String()111 if diff := cmp.Diff(tt.WantRange, rangeStr); diff != "" {112 t.Error(diff)113 }114 case Parameter:115 rangeStr := n.Annotation.Range.String()116 if diff := cmp.Diff(tt.WantRange, rangeStr); diff != "" {117 t.Error(diff)118 }119 }120 // Check labels.121 if patternNode, ok := resultNode.(Pattern); ok {122 if diff := cmp.Diff(tt.WantLabels, patternNode.Annotation.Labels); diff != "" {123 t.Error(diff)124 }125 }126 })127 }128}129func TestScanField(t *testing.T) {130 type value struct {131 Field string132 Advance int133 }134 cases := []struct {135 Input string136 Want value137 }{138 // Valid field.139 {140 Input: "repo:foo",141 Want: value{142 Field: "repo",143 Advance: 5,144 },145 },146 {147 Input: "RepO:foo",148 Want: value{149 Field: "RepO",150 Advance: 5,151 },152 },153 {154 Input: "after:",155 Want: value{156 Field: "after",157 Advance: 6,158 },159 },160 {161 Input: "-repo:",162 Want: value{163 Field: "-repo",164 Advance: 6,165 },166 },167 // Invalid field.168 {169 Input: "",170 Want: value{171 Field: "",172 Advance: 0,173 },174 },175 {176 Input: "-",177 Want: value{178 Field: "",179 Advance: 0,180 },181 },182 {183 Input: "-:",184 Want: value{185 Field: "",186 Advance: 0,187 },188 },189 {190 Input: ":",191 Want: value{192 Field: "",193 Advance: 0,194 },195 },196 {197 Input: "??:foo",198 Want: value{199 Field: "",200 Advance: 0,201 },202 },203 {204 Input: "repo",205 Want: value{206 Field: "",207 Advance: 0,208 },209 },210 {211 Input: "-repo",212 Want: value{213 Field: "",214 Advance: 0,215 },216 },217 {218 Input: "--repo:",219 Want: value{220 Field: "",221 Advance: 0,222 },223 },224 {225 Input: ":foo",226 Want: value{227 Field: "",228 Advance: 0,229 },230 },231 }232 for _, c := range cases {233 t.Run("scan field", func(t *testing.T) {234 gotField, gotAdvance := ScanField([]byte(c.Input))235 if diff := cmp.Diff(c.Want, value{gotField, gotAdvance}); diff != "" {236 t.Error(diff)237 }238 })239 }240}241func parseAndOrGrammar(in string) ([]Node, error) {242 if strings.TrimSpace(in) == "" {243 return nil, nil244 }245 parser := &parser{246 buf: []byte(in),247 leafParser: SearchTypeRegex,248 }249 nodes, err := parser.parseOr()250 if err != nil {251 return nil, err252 }253 if parser.balanced != 0 {254 return nil, errors.New("unbalanced expression")255 }256 return newOperator(nodes, And), nil257}258func TestParse(t *testing.T) {259 type relation string // a relation for comparing test outputs of queries parsed according to grammar and heuristics.260 const Same relation = "Same" // a constant that says heuristic output is interpreted the same as the grammar spec.261 type Spec = relation // constructor for expected output of the grammar spec without heuristics.262 type Diff = relation // constructor for expected heuristic output when different to the grammar spec.263 cases := []struct {264 Name string265 Input string266 WantGrammar relation267 WantHeuristic relation268 }{269 {270 Name: "Empty string",271 Input: "",272 WantGrammar: "",273 WantHeuristic: Same,274 },275 {276 Name: "Whitespace",277 Input: " ",278 WantGrammar: "",279 WantHeuristic: Same,280 },281 {282 Name: "Single",283 Input: "a",284 WantGrammar: `"a"`,285 WantHeuristic: Same,286 },287 {288 Name: "Whitespace basic",289 Input: "a b",290 WantGrammar: `(concat "a" "b")`,291 WantHeuristic: Same,292 },293 {294 Name: "Basic",295 Input: "a and b and c",296 WantGrammar: `(and "a" "b" "c")`,297 WantHeuristic: Same,298 },299 {300 Input: "(f(x)oo((a|b))bar)",301 WantGrammar: Spec(`(concat "f" "x" "oo" "a|b" "bar")`),302 WantHeuristic: Diff(`"(f(x)oo((a|b))bar)"`),303 },304 {305 Input: "aorb",306 WantGrammar: `"aorb"`,307 WantHeuristic: Same,308 },309 {310 Input: "aANDb",311 WantGrammar: `"aANDb"`,312 WantHeuristic: Same,313 },314 {315 Input: "a oror b",316 WantGrammar: `(concat "a" "oror" "b")`,317 WantHeuristic: Same,318 },319 {320 Name: "Reduced complex query mixed caps",321 Input: "a and b AND c or d and (e OR f) g h i or j",322 WantGrammar: `(or (and "a" "b" "c") (and "d" (concat (or "e" "f") "g" "h" "i")) "j")`,323 WantHeuristic: Same,324 },325 {326 Name: "Basic reduced complex query",327 Input: "a and b or c and d or e",328 WantGrammar: `(or (and "a" "b") (and "c" "d") "e")`,329 WantHeuristic: Same,330 },331 {332 Name: "Reduced complex query, reduction over parens",333 Input: "(a and b or c and d) or e",334 WantGrammar: `(or (and "a" "b") (and "c" "d") "e")`,335 WantHeuristic: Same,336 },337 {338 Name: "Reduced complex query, nested 'or' trickles up",339 Input: "(a and b or c) or d",340 WantGrammar: `(or (and "a" "b") "c" "d")`,341 WantHeuristic: Same,342 },343 {344 Name: "Reduced complex query, nested nested 'or' trickles up",345 Input: "(a and b or (c and d or f)) or e",346 WantGrammar: `(or (and "a" "b") (and "c" "d") "f" "e")`,347 WantHeuristic: Same,348 },349 {350 Name: "No reduction on precedence defined by parens",351 Input: "(a and (b or c) and d) or e",352 WantGrammar: `(or (and "a" (or "b" "c") "d") "e")`,353 WantHeuristic: Same,354 },355 {356 Name: "Paren reduction over operators",357 Input: "(((a b c))) and d",358 WantGrammar: Spec(`(and (concat "a" "b" "c") "d")`),359 WantHeuristic: Diff(`(and "(((a b c)))" "d")`),360 },361 // Partition parameters and concatenated patterns.362 {363 Input: "a (b and c) d",364 WantGrammar: `(concat "a" (and "b" "c") "d")`,365 WantHeuristic: Same,366 },367 {368 Input: "(a b c) and (d e f) and (g h i)",369 WantGrammar: Spec(`(and (concat "a" "b" "c") (concat "d" "e" "f") (concat "g" "h" "i"))`),370 WantHeuristic: `(and "(a b c)" "(d e f)" "(g h i)")`,371 },372 {373 Input: "(a) repo:foo (b)",374 WantGrammar: Spec(`(and "repo:foo" (concat "a" "b"))`),375 WantHeuristic: Diff(`(and "repo:foo" (concat "(a)" "(b)"))`),376 },377 {378 Input: "repo:foo func( or func(.*)",379 WantGrammar: Spec(`expected operand at 15`),380 WantHeuristic: Diff(`(and "repo:foo" (or "func(" "func(.*)"))`),381 },382 {383 Input: "repo:foo main { and bar {",384 WantGrammar: Spec(`(and (and "repo:foo" (concat "main" "{")) (concat "bar" "{"))`),385 WantHeuristic: Diff(`(and "repo:foo" (concat "main" "{") (concat "bar" "{"))`),386 },387 {388 Input: "a b (repo:foo c d)",389 WantGrammar: `(concat "a" "b" (and "repo:foo" (concat "c" "d")))`,390 WantHeuristic: Same,391 },392 {393 Input: "a b (c d repo:foo)",394 WantGrammar: `(concat "a" "b" (and "repo:foo" (concat "c" "d")))`,395 WantHeuristic: Same,396 },397 {398 Input: "a repo:b repo:c (d repo:e repo:f)",399 WantGrammar: `(and "repo:b" "repo:c" (concat "a" (and "repo:e" "repo:f" "d")))`,400 WantHeuristic: Same,401 },402 {403 Input: "a repo:b repo:c (repo:e repo:f (repo:g repo:h))",404 WantGrammar: `(and "repo:b" "repo:c" "repo:e" "repo:f" "repo:g" "repo:h" "a")`,405 WantHeuristic: Same,406 },407 {408 Input: "a repo:b repo:c (repo:e repo:f (repo:g repo:h)) b",409 WantGrammar: `(and "repo:b" "repo:c" "repo:e" "repo:f" "repo:g" "repo:h" (concat "a" "b"))`,410 WantHeuristic: Same,411 },412 {413 Input: "a repo:b repo:c (repo:e repo:f (repo:g repo:h b)) ",414 WantGrammar: `(and "repo:b" "repo:c" (concat "a" (and "repo:e" "repo:f" "repo:g" "repo:h" "b")))`,415 WantHeuristic: Same,416 },417 {418 Input: "(repo:foo a (repo:bar b (repo:qux c)))",419 WantGrammar: `(and "repo:foo" (concat "a" (and "repo:bar" (concat "b" (and "repo:qux" "c")))))`,420 WantHeuristic: Same,421 },422 {423 Input: "a repo:b repo:c (d repo:e repo:f e)",424 WantGrammar: `(and "repo:b" "repo:c" (concat "a" (and "repo:e" "repo:f" (concat "d" "e"))))`,425 WantHeuristic: Same,426 },427 // Keywords as patterns.428 {429 Input: "a or",430 WantGrammar: `(concat "a" "or")`,431 WantHeuristic: Same,432 },433 {434 Input: "or",435 WantGrammar: `"or"`,436 WantHeuristic: Same,437 },438 {439 Input: "or or or",440 WantGrammar: `(or "or" "or")`,441 WantHeuristic: Same,442 },443 {444 Input: "and and andand or oror",445 WantGrammar: `(or (and "and" "andand") "oror")`,446 WantHeuristic: Same,447 },448 // Errors.449 {450 Name: "Unbalanced",451 Input: "(foo) (bar",452 WantGrammar: Spec("unbalanced expression"),453 WantHeuristic: Diff(`(concat "(foo)" "(bar")`),454 },455 {456 Name: "Illegal expression on the right",457 Input: "a or or b",458 WantGrammar: "expected operand at 5",459 WantHeuristic: Same,460 },461 {462 Name: "Illegal expression on the right, mixed operators",463 Input: "a and OR",464 WantGrammar: `(and "a" "OR")`,465 WantHeuristic: Same,466 },467 {468 Input: "repo:foo or or or",469 WantGrammar: "expected operand at 12",470 WantHeuristic: Same,471 },472 // Reduction.473 {474 Name: "paren reduction with ands",475 Input: "(a and b) and (c and d)",476 WantGrammar: `(and "a" "b" "c" "d")`,477 WantHeuristic: Same,478 },479 {480 Name: "paren reduction with ors",481 Input: "(a or b) or (c or d)",482 WantGrammar: `(or "a" "b" "c" "d")`,483 WantHeuristic: Same,484 },485 {486 Name: "nested paren reduction with whitespace",487 Input: "(((a b c))) d",488 WantGrammar: Spec(`(concat "a" "b" "c" "d")`),489 WantHeuristic: Diff(`(concat "(((a b c)))" "d")`),490 },491 {492 Name: "left paren reduction with whitespace",493 Input: "(a b) c d",494 WantGrammar: Spec(`(concat "a" "b" "c" "d")`),495 WantHeuristic: Diff(`(concat "(a b)" "c" "d")`),496 },497 {498 Name: "right paren reduction with whitespace",499 Input: "a b (c d)",500 WantGrammar: Spec(`(concat "a" "b" "c" "d")`),501 WantHeuristic: Diff(`(concat "a" "b" "(c d)")`),502 },503 {504 Name: "grouped paren reduction with whitespace",505 Input: "(a b) (c d)",506 WantGrammar: Spec(`(concat "a" "b" "c" "d")`),507 WantHeuristic: Diff(`(concat "(a b)" "(c d)")`),508 },509 {510 Name: "multiple grouped paren reduction with whitespace",511 Input: "(a b) (c d) (e f)",512 WantGrammar: Spec(`(concat "a" "b" "c" "d" "e" "f")`),513 WantHeuristic: Diff(`(concat "(a b)" "(c d)" "(e f)")`),514 },515 {516 Name: "interpolated grouped paren reduction",517 Input: "(a b) c d (e f)",518 WantGrammar: Spec(`(concat "a" "b" "c" "d" "e" "f")`),519 WantHeuristic: Diff(`(concat "(a b)" "c" "d" "(e f)")`),520 },521 {522 Name: "mixed interpolated grouped paren reduction",523 Input: "(a and b and (z or q)) and (c and d) and (e and f)",524 WantGrammar: `(and "a" "b" (or "z" "q") "c" "d" "e" "f")`,525 WantHeuristic: Same,526 },527 // Parentheses.528 {529 Name: "empty paren",530 Input: "()",531 WantGrammar: Spec(`""`),532 WantHeuristic: Diff(`"()"`),533 },534 {535 Name: "paren inside contiguous string",536 Input: "foo()bar",537 WantGrammar: Spec(`(concat "foo" "bar")`),538 WantHeuristic: Diff(`"foo()bar"`),539 },540 {541 Name: "paren inside contiguous string",542 Input: "(x and regex(s)?)",543 WantGrammar: Spec(`(and "x" (concat "regex" "s" "?"))`),544 WantHeuristic: Diff(`(and "x" "regex(s)?")`),545 },546 {547 Name: "paren containing whitespace inside contiguous string",548 Input: "foo( )bar",549 WantGrammar: Spec(`(concat "foo" "bar")`),550 WantHeuristic: Diff(`"foo( )bar"`),551 },552 {553 Name: "nested empty paren",554 Input: "(x())",555 WantGrammar: Spec(`"x"`),556 WantHeuristic: Diff(`"(x())"`),557 },558 {559 Name: "interpolated nested empty paren",560 Input: "(()x( )(())())",561 WantGrammar: Spec(`"x"`),562 WantHeuristic: Diff(`"(()x( )(())())"`),563 },564 {565 Name: "empty paren on or",566 Input: "() or ()",567 WantGrammar: Spec(`""`),568 WantHeuristic: Diff(`(or "()" "()")`),569 },570 {571 Name: "empty left paren on or",572 Input: "() or (x)",573 WantGrammar: Spec(`"x"`),574 WantHeuristic: Diff(`(or "()" "(x)")`),575 },576 {577 Name: "complex interpolated nested empty paren",578 Input: "(()x( )(y or () or (f))())",579 WantGrammar: Spec(`(concat "x" (or "y" "f"))`),580 WantHeuristic: Diff(`(concat "()" "x" "()" (or "y" "()" "(f)") "()")`),581 },582 {583 Name: "disable parens as patterns heuristic if containing recognized operator",584 Input: "(() or ())",585 WantGrammar: Spec(`""`),586 WantHeuristic: Diff(`(or "()" "()")`),587 },588 // Escaping.589 {590 Input: `\(\)`,591 WantGrammar: `"\\(\\)"`,592 WantHeuristic: Same,593 },594 {595 Input: `\( \) ()`,596 WantGrammar: Spec(`(concat "\\(" "\\)")`),597 WantHeuristic: Diff(`(concat "\\(" "\\)" "()")`),598 },599 {600 Input: `\ `,601 WantGrammar: `"\\ "`,602 WantHeuristic: Same,603 },604 {605 Input: `\ \ `,606 WantGrammar: Spec(`(concat "\\ " "\\ ")`),607 WantHeuristic: Diff(`(concat "\\ " "\\ ")`),608 },609 // Dangling parentheses heuristic.610 {611 Input: `(`,612 WantGrammar: Spec(`expected operand at 1`),613 WantHeuristic: Diff(`"("`),614 },615 {616 Input: `)(())(`,617 WantGrammar: Spec(`unbalanced expression`),618 WantHeuristic: Diff(`"(())("`),619 },620 {621 Input: `foo( and bar(`,622 WantGrammar: Spec(`expected operand at 5`),623 WantHeuristic: Diff(`(and "foo(" "bar(")`),624 },625 {626 Input: `repo:foo foo( or bar(`,627 WantGrammar: Spec(`expected operand at 14`),628 WantHeuristic: Diff(`(and "repo:foo" (or "foo(" "bar("))`),629 },630 {631 Input: `(a or (b and )) or d)`,632 WantGrammar: Spec(`unbalanced expression`),633 WantHeuristic: Diff(`(or "(a" (and "(b" ")") "d)")`),634 },635 // Quotes and escape sequences.636 {637 Input: `"`,638 WantGrammar: `"\""`,639 WantHeuristic: Same,640 },641 {642 Input: `repo:foo' bar'`,643 WantGrammar: `(and "repo:foo'" "bar'")`,644 WantHeuristic: Same,645 },646 {647 Input: `repo:'foo' 'bar'`,648 WantGrammar: `(and "repo:foo" "bar")`,649 WantHeuristic: Same,650 },651 {652 Input: `repo:"foo" "bar"`,653 WantGrammar: `(and "repo:foo" "bar")`,654 WantHeuristic: Same,655 },656 {657 Input: `repo:"foo bar" "foo bar"`,658 WantGrammar: `(and "repo:foo bar" "foo bar")`,659 WantHeuristic: Same,660 },661 {662 Input: `repo:"fo\"o" "bar"`,663 WantGrammar: Spec(`(and "repo:fo\"o" "bar")`),664 WantHeuristic: Same,665 },666 {667 Input: `repo:foo /b\/ar/`,668 WantGrammar: `(and "repo:foo" "/b\\/ar/")`,669 WantHeuristic: Same,670 },671 {672 Input: `repo:foo /a/file/path`,673 WantGrammar: `(and "repo:foo" "/a/file/path")`,674 WantHeuristic: Same,675 },676 {677 Input: `repo:foo /a/file/path/`,678 WantGrammar: `(and "repo:foo" "/a/file/path/")`,679 WantHeuristic: Same,680 },681 {682 Input: `repo:foo /a/ /another/path/`,683 WantGrammar: `(and "repo:foo" (concat "/a/" "/another/path/"))`,684 WantHeuristic: Same,685 },686 {687 Input: `\t\r\n`,688 WantGrammar: `"\t\r\n"`,689 WantHeuristic: Same,690 },691 {692 Input: `repo:foo\ bar \:\\`,693 WantGrammar: `(and "repo:foo\\ bar" "\\:\\\\")`,694 WantHeuristic: Same,695 },696 }697 for _, tt := range cases {698 t.Run(tt.Name, func(t *testing.T) {699 check := func(result []Node, err error, want string) {700 var resultStr []string701 if err != nil {702 if diff := cmp.Diff(want, err.Error()); diff != "" {703 t.Fatal(diff)704 }705 return706 }707 for _, node := range result {708 resultStr = append(resultStr, node.String())709 }710 got := strings.Join(resultStr, " ")711 if diff := cmp.Diff(want, got); diff != "" {712 t.Error(diff)713 }714 }715 var result []Node716 var err error717 result, err = parseAndOrGrammar(tt.Input) // Parse without heuristic.718 check(result, err, string(tt.WantGrammar))719 result, err = ParseAndOr(tt.Input, SearchTypeRegex)720 if tt.WantHeuristic == Same {721 check(result, err, string(tt.WantGrammar))722 } else {723 check(result, err, string(tt.WantHeuristic))724 }725 })726 }727}728func TestScanDelimited(t *testing.T) {729 type result struct {730 Value string731 Count int732 ErrMsg string733 }734 cases := []struct {735 name string736 input string737 delimiter rune738 want result739 }{740 {741 input: `""`,742 delimiter: '"',743 want: result{Value: "", Count: 2, ErrMsg: ""},744 },745 {746 input: `"a"`,747 delimiter: '"',748 want: result{Value: `a`, Count: 3, ErrMsg: ""},749 },750 {751 input: `"\""`,752 delimiter: '"',753 want: result{Value: `"`, Count: 4, ErrMsg: ""},754 },755 {756 input: `"\\""`,757 delimiter: '"',758 want: result{Value: `\`, Count: 4, ErrMsg: ""},759 },760 {761 input: `"\\\"`,762 delimiter: '"',763 want: result{Value: "", Count: 5, ErrMsg: `unterminated literal: expected "`},764 },765 {766 input: `"\\\""`,767 delimiter: '"',768 want: result{Value: `\"`, Count: 6, ErrMsg: ""},769 },770 {771 input: `"a`,772 delimiter: '"',773 want: result{Value: "", Count: 2, ErrMsg: `unterminated literal: expected "`},774 },775 {776 input: `"\?"`,777 delimiter: '"',778 want: result{Value: "", Count: 3, ErrMsg: `unrecognized escape sequence`},779 },780 {781 name: "panic",782 input: `a"`,783 delimiter: '"',784 want: result{},785 },786 {787 input: `/\//`,788 delimiter: '/',789 want: result{Value: "/", Count: 4, ErrMsg: ""},790 },791 }792 for _, tt := range cases {793 if tt.name == "panic" {794 defer func() {795 if r := recover(); r == nil {796 t.Errorf("expected panic for ScanDelimited")797 }798 }()799 _, _, _ = ScanDelimited([]byte(tt.input), tt.delimiter)800 }801 t.Run(tt.name, func(t *testing.T) {802 value, count, err := ScanDelimited([]byte(tt.input), tt.delimiter)803 var errMsg string804 if err != nil {805 errMsg = err.Error()806 }807 got := result{value, count, errMsg}808 if diff := cmp.Diff(tt.want, got); diff != "" {809 t.Error(diff)810 }811 })812 }813}814func TestMergePatterns(t *testing.T) {815 cases := []struct {816 input string817 want string818 }{819 {820 input: "foo()bar",821 want: `{"start":{"line":0,"column":0},"end":{"line":0,"column":8}}`,822 },823 {824 input: "()bar",825 want: `{"start":{"line":0,"column":0},"end":{"line":0,"column":5}}`,826 },827 }828 for _, tt := range cases {829 t.Run("merge pattern", func(t *testing.T) {830 p := &parser{buf: []byte(tt.input), heuristics: parensAsPatterns}831 nodes, err := p.parseLeavesRegexp()832 got := nodes[0].(Pattern).Annotation.Range.String()833 if err != nil {834 t.Error(err)835 }836 if diff := cmp.Diff(tt.want, got); diff != "" {837 t.Error(diff)838 }839 })840 }841}...
systemroleassignments_test.go
Source:systemroleassignments_test.go
1// Copyright (c) Microsoft Corporation. All rights reserved.2// Licensed under the MIT license.3package engine4import (5 "testing"6 "github.com/Azure/aks-engine/pkg/api"7 "github.com/google/go-cmp/cmp"8 "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-09-01-preview/authorization"9 "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"10 "github.com/Azure/go-autorest/autorest/to"11)12func TestCreateVmasRoleAssignment(t *testing.T) {13 actual := createVMASRoleAssignment()14 expected := SystemRoleAssignmentARM{15 ARMResource: ARMResource{16 APIVersion: "[variables('apiVersionAuthorizationSystem')]",17 DependsOn: []string{18 "[concat('Microsoft.Compute/virtualMachines/', variables('masterVMNamePrefix'), copyIndex(variables('masterOffset')))]",19 },20 Copy: map[string]string{21 "count": "[sub(variables('masterCount'), variables('masterOffset'))]",22 "name": "vmLoopNode",23 },24 },25 RoleAssignment: authorization.RoleAssignment{26 Name: to.StringPtr("[guid(concat('Microsoft.Compute/virtualMachines/', variables('masterVMNamePrefix'), copyIndex(variables('masterOffset')), 'vmidentity'))]"),27 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),28 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{29 RoleDefinitionID: to.StringPtr("[variables('contributorRoleDefinitionId')]"),30 PrincipalID: to.StringPtr("[reference(concat('Microsoft.Compute/virtualMachines/', variables('masterVMNamePrefix'), copyIndex(variables('masterOffset'))), '2017-03-30', 'Full').identity.principalId]"),31 PrincipalType: authorization.ServicePrincipal,32 },33 },34 }35 diff := cmp.Diff(actual, expected)36 if diff != "" {37 t.Errorf("unexpected diff while comparing: %s", diff)38 }39}40func TestCreateAgentVmasSysRoleAssignment(t *testing.T) {41 profile := &api.AgentPoolProfile{42 Name: "fooprofile",43 }44 actual := createAgentVMASSysRoleAssignment(profile)45 expected := SystemRoleAssignmentARM{46 ARMResource: ARMResource{47 APIVersion: "[variables('apiVersionAuthorizationSystem')]",48 DependsOn: []string{49 "[concat('Microsoft.Compute/virtualMachines/', variables('fooprofileVMNamePrefix'), copyIndex(variables('fooprofileOffset')))]",50 },51 Copy: map[string]string{52 "count": "[sub(variables('fooprofileCount'), variables('fooprofileOffset'))]",53 "name": "vmLoopNode",54 },55 },56 RoleAssignment: authorization.RoleAssignment{57 Name: to.StringPtr("[guid(concat('Microsoft.Compute/virtualMachines/', variables('fooprofileVMNamePrefix'), copyIndex(variables('fooprofileOffset')), 'vmidentity'))]"),58 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),59 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{60 RoleDefinitionID: to.StringPtr("[variables('readerRoleDefinitionId')]"),61 PrincipalID: to.StringPtr("[reference(concat('Microsoft.Compute/virtualMachines/', variables('fooprofileVMNamePrefix'), copyIndex(variables('fooprofileOffset'))), '2017-03-30', 'Full').identity.principalId]"),62 PrincipalType: authorization.ServicePrincipal,63 },64 },65 }66 diff := cmp.Diff(actual, expected)67 if diff != "" {68 t.Errorf("unexpected diff while comparing: %s", diff)69 }70}71func TestCreateAgentVmssSysRoleAssignment(t *testing.T) {72 profile := &api.AgentPoolProfile{73 Name: "fooprofile",74 }75 actual := createAgentVMSSSysRoleAssignment(profile)76 expected := SystemRoleAssignmentARM{77 ARMResource: ARMResource{78 APIVersion: "[variables('apiVersionAuthorizationSystem')]",79 DependsOn: []string{80 "[concat('Microsoft.Compute/virtualMachineScaleSets/', variables('fooprofileVMNamePrefix'))]",81 },82 },83 RoleAssignment: authorization.RoleAssignment{84 Name: to.StringPtr("[guid(concat('Microsoft.Compute/virtualMachineScaleSets/', variables('fooprofileVMNamePrefix'), 'vmidentity'))]"),85 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),86 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{87 RoleDefinitionID: to.StringPtr("[variables('readerRoleDefinitionId')]"),88 PrincipalID: to.StringPtr("[reference(concat('Microsoft.Compute/virtualMachineScaleSets/', variables('fooprofileVMNamePrefix')), '2017-03-30', 'Full').identity.principalId]"),89 PrincipalType: authorization.ServicePrincipal,90 },91 },92 }93 diff := cmp.Diff(actual, expected)94 if diff != "" {95 t.Errorf("unexpected diff while comparing: %s", diff)96 }97}98func TestCreateKubernetesMasterRoleAssignmentForAgentPools(t *testing.T) {99 masterProfile := &api.MasterProfile{100 Count: 2,101 }102 // Two pools sharing a common VNET103 agentProfile1 := &api.AgentPoolProfile{104 Name: "agentProfile1",105 VnetSubnetID: "/subscriptions/SUB_ID/resourceGroups/RG_NAME/providers/Microsoft.Network/virtualNetworks/VNET_NAME/subnets/SUBNET1_NAME",106 }107 agentProfile2 := &api.AgentPoolProfile{108 Name: "agentProfile2",109 VnetSubnetID: "/subscriptions/SUB_ID/resourceGroups/RG_NAME/providers/Microsoft.Network/virtualNetworks/VNET_NAME/subnets/SUBNET2_NAME",110 }111 actual := createKubernetesMasterRoleAssignmentForAgentPools(masterProfile, []*api.AgentPoolProfile{agentProfile1, agentProfile2})112 expected := []DeploymentWithResourceGroupARM{113 {114 DeploymentARMResource: DeploymentARMResource{115 APIVersion: "2017-05-10",116 DependsOn: []string{117 "[concat(variables('masterVMNamePrefix'), 0)]",118 "[concat(variables('masterVMNamePrefix'), 1)]",119 },120 },121 ResourceGroup: to.StringPtr("[variables('agentProfile1SubnetResourceGroup')]"),122 DeploymentExtended: resources.DeploymentExtended{123 Name: to.StringPtr("[concat('masterMsiRoleAssignment-', variables('agentProfile1VMNamePrefix'))]"),124 Type: to.StringPtr("Microsoft.Resources/deployments"),125 Properties: &resources.DeploymentPropertiesExtended{126 Mode: "Incremental",127 Template: map[string]interface{}{128 "resources": []interface{}{129 SystemRoleAssignmentARM{130 ARMResource: ARMResource{131 APIVersion: "[variables('apiVersionAuthorizationSystem')]",132 },133 RoleAssignment: authorization.RoleAssignment{134 Name: to.StringPtr("[concat(variables('agentProfile1Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId)))]"),135 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),136 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{137 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),138 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId]"),139 },140 },141 },142 SystemRoleAssignmentARM{143 ARMResource: ARMResource{144 APIVersion: "[variables('apiVersionAuthorizationSystem')]",145 },146 RoleAssignment: authorization.RoleAssignment{147 Name: to.StringPtr("[concat(variables('agentProfile1Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId)))]"),148 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),149 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{150 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),151 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId]"),152 },153 },154 },155 },156 "contentVersion": "1.0.0.0",157 "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",158 },159 },160 },161 },162 }163 diff := cmp.Diff(actual, expected)164 if diff != "" {165 t.Errorf("unexpected diff while comparing: %s", diff)166 }167 // Two pools with discrete VNETs168 agentProfile1 = &api.AgentPoolProfile{169 Name: "agentProfile1",170 VnetSubnetID: "/subscriptions/SUB_ID/resourceGroups/RG_NAME/providers/Microsoft.Network/virtualNetworks/VNET1_NAME/subnets/SUBNET1_NAME",171 }172 agentProfile2 = &api.AgentPoolProfile{173 Name: "agentProfile2",174 VnetSubnetID: "/subscriptions/SUB_ID/resourceGroups/RG_NAME/providers/Microsoft.Network/virtualNetworks/VNET2_NAME/subnets/SUBNET2_NAME",175 }176 actual = createKubernetesMasterRoleAssignmentForAgentPools(masterProfile, []*api.AgentPoolProfile{agentProfile1, agentProfile2})177 expected = []DeploymentWithResourceGroupARM{178 {179 DeploymentARMResource: DeploymentARMResource{180 APIVersion: "2017-05-10",181 DependsOn: []string{182 "[concat(variables('masterVMNamePrefix'), 0)]",183 "[concat(variables('masterVMNamePrefix'), 1)]",184 },185 },186 ResourceGroup: to.StringPtr("[variables('agentProfile1SubnetResourceGroup')]"),187 DeploymentExtended: resources.DeploymentExtended{188 Name: to.StringPtr("[concat('masterMsiRoleAssignment-', variables('agentProfile1VMNamePrefix'))]"),189 Type: to.StringPtr("Microsoft.Resources/deployments"),190 Properties: &resources.DeploymentPropertiesExtended{191 Mode: "Incremental",192 Template: map[string]interface{}{193 "resources": []interface{}{194 SystemRoleAssignmentARM{195 ARMResource: ARMResource{196 APIVersion: "[variables('apiVersionAuthorizationSystem')]",197 },198 RoleAssignment: authorization.RoleAssignment{199 Name: to.StringPtr("[concat(variables('agentProfile1Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId)))]"),200 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),201 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{202 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),203 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId]"),204 },205 },206 },207 SystemRoleAssignmentARM{208 ARMResource: ARMResource{209 APIVersion: "[variables('apiVersionAuthorizationSystem')]",210 },211 RoleAssignment: authorization.RoleAssignment{212 Name: to.StringPtr("[concat(variables('agentProfile1Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId)))]"),213 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),214 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{215 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),216 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId]"),217 },218 },219 },220 },221 "contentVersion": "1.0.0.0",222 "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",223 },224 },225 },226 },227 {228 DeploymentARMResource: DeploymentARMResource{229 APIVersion: "2017-05-10",230 DependsOn: []string{231 "[concat(variables('masterVMNamePrefix'), 0)]",232 "[concat(variables('masterVMNamePrefix'), 1)]",233 },234 },235 ResourceGroup: to.StringPtr("[variables('agentProfile2SubnetResourceGroup')]"),236 DeploymentExtended: resources.DeploymentExtended{237 Name: to.StringPtr("[concat('masterMsiRoleAssignment-', variables('agentProfile2VMNamePrefix'))]"),238 Type: to.StringPtr("Microsoft.Resources/deployments"),239 Properties: &resources.DeploymentPropertiesExtended{240 Mode: "Incremental",241 Template: map[string]interface{}{242 "resources": []interface{}{243 SystemRoleAssignmentARM{244 ARMResource: ARMResource{245 APIVersion: "[variables('apiVersionAuthorizationSystem')]",246 },247 RoleAssignment: authorization.RoleAssignment{248 Name: to.StringPtr("[concat(variables('agentProfile2Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId)))]"),249 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),250 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{251 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),252 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 0)), '2017-03-30', 'Full').identity.principalId]"),253 },254 },255 },256 SystemRoleAssignmentARM{257 ARMResource: ARMResource{258 APIVersion: "[variables('apiVersionAuthorizationSystem')]",259 },260 RoleAssignment: authorization.RoleAssignment{261 Name: to.StringPtr("[concat(variables('agentProfile2Vnet'), '/Microsoft.Authorization/', guid(uniqueString(reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId)))]"),262 Type: to.StringPtr("Microsoft.Network/virtualNetworks/providers/roleAssignments"),263 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{264 RoleDefinitionID: to.StringPtr("[variables('networkContributorRoleDefinitionId')]"),265 PrincipalID: to.StringPtr("[reference(resourceId(resourceGroup().name, 'Microsoft.Compute/virtualMachines', concat(variables('masterVMNamePrefix'), 1)), '2017-03-30', 'Full').identity.principalId]"),266 },267 },268 },269 },270 "contentVersion": "1.0.0.0",271 "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",272 },273 },274 },275 },276 }277 diff = cmp.Diff(actual, expected)278 if diff != "" {279 t.Errorf("unexpected diff while comparing: %s", diff)280 }281}...
roleassignments_test.go
Source:roleassignments_test.go
1// Copyright (c) Microsoft Corporation. All rights reserved.2// Licensed under the MIT license.3package engine4import (5 "testing"6 "github.com/Azure/aks-engine/pkg/api"7 "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-09-01-preview/authorization"8 "github.com/Azure/go-autorest/autorest/to"9 "github.com/google/go-cmp/cmp"10)11func TestCreateMSIRoleAssignment(t *testing.T) {12 // Test create Contributor role assignment13 actual := createMSIRoleAssignment(IdentityContributorRole)14 expected := RoleAssignmentARM{15 ARMResource: ARMResource{16 APIVersion: "[variables('apiVersionAuthorizationUser')]",17 DependsOn: []string{18 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('userAssignedID'))]",19 },20 },21 RoleAssignment: authorization.RoleAssignment{22 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),23 Name: to.StringPtr("[guid(concat(variables('userAssignedID'), 'roleAssignment', resourceGroup().id))]"),24 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{25 RoleDefinitionID: to.StringPtr("[variables('contributorRoleDefinitionId')]"),26 PrincipalID: to.StringPtr("[reference(concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('userAssignedID'))).principalId]"),27 PrincipalType: authorization.ServicePrincipal,28 Scope: to.StringPtr("[resourceGroup().id]"),29 },30 },31 }32 diff := cmp.Diff(actual, expected)33 if diff != "" {34 t.Errorf("unexpected diff while comparing: %s", diff)35 }36 // Test create Reader role assignment37 actual = createMSIRoleAssignment(IdentityReaderRole)38 expected = RoleAssignmentARM{39 ARMResource: ARMResource{40 APIVersion: "[variables('apiVersionAuthorizationUser')]",41 DependsOn: []string{42 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('userAssignedID'))]",43 },44 },45 RoleAssignment: authorization.RoleAssignment{46 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),47 Name: to.StringPtr("[guid(concat(variables('userAssignedID'), 'roleAssignment', resourceGroup().id))]"),48 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{49 RoleDefinitionID: to.StringPtr("[variables('readerRoleDefinitionId')]"),50 PrincipalID: to.StringPtr("[reference(concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('userAssignedID'))).principalId]"),51 PrincipalType: authorization.ServicePrincipal,52 Scope: to.StringPtr("[resourceGroup().id]"),53 },54 },55 }56 diff = cmp.Diff(actual, expected)57 if diff != "" {58 t.Errorf("unexpected diff while comparing: %s", diff)59 }60}61func TestCreateKubernetesSpAppGIdentityOperatorAccessRoleAssignment(t *testing.T) {62 // using service principal63 cs := &api.ContainerService{64 Properties: &api.Properties{65 ServicePrincipalProfile: &api.ServicePrincipalProfile{66 ObjectID: "xxxx",67 },68 },69 }70 actual := createKubernetesSpAppGIdentityOperatorAccessRoleAssignment(cs.Properties)71 expected := RoleAssignmentARM{72 ARMResource: ARMResource{73 APIVersion: "[variables('apiVersionAuthorizationSystem')]",74 DependsOn: []string{75 "[concat('Microsoft.Network/applicationgateways/', variables('appGwName'))]",76 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('appGwICIdentityName'))]",77 },78 },79 RoleAssignment: authorization.RoleAssignment{80 Type: to.StringPtr("Microsoft.ManagedIdentity/userAssignedIdentities/providers/roleAssignments"),81 Name: to.StringPtr("[concat(variables('appGwICIdentityName'), '/Microsoft.Authorization/', guid(resourceGroup().id, 'aksidentityaccess'))]"),82 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{83 RoleDefinitionID: to.StringPtr(string(IdentityManagedIdentityOperatorRole)),84 PrincipalID: to.StringPtr("xxxx"),85 PrincipalType: authorization.ServicePrincipal,86 Scope: to.StringPtr("[variables('appGwICIdentityId')]"),87 },88 },89 }90 diff := cmp.Diff(actual, expected)91 if diff != "" {92 t.Errorf("unexpected diff while comparing: %s", diff)93 }94 // using managed identity95 cs = &api.ContainerService{96 Properties: &api.Properties{97 OrchestratorProfile: &api.OrchestratorProfile{98 KubernetesConfig: &api.KubernetesConfig{99 UseManagedIdentity: true,100 },101 },102 },103 }104 actual = createKubernetesSpAppGIdentityOperatorAccessRoleAssignment(cs.Properties)105 expected = RoleAssignmentARM{106 ARMResource: ARMResource{107 APIVersion: "[variables('apiVersionAuthorizationSystem')]",108 DependsOn: []string{109 "[concat('Microsoft.Network/applicationgateways/', variables('appGwName'))]",110 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('appGwICIdentityName'))]",111 },112 },113 RoleAssignment: authorization.RoleAssignment{114 Type: to.StringPtr("Microsoft.ManagedIdentity/userAssignedIdentities/providers/roleAssignments"),115 Name: to.StringPtr("[concat(variables('appGwICIdentityName'), '/Microsoft.Authorization/', guid(resourceGroup().id, 'aksidentityaccess'))]"),116 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{117 RoleDefinitionID: to.StringPtr(string(IdentityManagedIdentityOperatorRole)),118 PrincipalID: to.StringPtr("[reference(concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('userAssignedID'))).principalId]"),119 PrincipalType: authorization.ServicePrincipal,120 Scope: to.StringPtr("[variables('appGwICIdentityId')]"),121 },122 },123 }124 diff = cmp.Diff(actual, expected)125 if diff != "" {126 t.Errorf("unexpected diff while comparing: %s", diff)127 }128}129func TestCreateAppGwIdentityResourceGroupReadSysRoleAssignment(t *testing.T) {130 actual := createAppGwIdentityResourceGroupReadSysRoleAssignment()131 expected := RoleAssignmentARM{132 ARMResource: ARMResource{133 APIVersion: "[variables('apiVersionAuthorizationSystem')]",134 DependsOn: []string{135 "[concat('Microsoft.Network/applicationgateways/', variables('appGwName'))]",136 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('appGwICIdentityName'))]",137 },138 },139 RoleAssignment: authorization.RoleAssignment{140 Type: to.StringPtr("Microsoft.Authorization/roleAssignments"),141 Name: to.StringPtr("[guid(resourceGroup().id, 'identityrgaccess')]"),142 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{143 RoleDefinitionID: to.StringPtr(string(IdentityReaderRole)),144 PrincipalID: to.StringPtr("[reference(variables('appGwICIdentityId'), variables('apiVersionManagedIdentity')).principalId]"),145 Scope: to.StringPtr("[resourceGroup().id]"),146 },147 },148 }149 diff := cmp.Diff(actual, expected)150 if diff != "" {151 t.Errorf("unexpected diff while comparing: %s", diff)152 }153}154func TestCreateAppGwIdentityApplicationGatewayWriteSysRoleAssignment(t *testing.T) {155 actual := createAppGwIdentityApplicationGatewayWriteSysRoleAssignment()156 expected := RoleAssignmentARM{157 ARMResource: ARMResource{158 APIVersion: "[variables('apiVersionAuthorizationSystem')]",159 DependsOn: []string{160 "[concat('Microsoft.Network/applicationgateways/', variables('appGwName'))]",161 "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', variables('appGwICIdentityName'))]",162 },163 },164 RoleAssignment: authorization.RoleAssignment{165 Type: to.StringPtr("Microsoft.Network/applicationgateways/providers/roleAssignments"),166 Name: to.StringPtr("[concat(variables('appGwName'), '/Microsoft.Authorization/', guid(resourceGroup().id, 'identityappgwaccess'))]"),167 RoleAssignmentPropertiesWithScope: &authorization.RoleAssignmentPropertiesWithScope{168 RoleDefinitionID: to.StringPtr(string(IdentityContributorRole)),169 PrincipalID: to.StringPtr("[reference(variables('appGwICIdentityId'), variables('apiVersionManagedIdentity')).principalId]"),170 Scope: to.StringPtr("[variables('appGwId')]"),171 },172 },173 }174 diff := cmp.Diff(actual, expected)175 if diff != "" {176 t.Errorf("unexpected diff while comparing: %s", diff)177 }178}...
Concat
Using AI Code Generation
1import (2func main() {3 s3 := diff.Concat(s1, s2)4 fmt.Println(s3)5}6import (7func Concat(s1, s2 string) string {8 return strings.Join([]string{s1, s2}, " ")9}10import (11func Concat(s1, s2 string) string {12 return strings.Join([]string{s1, s2}, " ")13}14func Concat(s1, s2 string) string {15 return strings.Join([]string{s1, s2}, " ")16}
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(Concat(str1, str2))4}5func Concat(str1, str2 string) string {6}
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.Concat("Hello", "World"))4}5import (6func main() {7 fmt.Println(stringutil.Reverse("Hello"))8}9import (10func main() {11 fmt.Println(stringutil.Reverse("Hello"))12}13import (14func main() {15 fmt.Println(stringutil.Reverse("Hello"))16}17import (18func main() {19 fmt.Println(stringutil.Reverse("Hello"))20}21import (22func main() {23 fmt.Println(stringutil.Reverse("Hello"))24}25import (26func main() {27 fmt.Println(stringutil.Reverse("Hello"))28}29import (30func main() {31 fmt.Println(stringutil.Reverse("Hello"))32}33import (34func main() {35 fmt.Println(stringutil.Reverse("Hello"))36}37import (38func main() {39 fmt.Println(stringutil.Reverse("Hello"))40}41import (42func main() {43 fmt.Println(stringutil.Reverse("Hello"))44}45import (
Concat
Using AI Code Generation
1import (2type Config struct {3}4func main() {5 k := koanf.New(".")6 if err := k.Load(file.Provider("config.yaml"), yaml.Parser()); err != nil {7 panic(err)8 }9 if err := k.Load(file.Provider("config2.yaml"), yaml.Parser()); err != nil {10 panic(err)11 }12 if err := k.Load(file.Provider("config3.yaml"), yaml.Parser()); err != nil {13 panic(err)14 }15 if err := k.Load(file.Provider("config4.yaml"), yaml.Parser()); err != nil {16 panic(err)17 }18 if err := k.Load(file.Provider("config5.yaml"), yaml.Parser()); err != nil {19 panic(err)20 }21 if err := k.Load(file.Provider("config6.yaml"), yaml.Parser()); err != nil {22 panic(err)23 }24 if err := k.Load(file.Provider("config7.yaml"), yaml.Parser()); err != nil {25 panic(err)26 }27 if err := k.Load(file.Provider("config8.yaml"), yaml.Parser()); err != nil {28 panic(err)29 }
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))4}5import (6func main() {7 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))8}9import (10func main() {11 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))12}13import (14func main() {15 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))16}17import (18func main() {19 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))20}21import (22func main() {23 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))24}25import (26func main() {27 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))28}29import (30func main() {31 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))32}33import (34func main() {35 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))36}37import (38func main() {39 fmt.Println(strings.Join([]string{"Hello", "World"}, " "))40}
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.Concat("Hello", "World"))4}5import (6func main() {7 fmt.Println(stringutil.Concat("Hello", "World"))8}
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(a + b)4}5import (6func main() {7 fmt.Println(a, b)8}
Concat
Using AI Code Generation
1func main(){2 str3 := diff.Concat(str1, str2)3 fmt.Println(str3)4}5func Concat(str1, str2 string) string {6}
Concat
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.Concat("Hello", "World"))4}5func Concat(s1, s2 string) string {6}
Concat
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 s := diff.Concat("Hello", "Playground")5 fmt.Println(s)6}7import "fmt"8import "github.com/GoLang/concat"9func main() {10 fmt.Println("Hello, playground")11 s := diff.Concat("Hello", "Playground")12 fmt.Println(s)13}14import "fmt"15import "github.com/GoLang/concat/diff"16func main() {17 fmt.Println("Hello, playground")18 s := diff.Concat("Hello", "Playground")19 fmt.Println(s)20}
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!!