How to use extract method of main Package

Best Syzkaller code snippet using main.extract

declaration_extractor_test.go

Source:declaration_extractor_test.go Github

copy

Full Screen

1package declaration_extractor_test2import (3 "bytes"4 "errors"5 "os"6 "path/filepath"7 "runtime"8 "testing"9 "github.com/skycoin/cx/cmd/declaration_extractor"10)11//Sets the offset for windows or other os12func setOffset(offset int, lineNumber int) int {13 //Input offset is the offset for linux/mac14 var newOffset int = offset15 runtimeOS := runtime.GOOS16 //Determines runtime os and sets the offset accordingly17 if runtimeOS == "windows" {18 newOffset += lineNumber - 119 }20 return newOffset21}22func TestDeclarationExtractor_ReplaceCommentsWithWhitespaces(t *testing.T) {23 tests := []struct {24 scenario string25 testDir string26 wantCommentReplaced string27 }{28 {29 scenario: "Has comments",30 testDir: "./test_files/ReplaceCommentsWithWhitespaces/HasComments.cx",31 wantCommentReplaced: "./test_files/ReplaceCommentsWithWhitespaces/HasCommentsResult.cx",32 },33 }34 for _, tc := range tests {35 t.Run(tc.scenario, func(t *testing.T) {36 srcBytes, err := os.ReadFile(tc.testDir)37 if err != nil {38 t.Fatal(err)39 }40 wantBytes, err := os.ReadFile(tc.wantCommentReplaced)41 if err != nil {42 t.Fatal(err)43 }44 commentReplaced := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)45 if len(srcBytes) != len(commentReplaced) {46 t.Errorf("Length not the same: orginal %vbytes, replaced %vbytes", len(srcBytes), len(commentReplaced))47 }48 srcLines := bytes.Count(srcBytes, []byte("\n")) + 149 newLines := bytes.Count(commentReplaced, []byte("\n")) + 150 if srcLines != newLines {51 t.Errorf("Lines not equal: original %vlines, new %vlines", srcLines, newLines)52 }53 if string(commentReplaced) != string(wantBytes) {54 t.Errorf("want comments replaced\n%v\ngot\n%v", string(wantBytes), string(commentReplaced))55 file, err := os.Create("gotCommentsReplaced.cx")56 if err != nil {57 t.Fatal(err)58 }59 file.Write(commentReplaced)60 }61 })62 }63}64func TestDeclarationExtractor_ReplaceStringContentsWithWhitespaces(t *testing.T) {65 tests := []struct {66 scenario string67 testDir string68 wantStringContentsReplaced string69 wantErr error70 }{71 {72 scenario: "Has String",73 testDir: "./test_files/ReplaceStringContentsWithWhitespaces/HasString.cx",74 wantStringContentsReplaced: "./test_files/ReplaceStringContentsWithWhitespaces/HasString.cxStringContentsReplaced.cx",75 wantErr: nil,76 },77 {78 scenario: "Syntax Error",79 testDir: "./test_files/ReplaceStringContentsWithWhitespaces/SyntaxError.cx",80 wantStringContentsReplaced: "./test_files/ReplaceStringContentsWithWhitespaces/SyntaxError.cxStringContentsReplaced.cx",81 wantErr: errors.New("9: syntax error: quote not terminated"),82 },83 }84 for _, tc := range tests {85 t.Run(tc.scenario, func(t *testing.T) {86 srcBytes, err := os.ReadFile(tc.testDir)87 if err != nil {88 t.Fatal(err)89 }90 wantBytes, err := os.ReadFile(tc.wantStringContentsReplaced)91 if err != nil {92 t.Fatal(err)93 }94 stringContentsReplaced, gotErr := declaration_extractor.ReplaceStringContentsWithWhitespaces(srcBytes)95 if len(srcBytes) != len(stringContentsReplaced) {96 t.Errorf("Length not the same: orginal %vbytes, replaced %vbytes", len(srcBytes), len(stringContentsReplaced))97 }98 srcLines := bytes.Count(srcBytes, []byte("\n")) + 199 newLines := bytes.Count(stringContentsReplaced, []byte("\n")) + 1100 if srcLines != newLines {101 t.Errorf("Lines not equal: original %vlines, new %vlines", srcLines, newLines)102 }103 if string(stringContentsReplaced) != string(wantBytes) {104 t.Errorf("want string contents replaced\n%v\ngot\n%v", string(wantBytes), string(stringContentsReplaced))105 file, err := os.Create(tc.testDir + "gotStringContentsReplaced.cx")106 if err != nil {107 t.Fatal(err)108 }109 file.Write(stringContentsReplaced)110 }111 if (gotErr != nil && tc.wantErr == nil) ||112 (gotErr == nil && tc.wantErr != nil) {113 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)114 }115 if gotErr != nil && tc.wantErr != nil {116 if gotErr.Error() != tc.wantErr.Error() {117 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)118 }119 }120 })121 }122}123func TestDeclarationExtractor_ExtractGlobals(t *testing.T) {124 tests := []struct {125 scenario string126 testDir string127 wantGlobals []declaration_extractor.GlobalDeclaration128 wantErr error129 }{130 {131 scenario: "Has Globals",132 testDir: "./test_files/ExtractGlobals/HasGlobals.cx",133 wantGlobals: []declaration_extractor.GlobalDeclaration{134 {135 PackageID: "main",136 FileID: "./test_files/ExtractGlobals/HasGlobals.cx",137 StartOffset: 222,138 Length: 30,139 LineNumber: 15,140 GlobalVariableName: "fooV",141 },142 {143 PackageID: "main",144 FileID: "./test_files/ExtractGlobals/HasGlobals.cx",145 StartOffset: 253,146 Length: 16,147 LineNumber: 16,148 GlobalVariableName: "fooA",149 },150 {151 PackageID: "main",152 FileID: "./test_files/ExtractGlobals/HasGlobals.cx",153 StartOffset: 270,154 Length: 12,155 LineNumber: 17,156 GlobalVariableName: "fooR",157 },158 },159 wantErr: nil,160 },161 {162 scenario: "Has Globals 2",163 testDir: "./test_files/ExtractGlobals/HasGlobals2.cx",164 wantGlobals: []declaration_extractor.GlobalDeclaration{165 {166 PackageID: "main",167 FileID: "./test_files/ExtractGlobals/HasGlobals2.cx",168 StartOffset: 153,169 Length: 56,170 LineNumber: 12,171 GlobalVariableName: "fooV",172 },173 },174 wantErr: nil,175 },176 {177 scenario: "Package Error",178 testDir: "./test_files/ExtractGlobals/PackageError.cx",179 wantGlobals: []declaration_extractor.GlobalDeclaration{},180 wantErr: errors.New("PackageError.cx:10: syntax error: package declaration"),181 },182 {183 scenario: "Syntax Error",184 testDir: "./test_files/ExtractGlobals/SyntaxError.cx",185 wantGlobals: []declaration_extractor.GlobalDeclaration{186 {187 PackageID: "main",188 FileID: "./test_files/ExtractGlobals/SyntaxError.cx",189 StartOffset: 153,190 Length: 56,191 LineNumber: 12,192 GlobalVariableName: "fooV",193 },194 },195 wantErr: errors.New("SyntaxError.cx:23: syntax error: global declaration"),196 },197 }198 for _, tc := range tests {199 t.Run(tc.scenario, func(t *testing.T) {200 srcBytes, err := os.ReadFile(tc.testDir)201 if err != nil {202 t.Fatal(err)203 }204 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)205 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)206 if err != nil {207 t.Fatal(filepath.Base(tc.testDir), err)208 }209 gotGlobals, gotErr := declaration_extractor.ExtractGlobals(ReplaceStringContentsWithWhitespaces, tc.testDir)210 for _, wantGlobal := range tc.wantGlobals {211 wantGlobal.StartOffset = setOffset(wantGlobal.StartOffset, wantGlobal.LineNumber)212 var match bool = false213 var gotGlobalF declaration_extractor.GlobalDeclaration214 for _, gotGlobal := range gotGlobals {215 if gotGlobal.GlobalVariableName == wantGlobal.GlobalVariableName {216 if gotGlobal == wantGlobal {217 match = true218 }219 gotGlobalF = gotGlobal220 break221 }222 }223 if !match {224 t.Errorf("want global %v, got %v", wantGlobal, gotGlobalF)225 }226 }227 if (gotErr != nil && tc.wantErr == nil) ||228 (gotErr == nil && tc.wantErr != nil) {229 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)230 }231 if gotErr != nil && tc.wantErr != nil {232 if gotErr.Error() != tc.wantErr.Error() {233 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)234 }235 }236 })237 }238}239func TestDeclarationExtractor_ExtractEnums(t *testing.T) {240 tests := []struct {241 scenario string242 testDir string243 wantEnums []declaration_extractor.EnumDeclaration244 wantErr error245 }{246 {247 scenario: "Has Enums",248 testDir: "./test_files/ExtractEnums/HasEnums.cx",249 wantEnums: []declaration_extractor.EnumDeclaration{250 {251 PackageID: "main",252 FileID: "./test_files/ExtractEnums/HasEnums.cx",253 StartOffset: 26,254 Length: 17,255 LineNumber: 4,256 Type: "int",257 Value: 0,258 EnumName: "Summer",259 },260 {261 PackageID: "main",262 FileID: "./test_files/ExtractEnums/HasEnums.cx",263 StartOffset: 45,264 Length: 6,265 LineNumber: 5,266 Type: "int",267 Value: 1,268 EnumName: "Autumn",269 },270 {271 PackageID: "main",272 FileID: "./test_files/ExtractEnums/HasEnums.cx",273 StartOffset: 53,274 Length: 6,275 LineNumber: 6,276 Type: "int",277 Value: 2,278 EnumName: "Winter",279 },280 {281 PackageID: "main",282 FileID: "./test_files/ExtractEnums/HasEnums.cx",283 StartOffset: 61,284 Length: 6,285 LineNumber: 7,286 Type: "int",287 Value: 3,288 EnumName: "Spring",289 },290 {291 PackageID: "main",292 FileID: "./test_files/ExtractEnums/HasEnums.cx",293 StartOffset: 83,294 Length: 11,295 LineNumber: 11,296 Type: "",297 Value: 0,298 EnumName: "Apples",299 },300 {301 PackageID: "main",302 FileID: "./test_files/ExtractEnums/HasEnums.cx",303 StartOffset: 99,304 Length: 11,305 LineNumber: 12,306 Type: "",307 Value: 1,308 EnumName: "Oranges",309 },310 },311 },312 {313 scenario: "Package Error",314 testDir: "./test_files/ExtractEnums/PackageError.cx",315 wantEnums: []declaration_extractor.EnumDeclaration{},316 wantErr: errors.New("PackageError.cx:1: syntax error: package declaration"),317 },318 {319 scenario: "Syntax Error",320 testDir: "./test_files/ExtractEnums/SyntaxError.cx",321 wantEnums: []declaration_extractor.EnumDeclaration{322 {323 PackageID: "main",324 FileID: "./test_files/ExtractEnums/SyntaxError.cx",325 StartOffset: 26,326 Length: 17,327 LineNumber: 4,328 Type: "int",329 Value: 0,330 EnumName: "Summer",331 },332 {333 PackageID: "main",334 FileID: "./test_files/ExtractEnums/SyntaxError.cx",335 StartOffset: 45,336 Length: 6,337 LineNumber: 5,338 Type: "int",339 Value: 1,340 EnumName: "Autumn",341 },342 {343 PackageID: "main",344 FileID: "./test_files/ExtractEnums/SyntaxError.cx",345 StartOffset: 53,346 Length: 6,347 LineNumber: 6,348 Type: "int",349 Value: 2,350 EnumName: "Winter",351 },352 {353 PackageID: "main",354 FileID: "./test_files/ExtractEnums/SyntaxError.cx",355 StartOffset: 61,356 Length: 6,357 LineNumber: 7,358 Type: "int",359 Value: 3,360 EnumName: "Spring",361 },362 {363 PackageID: "main",364 FileID: "./test_files/ExtractEnums/SyntaxError.cx",365 StartOffset: 83,366 Length: 11,367 LineNumber: 11,368 Type: "",369 Value: 0,370 EnumName: "Apples",371 },372 {373 PackageID: "main",374 FileID: "./test_files/ExtractEnums/SyntaxError.cx",375 StartOffset: 99,376 Length: 11,377 LineNumber: 12,378 Type: "",379 Value: 1,380 EnumName: "Oranges",381 },382 },383 wantErr: errors.New("SyntaxError.cx:13: syntax error: enum declaration"),384 },385 }386 for _, tc := range tests {387 t.Run(tc.scenario, func(t *testing.T) {388 srcBytes, err := os.ReadFile(tc.testDir)389 if err != nil {390 t.Fatal(err)391 }392 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)393 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)394 if err != nil {395 t.Fatal(filepath.Base(tc.testDir), err)396 }397 gotEnums, gotErr := declaration_extractor.ExtractEnums(ReplaceStringContentsWithWhitespaces, tc.testDir)398 for _, wantEnum := range tc.wantEnums {399 wantEnum.StartOffset = setOffset(wantEnum.StartOffset, wantEnum.LineNumber)400 var match bool401 var gotEnumF declaration_extractor.EnumDeclaration402 for _, gotEnum := range gotEnums {403 if gotEnum.EnumName == wantEnum.EnumName {404 if gotEnum == wantEnum {405 match = true406 }407 gotEnumF = gotEnum408 break409 }410 }411 if !match {412 t.Errorf("want enum %v, got %v", wantEnum, gotEnumF)413 }414 }415 if (gotErr != nil && tc.wantErr == nil) ||416 (gotErr == nil && tc.wantErr != nil) {417 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)418 }419 if gotErr != nil && tc.wantErr != nil {420 if gotErr.Error() != tc.wantErr.Error() {421 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)422 }423 }424 })425 }426}427func TestDeclarationExtractor_ExtractTypeDefinitions(t *testing.T) {428 tests := []struct {429 scenario string430 testDir string431 wantTypeDefinitions []declaration_extractor.TypeDefinitionDeclaration432 wantErr error433 }{434 {435 scenario: "Has Type Definitions",436 testDir: "./test_files/ExtractTypeDefinitions/HasTypeDefinitions.cx",437 wantTypeDefinitions: []declaration_extractor.TypeDefinitionDeclaration{438 {439 PackageID: "main",440 FileID: "./test_files/ExtractTypeDefinitions/HasTypeDefinitions.cx",441 StartOffset: 14,442 Length: 18,443 LineNumber: 3,444 TypeDefinitionName: "Direction",445 },446 {447 PackageID: "main",448 FileID: "./test_files/ExtractTypeDefinitions/HasTypeDefinitions.cx",449 StartOffset: 100,450 Length: 15,451 LineNumber: 12,452 TypeDefinitionName: "Season",453 },454 },455 },456 {457 scenario: "Package Error",458 testDir: "./test_files/ExtractTypeDefinitions/PackageError.cx",459 wantTypeDefinitions: []declaration_extractor.TypeDefinitionDeclaration{},460 wantErr: errors.New("PackageError.cx:1: syntax error: package declaration"),461 },462 {463 scenario: "Syntax Error",464 testDir: "./test_files/ExtractTypeDefinitions/SyntaxError.cx",465 wantTypeDefinitions: []declaration_extractor.TypeDefinitionDeclaration{466 {467 PackageID: "main",468 FileID: "./test_files/ExtractTypeDefinitions/SyntaxError.cx",469 StartOffset: 14,470 Length: 18,471 LineNumber: 3,472 TypeDefinitionName: "Direction",473 },474 {475 PackageID: "main",476 FileID: "./test_files/ExtractTypeDefinitions/SyntaxError.cx",477 StartOffset: 100,478 Length: 15,479 LineNumber: 12,480 TypeDefinitionName: "Season",481 },482 },483 wantErr: errors.New("SyntaxError.cx:21: syntax error: type definition declaration"),484 },485 {486 scenario: "Syntax Error 2",487 testDir: "./test_files/ExtractTypeDefinitions/SyntaxError2.cx",488 wantTypeDefinitions: []declaration_extractor.TypeDefinitionDeclaration{489 {490 PackageID: "main",491 FileID: "./test_files/ExtractTypeDefinitions/SyntaxError2.cx",492 StartOffset: 14,493 Length: 18,494 LineNumber: 3,495 TypeDefinitionName: "Direction",496 },497 {498 PackageID: "main",499 FileID: "./test_files/ExtractTypeDefinitions/SyntaxError2.cx",500 StartOffset: 100,501 Length: 15,502 LineNumber: 12,503 TypeDefinitionName: "Season",504 },505 },506 wantErr: errors.New("SyntaxError2.cx:21: syntax error: type definition declaration"),507 },508 }509 for _, tc := range tests {510 t.Run(tc.scenario, func(t *testing.T) {511 srcBytes, err := os.ReadFile(tc.testDir)512 if err != nil {513 t.Fatal(err)514 }515 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)516 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)517 if err != nil {518 t.Fatal(filepath.Base(tc.testDir), err)519 }520 gotTypeDefinitions, gotErr := declaration_extractor.ExtractTypeDefinitions(ReplaceStringContentsWithWhitespaces, tc.testDir)521 for _, wantTypeDef := range tc.wantTypeDefinitions {522 wantTypeDef.StartOffset = setOffset(wantTypeDef.StartOffset, wantTypeDef.LineNumber)523 var gotTypeDefF declaration_extractor.TypeDefinitionDeclaration524 var match bool525 for _, gotTypeDef := range gotTypeDefinitions {526 if gotTypeDef.TypeDefinitionName == wantTypeDef.TypeDefinitionName {527 gotTypeDefF = gotTypeDef528 if gotTypeDef == wantTypeDef {529 match = true530 }531 break532 }533 }534 if !match {535 t.Errorf("want type definition %v, got %v", wantTypeDef, gotTypeDefF)536 }537 }538 if (gotErr != nil && tc.wantErr == nil) ||539 (gotErr == nil && tc.wantErr != nil) {540 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)541 }542 if gotErr != nil && tc.wantErr != nil {543 if gotErr.Error() != tc.wantErr.Error() {544 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)545 }546 }547 })548 }549}550func TestDeclarationExtractor_ExtractStructs(t *testing.T) {551 tests := []struct {552 scenario string553 testDir string554 wantStructs []declaration_extractor.StructDeclaration555 wantErr error556 }{557 {558 scenario: "Has structs",559 testDir: "./test_files/ExtractStructs/HasStructs.cx",560 wantStructs: []declaration_extractor.StructDeclaration{561 {562 PackageID: "main",563 FileID: "./test_files/ExtractStructs/HasStructs.cx",564 StartOffset: 58,565 Length: 17,566 LineNumber: 5,567 StructName: "Point",568 StructFields: []*declaration_extractor.StructField{569 {570 StructFieldName: "x",571 StartOffset: 79,572 Length: 5,573 LineNumber: 6,574 },575 {576 StructFieldName: "y",577 StartOffset: 86,578 Length: 5,579 LineNumber: 7,580 },581 },582 },583 {584 PackageID: "main",585 FileID: "./test_files/ExtractStructs/HasStructs.cx",586 StartOffset: 121,587 Length: 19,588 LineNumber: 11,589 StructName: "Strings",590 StructFields: []*declaration_extractor.StructField{591 {592 StructFieldName: "lBound",593 StartOffset: 144,594 Length: 10,595 LineNumber: 12,596 },597 {598 StructFieldName: "string",599 StartOffset: 156,600 Length: 10,601 LineNumber: 13,602 },603 {604 StructFieldName: "stringA",605 StartOffset: 168,606 Length: 13,607 LineNumber: 14,608 },609 {610 StructFieldName: "rBound",611 StartOffset: 183,612 Length: 10,613 LineNumber: 15,614 },615 },616 },617 },618 },619 {620 scenario: "Has Struct 2",621 testDir: "./test_files/ExtractStructs/HasStructs2.cx",622 wantStructs: []declaration_extractor.StructDeclaration{623 {624 PackageID: "main",625 FileID: "./test_files/ExtractStructs/HasStructs2.cx",626 StartOffset: 14,627 Length: 17,628 LineNumber: 3,629 StructName: "Point",630 StructFields: []*declaration_extractor.StructField{631 {632 StructFieldName: "x",633 StartOffset: 35,634 Length: 5,635 LineNumber: 4,636 },637 {638 StructFieldName: "y",639 StartOffset: 42,640 Length: 5,641 LineNumber: 5,642 },643 },644 },645 {646 PackageID: "main",647 FileID: "./test_files/ExtractStructs/HasStructs2.cx",648 StartOffset: 51,649 Length: 18,650 LineNumber: 8,651 StructName: "Canvas",652 StructFields: []*declaration_extractor.StructField{653 {654 StructFieldName: "points",655 StartOffset: 73,656 Length: 16,657 LineNumber: 9,658 },659 },660 },661 },662 },663 {664 scenario: "Package Error",665 testDir: "./test_files/ExtractStructs/PackageError.cx",666 wantStructs: []declaration_extractor.StructDeclaration{},667 wantErr: errors.New("PackageError.cx:2: syntax error: package declaration"),668 },669 {670 scenario: "Syntax Error",671 testDir: "./test_files/ExtractStructs/SyntaxError.cx",672 wantStructs: []declaration_extractor.StructDeclaration{673 {674 PackageID: "main",675 FileID: "./test_files/ExtractStructs/SyntaxError.cx",676 StartOffset: 14,677 Length: 17,678 LineNumber: 3,679 StructName: "Point",680 StructFields: []*declaration_extractor.StructField{681 {682 StructFieldName: "x",683 StartOffset: 35,684 Length: 5,685 LineNumber: 4,686 },687 {688 StructFieldName: "y",689 StartOffset: 42,690 Length: 5,691 LineNumber: 5,692 },693 },694 },695 },696 wantErr: errors.New("SyntaxError.cx:8: syntax error: struct declaration"),697 },698 {699 scenario: "Syntax Error 2",700 testDir: "./test_files/ExtractStructs/SyntaxError2.cx",701 wantStructs: []declaration_extractor.StructDeclaration{702 {703 PackageID: "main",704 FileID: "./test_files/ExtractStructs/SyntaxError2.cx",705 StartOffset: 58,706 Length: 17,707 LineNumber: 5,708 StructName: "Point",709 StructFields: []*declaration_extractor.StructField{710 {711 StructFieldName: "x",712 StartOffset: 79,713 Length: 5,714 LineNumber: 6,715 },716 {717 StructFieldName: "y",718 StartOffset: 86,719 Length: 5,720 LineNumber: 7,721 },722 },723 },724 },725 wantErr: errors.New("SyntaxError2.cx:16: syntax error:struct field"),726 },727 }728 for _, tc := range tests {729 t.Run(tc.scenario, func(t *testing.T) {730 srcBytes, err := os.ReadFile(tc.testDir)731 if err != nil {732 t.Fatal(err)733 }734 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)735 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)736 if err != nil {737 t.Fatal(filepath.Base(tc.testDir), err)738 }739 gotStructs, gotErr := declaration_extractor.ExtractStructs(ReplaceStringContentsWithWhitespaces, tc.testDir)740 for _, wantStruct := range tc.wantStructs {741 wantStruct.StartOffset = setOffset(wantStruct.StartOffset, wantStruct.LineNumber)742 var match bool743 var gotStructF declaration_extractor.StructDeclaration744 for _, gotStruct := range gotStructs {745 if gotStruct.StructName == wantStruct.StructName {746 gotStructF = gotStruct747 if gotStruct.FileID == wantStruct.FileID &&748 gotStruct.StartOffset == wantStruct.StartOffset &&749 gotStruct.Length == wantStruct.Length &&750 gotStruct.LineNumber == wantStruct.LineNumber &&751 gotStruct.PackageID == wantStruct.PackageID {752 var fieldMatch bool = true753 for k, wantField := range wantStruct.StructFields {754 if *gotStruct.StructFields[k] != *wantField {755 fieldMatch = false756 break757 }758 }759 if fieldMatch {760 match = true761 }762 break763 }764 break765 }766 }767 if !match {768 t.Errorf("want struct %v", wantStruct)769 for _, wantField := range wantStruct.StructFields {770 t.Error(wantField)771 }772 t.Errorf("got %v", gotStructF)773 for _, gotField := range gotStructF.StructFields {774 t.Error(gotField)775 }776 }777 }778 if (gotErr != nil && tc.wantErr == nil) ||779 (gotErr == nil && tc.wantErr != nil) {780 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)781 }782 if gotErr != nil && tc.wantErr != nil {783 if gotErr.Error() != tc.wantErr.Error() {784 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)785 }786 }787 })788 }789}790func TestDeclarationExtractor_ExtractFuncs(t *testing.T) {791 tests := []struct {792 scenario string793 testDir string794 wantFuncs []declaration_extractor.FuncDeclaration795 wantErr error796 }{797 {798 scenario: "Has funcs",799 testDir: "./test_files/ExtractFuncs/HasFuncs.cx",800 wantFuncs: []declaration_extractor.FuncDeclaration{801 {802 PackageID: "main",803 FileID: "./test_files/ExtractFuncs/HasFuncs.cx",804 StartOffset: 322,805 Length: 12,806 LineNumber: 20,807 FuncName: "main",808 },809 {810 PackageID: "main",811 FileID: "./test_files/ExtractFuncs/HasFuncs.cx",812 StartOffset: 14,813 Length: 53,814 LineNumber: 3,815 FuncName: "addition",816 },817 {818 PackageID: "main",819 FileID: "./test_files/ExtractFuncs/HasFuncs.cx",820 StartOffset: 104,821 Length: 50,822 LineNumber: 7,823 FuncName: "minus",824 },825 {826 PackageID: "main",827 FileID: "./test_files/ExtractFuncs/HasFuncs.cx",828 StartOffset: 226,829 Length: 29,830 LineNumber: 15,831 FuncName: "printName",832 },833 },834 },835 {836 scenario: "Package Error",837 testDir: "./test_files/ExtractFuncs/PackageError.cx",838 wantFuncs: []declaration_extractor.FuncDeclaration{},839 wantErr: errors.New("PackageError.cx:1: syntax error: package declaration"),840 },841 {842 scenario: "Syntax Error",843 testDir: "./test_files/ExtractFuncs/SyntaxError.cx",844 wantFuncs: []declaration_extractor.FuncDeclaration{845 {846 PackageID: "main",847 FileID: "./test_files/ExtractFuncs/SyntaxError.cx",848 StartOffset: 322,849 Length: 12,850 LineNumber: 20,851 FuncName: "main",852 },853 {854 PackageID: "main",855 FileID: "./test_files/ExtractFuncs/SyntaxError.cx",856 StartOffset: 14,857 Length: 53,858 LineNumber: 3,859 FuncName: "addition",860 },861 {862 PackageID: "main",863 FileID: "./test_files/ExtractFuncs/SyntaxError.cx",864 StartOffset: 104,865 Length: 50,866 LineNumber: 7,867 FuncName: "minus",868 },869 {870 PackageID: "main",871 FileID: "./test_files/ExtractFuncs/SyntaxError.cx",872 StartOffset: 226,873 Length: 29,874 LineNumber: 15,875 FuncName: "printName",876 },877 },878 wantErr: errors.New("SyntaxError.cx:31: syntax error: func declaration"),879 },880 }881 for _, tc := range tests {882 t.Run(tc.scenario, func(t *testing.T) {883 srcBytes, err := os.ReadFile(tc.testDir)884 if err != nil {885 t.Fatal(err)886 }887 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)888 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)889 if err != nil {890 t.Fatal(filepath.Base(tc.testDir), err)891 }892 gotFuncs, gotErr := declaration_extractor.ExtractFuncs(ReplaceStringContentsWithWhitespaces, tc.testDir)893 for _, wantFunc := range tc.wantFuncs {894 wantFunc.StartOffset = setOffset(wantFunc.StartOffset, wantFunc.LineNumber)895 var match bool896 var gotFuncF declaration_extractor.FuncDeclaration897 for _, gotFunc := range gotFuncs {898 if gotFunc.FuncName == wantFunc.FuncName {899 if gotFunc == wantFunc {900 match = true901 }902 gotFuncF = gotFunc903 break904 }905 }906 if !match {907 t.Errorf("want func %v, got %v", wantFunc, gotFuncF)908 }909 }910 if (gotErr != nil && tc.wantErr == nil) ||911 (gotErr == nil && tc.wantErr != nil) {912 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)913 }914 if gotErr != nil && tc.wantErr != nil {915 if gotErr.Error() != tc.wantErr.Error() {916 t.Errorf("want error %v, got %v", tc.wantErr, gotErr)917 }918 }919 })920 }921}922func TestDeclarationExtractor_ReDeclarationCheck(t *testing.T) {923 tests := []struct {924 scenario string925 testDir string926 wantReDeclarationError error927 }{928 {929 scenario: "No Redeclaration",930 testDir: "./test_files/ReDeclarationCheck/NoRedeclaration.cx",931 wantReDeclarationError: nil,932 },933 {934 scenario: "Redeclared global",935 testDir: "./test_files/ReDeclarationCheck/RedeclaredGlobal.cx",936 wantReDeclarationError: errors.New("RedeclaredGlobal.cx:5: redeclaration error: global: banana"),937 },938 {939 scenario: "Redeclared enum",940 testDir: "./test_files/ReDeclarationCheck/RedeclaredEnum.cx",941 wantReDeclarationError: errors.New("RedeclaredEnum.cx:8: redeclaration error: enum: myEnum"),942 },943 {944 scenario: "Redeclared type definition",945 testDir: "./test_files/ReDeclarationCheck/RedeclaredTypeDefinition.cx",946 wantReDeclarationError: errors.New("RedeclaredTypeDefinition.cx:21: redeclaration error: type definition: Season"),947 },948 {949 scenario: "Redeclared struct",950 testDir: "./test_files/ReDeclarationCheck/RedeclaredStruct.cx",951 wantReDeclarationError: errors.New("RedeclaredStruct.cx:15: redeclaration error: struct: Animal"),952 },953 {954 scenario: "Redeclared struct field",955 testDir: "./test_files/ReDeclarationCheck/RedeclaredStructField.cx",956 wantReDeclarationError: errors.New("RedeclaredStructField.cx:13: redeclaration error: struct field: name"),957 },958 {959 scenario: "Redeclared func",960 testDir: "./test_files/ReDeclarationCheck/RedeclaredFunc.cx",961 wantReDeclarationError: errors.New("RedeclaredFunc.cx:23: redeclaration error: func: add"),962 },963 }964 for _, tc := range tests {965 t.Run(tc.scenario, func(t *testing.T) {966 srcBytes, err := os.ReadFile(tc.testDir)967 if err != nil {968 t.Fatal(err)969 }970 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)971 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)972 if err != nil {973 t.Fatal(filepath.Base(tc.testDir), err)974 }975 globals, err := declaration_extractor.ExtractGlobals(ReplaceStringContentsWithWhitespaces, tc.testDir)976 if err != nil {977 t.Fatal(err)978 }979 enums, err := declaration_extractor.ExtractEnums(ReplaceStringContentsWithWhitespaces, tc.testDir)980 if err != nil {981 t.Fatal(err)982 }983 typeDefinitions, err := declaration_extractor.ExtractTypeDefinitions(ReplaceStringContentsWithWhitespaces, tc.testDir)984 if err != nil {985 t.Fatal(err)986 }987 structs, err := declaration_extractor.ExtractStructs(ReplaceStringContentsWithWhitespaces, tc.testDir)988 if err != nil {989 t.Fatal(err)990 }991 funcs, err := declaration_extractor.ExtractFuncs(ReplaceStringContentsWithWhitespaces, tc.testDir)992 if err != nil {993 t.Fatal(err)994 }995 gotReDeclarationError := declaration_extractor.ReDeclarationCheck(globals, enums, typeDefinitions, structs, funcs)996 if (gotReDeclarationError != nil && tc.wantReDeclarationError == nil) ||997 (gotReDeclarationError == nil && tc.wantReDeclarationError != nil) {998 t.Errorf("want error %v, got %v", tc.wantReDeclarationError, gotReDeclarationError)999 }1000 if gotReDeclarationError != nil && tc.wantReDeclarationError != nil {1001 if gotReDeclarationError.Error() != tc.wantReDeclarationError.Error() {1002 t.Errorf("want error %v, got %v", tc.wantReDeclarationError, gotReDeclarationError)1003 }1004 }1005 })1006 }1007}1008func TestDeclarationExtractor_GetDeclarations(t *testing.T) {1009 tests := []struct {1010 scenario string1011 testDir string1012 wantDeclarations []string1013 }{1014 {1015 scenario: "Has declarations",1016 testDir: "./test_files/GetDeclarations/HasDeclarations.cx",1017 wantDeclarations: []string{1018 "var number i32",1019 `var string str = "Hello World"`,1020 "Apple fruit = iota",1021 "Orange",1022 "Banana",1023 "type fruit i64",1024 "type Blender struct",1025 "func (b *Blender) blend ()",1026 "func main ()",1027 },1028 },1029 }1030 for _, tc := range tests {1031 t.Run(tc.scenario, func(t *testing.T) {1032 srcBytes, err := os.ReadFile(tc.testDir)1033 if err != nil {1034 t.Fatal(err)1035 }1036 ReplaceCommentsWithWhitespaces := declaration_extractor.ReplaceCommentsWithWhitespaces(srcBytes)1037 ReplaceStringContentsWithWhitespaces, err := declaration_extractor.ReplaceStringContentsWithWhitespaces(ReplaceCommentsWithWhitespaces)1038 if err != nil {1039 t.Fatal(filepath.Base(tc.testDir), err)1040 }1041 globals, err := declaration_extractor.ExtractGlobals(ReplaceStringContentsWithWhitespaces, tc.testDir)1042 if err != nil {1043 t.Fatal(err)1044 }1045 enums, err := declaration_extractor.ExtractEnums(ReplaceStringContentsWithWhitespaces, tc.testDir)1046 if err != nil {1047 t.Fatal(err)1048 }1049 typeDefinitions, err := declaration_extractor.ExtractTypeDefinitions(ReplaceStringContentsWithWhitespaces, tc.testDir)1050 if err != nil {1051 t.Fatal(err)1052 }1053 structs, err := declaration_extractor.ExtractStructs(ReplaceStringContentsWithWhitespaces, tc.testDir)1054 if err != nil {1055 t.Fatal(err)1056 }1057 funcs, err := declaration_extractor.ExtractFuncs(ReplaceStringContentsWithWhitespaces, tc.testDir)1058 if err != nil {1059 t.Fatal(err)1060 }1061 if declaration_extractor.ReDeclarationCheck(globals, enums, typeDefinitions, structs, funcs) != nil {1062 t.Fatal(err)1063 }1064 declarations := declaration_extractor.GetDeclarations(ReplaceCommentsWithWhitespaces, globals, enums, typeDefinitions, structs, funcs)1065 for i := range declarations {1066 if declarations[i] != tc.wantDeclarations[i] {1067 t.Errorf("want declaration %v, got %v", tc.wantDeclarations[i], declarations[i])1068 }1069 }1070 })1071 }1072}1073func TestDeclarationExtractor_ExtractAllDeclarations(t *testing.T) {1074 tests := []struct {1075 scenario string1076 testDirs []string1077 wantGlobals int1078 wantEnums int1079 wantTypeDefinitions int1080 wantStructs int1081 wantFuncs int1082 wantError error1083 }{1084 {1085 scenario: "Single file",1086 testDirs: []string{1087 "./test_files/ExtractAllDeclarations/SingleFile.cx",1088 },1089 wantGlobals: 2,1090 wantEnums: 3,1091 wantTypeDefinitions: 1,1092 wantStructs: 1,1093 wantFuncs: 2,1094 wantError: nil,1095 },1096 {1097 scenario: "Multiple files",1098 testDirs: []string{1099 "./test_files/ExtractAllDeclarations/MultipleFiles/main.cx",1100 "./test_files/ExtractAllDeclarations/MultipleFiles/helper.cx",1101 "./test_files/ExtractAllDeclarations/MultipleFiles/program.cx",1102 },1103 wantGlobals: 3,1104 wantEnums: 12,1105 wantTypeDefinitions: 3,1106 wantStructs: 3,1107 wantFuncs: 5,1108 wantError: nil,1109 },1110 {1111 scenario: "Global Syntax Error",1112 testDirs: []string{1113 "./test_files/ExtractAllDeclarations/GlobalSyntaxError/main.cx",1114 "./test_files/ExtractAllDeclarations/GlobalSyntaxError/helper.cx",1115 "./test_files/ExtractAllDeclarations/GlobalSyntaxError/program.cx",1116 },1117 wantGlobals: 0,1118 wantEnums: 12,1119 wantTypeDefinitions: 3,1120 wantStructs: 3,1121 wantFuncs: 5,1122 wantError: errors.New("main.cx:9: syntax error: global declaration"),1123 },1124 {1125 scenario: "Enum Syntax Error",1126 testDirs: []string{1127 "./test_files/ExtractAllDeclarations/EnumSyntaxError/main.cx",1128 "./test_files/ExtractAllDeclarations/EnumSyntaxError/helper.cx",1129 "./test_files/ExtractAllDeclarations/EnumSyntaxError/program.cx",1130 },1131 wantGlobals: 3,1132 wantEnums: 0,1133 wantTypeDefinitions: 3,1134 wantStructs: 3,1135 wantFuncs: 5,1136 wantError: errors.New("program.cx:27: syntax error: enum declaration"),1137 },1138 {1139 scenario: "Type Definition Syntax Error",1140 testDirs: []string{1141 "./test_files/ExtractAllDeclarations/TypeDefinitionSyntaxError/main.cx",1142 "./test_files/ExtractAllDeclarations/TypeDefinitionSyntaxError/helper.cx",1143 "./test_files/ExtractAllDeclarations/TypeDefinitionSyntaxError/program.cx",1144 },1145 wantGlobals: 3,1146 wantEnums: 12,1147 wantTypeDefinitions: 0,1148 wantStructs: 3,1149 wantFuncs: 5,1150 wantError: errors.New("program.cx:21: syntax error: type definition declaration"),1151 }, {1152 scenario: "Struct Syntax Error",1153 testDirs: []string{1154 "./test_files/ExtractAllDeclarations/StructSyntaxError/main.cx",1155 "./test_files/ExtractAllDeclarations/StructSyntaxError/helper.cx",1156 "./test_files/ExtractAllDeclarations/StructSyntaxError/program.cx",1157 },1158 wantGlobals: 3,1159 wantEnums: 12,1160 wantTypeDefinitions: 3,1161 wantStructs: 0,1162 wantFuncs: 5,1163 wantError: errors.New("helper.cx:20: syntax error: struct declaration"),1164 },1165 {1166 scenario: "Func Syntax Error",1167 testDirs: []string{1168 "./test_files/ExtractAllDeclarations/FuncSyntaxError/main.cx",1169 "./test_files/ExtractAllDeclarations/FuncSyntaxError/helper.cx",1170 "./test_files/ExtractAllDeclarations/FuncSyntaxError/program.cx",1171 },1172 wantGlobals: 3,1173 wantEnums: 12,1174 wantTypeDefinitions: 3,1175 wantStructs: 3,1176 wantFuncs: 2,1177 wantError: errors.New("helper.cx:34: syntax error: func declaration"),1178 },1179 {1180 scenario: "Redeclaration Error",1181 testDirs: []string{1182 "./test_files/ExtractAllDeclarations/RedeclarationError/main.cx",1183 "./test_files/ExtractAllDeclarations/RedeclarationError/helper.cx",1184 "./test_files/ExtractAllDeclarations/RedeclarationError/program.cx",1185 },1186 wantGlobals: 4,1187 wantEnums: 12,1188 wantTypeDefinitions: 3,1189 wantStructs: 3,1190 wantFuncs: 5,1191 wantError: errors.New("main.cx:13: redeclaration error: global: number"),1192 },1193 {1194 scenario: "String Syntax Error",1195 testDirs: []string{1196 "./test_files/ExtractAllDeclarations/StringSyntaxError/main.cx",1197 "./test_files/ExtractAllDeclarations/StringSyntaxError/helper.cx",1198 "./test_files/ExtractAllDeclarations/StringSyntaxError/program.cx",1199 },1200 wantGlobals: 3,1201 wantEnums: 0,1202 wantTypeDefinitions: 0,1203 wantStructs: 3,1204 wantFuncs: 4,1205 wantError: errors.New("program.cx:41: syntax error: quote not terminated"),1206 },1207 }1208 for _, tc := range tests {1209 t.Run(tc.scenario, func(t *testing.T) {1210 var files []*os.File1211 for _, testDir := range tc.testDirs {1212 file, err := os.Open(testDir)1213 if err != nil {1214 t.Fatal(err)1215 }1216 files = append(files, file)1217 }1218 Globals, Enums, TypeDefinitions, Structs, Funcs, gotErr := declaration_extractor.ExtractAllDeclarations(files)1219 if len(Globals) == 0 && len(Enums) == 0 && len(Structs) == 0 && len(Funcs) == 0 {1220 t.Error("No Declarations found")1221 }1222 if len(Globals) != tc.wantGlobals {1223 t.Errorf("want global %v, got %v", tc.wantGlobals, len(Globals))1224 }1225 if len(Enums) != tc.wantEnums {1226 t.Errorf("want enum %v, got %v", tc.wantEnums, len(Enums))1227 }1228 if len(TypeDefinitions) != tc.wantTypeDefinitions {1229 t.Errorf("want type definition %v, got %v", tc.wantTypeDefinitions, len(TypeDefinitions))1230 }1231 if len(Structs) != tc.wantStructs {1232 t.Errorf("want struct %v, got %v", tc.wantStructs, len(Structs))1233 }1234 if len(Funcs) != tc.wantFuncs {1235 t.Errorf("want func %v, got %v", tc.wantFuncs, len(Funcs))1236 }1237 if (gotErr != nil && tc.wantError == nil) ||1238 (gotErr == nil && tc.wantError != nil) {1239 t.Errorf("want error %v, got %v", tc.wantError, gotErr)1240 }1241 if gotErr != nil && tc.wantError != nil {1242 if gotErr.Error() != tc.wantError.Error() {1243 t.Errorf("want error %v, got %v", tc.wantError, gotErr)1244 }1245 }1246 })1247 }1248}1249// Regex is slower because there’s a lot of conditionals and it’s a long pattern to match.1250// Tokenizing is faster but isn’t as accurate.1251func BenchmarkDeclarationExtractor_ExtractFuncs(b *testing.B) {1252 benchmarks := []struct {1253 scenario string1254 testDir string1255 }{1256 {scenario: "regular funcs", testDir: "./test_files/ExtractFuncs/HasFuncs.cx"},1257 }1258 for _, bm := range benchmarks {1259 b.Run(bm.scenario, func(b *testing.B) {1260 srcBytes, err := os.ReadFile(bm.testDir)1261 if err != nil {1262 b.Fatal(err)1263 }1264 for n := 0; n < b.N; n++ {1265 declaration_extractor.ExtractFuncs(srcBytes, bm.testDir)1266 }1267 })1268 }1269}...

Full Screen

Full Screen

cfsmextract.go

Source:cfsmextract.go Github

copy

Full Screen

1package cfsmextract2// This file contains only the functions needed to start the analysis3// - Handle command line flags4// - Set up session variables5import (6 "fmt"7 "go/types"8 "log"9 "os"10 "time"11 "github.com/nickng/dingo-hunter/cfsmextract/sesstype"12 "github.com/nickng/dingo-hunter/cfsmextract/utils"13 "github.com/nickng/dingo-hunter/ssabuilder"14 "golang.org/x/tools/go/ssa"15)16type CFSMExtract struct {17 SSA *ssabuilder.SSAInfo18 Time time.Duration19 Done chan struct{}20 Error chan error21 session *sesstype.Session22 goQueue []*frame23 prefix string24 outdir string25}26func New(ssainfo *ssabuilder.SSAInfo, prefix, outdir string) *CFSMExtract {27 return &CFSMExtract{28 SSA: ssainfo,29 Done: make(chan struct{}),30 Error: make(chan error),31 session: sesstype.CreateSession(),32 goQueue: []*frame{},33 prefix: prefix,34 outdir: outdir,35 }36}37// Run function analyses main.main() then all the goroutines collected, and38// finally output the analysis results.39func (extract *CFSMExtract) Run() {40 startTime := time.Now()41 mainPkg := ssabuilder.MainPkg(extract.SSA.Prog)42 if mainPkg == nil {43 fmt.Fprintf(os.Stderr, "Error: 'main' package not found\n")44 os.Exit(1)45 }46 init := mainPkg.Func("init")47 main := mainPkg.Func("main")48 fr := makeToplevelFrame(extract)49 for _, pkg := range extract.SSA.Prog.AllPackages() {50 for _, memb := range pkg.Members {51 switch val := memb.(type) {52 case *ssa.Global:53 switch derefAll(val.Type()).(type) {54 case *types.Array:55 vd := utils.NewDef(val)56 fr.env.globals[val] = vd57 fr.env.arrays[vd] = make(Elems)58 case *types.Struct:59 vd := utils.NewDef(val)60 fr.env.globals[val] = vd61 fr.env.structs[vd] = make(Fields)62 case *types.Chan:63 var c *types.Chan64 vd := utils.NewDef(utils.EmptyValue{T: c})65 fr.env.globals[val] = vd66 default:67 fr.env.globals[val] = utils.NewDef(val)68 }69 }70 }71 }72 fmt.Fprintf(os.Stderr, "++ call.toplevel %s()\n", orange("init"))73 visitFunc(init, fr)74 if main == nil {75 fmt.Fprintf(os.Stderr, "Error: 'main()' function not found in 'main' package\n")76 os.Exit(1)77 }78 fmt.Fprintf(os.Stderr, "++ call.toplevel %s()\n", orange("main"))79 visitFunc(main, fr)80 fr.env.session.Types[fr.gortn.role] = fr.gortn.root81 var goFrm *frame82 for len(extract.goQueue) > 0 {83 goFrm, extract.goQueue = extract.goQueue[0], extract.goQueue[1:]84 fmt.Fprintf(os.Stderr, "\n%s\nLOCATION: %s%s\n", goFrm.fn.Name(), goFrm.gortn.role.Name(), loc(goFrm, goFrm.fn.Pos()))85 visitFunc(goFrm.fn, goFrm)86 goFrm.env.session.Types[goFrm.gortn.role] = goFrm.gortn.root87 }88 extract.Time = time.Since(startTime)89 extract.Done <- struct{}{}90}91// Session returns the session after extraction.92func (extract *CFSMExtract) Session() *sesstype.Session {93 return extract.session94}95func (extract *CFSMExtract) WriteOutput() {96 fmt.Printf(" ----- Results ----- \n%s\n", extract.session.String())97 sesstype.PrintNodeSummary(extract.session)98 dotFile, err := os.OpenFile(fmt.Sprintf("%s.dot", extract.prefix), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)99 if err != nil {100 panic(err)101 }102 defer dotFile.Close()103 dot := sesstype.NewGraphvizDot(extract.session)104 if _, err = dot.WriteTo(dotFile); err != nil {105 panic(err)106 }107 os.MkdirAll(extract.outdir, 0750)108 cfsmPath := fmt.Sprintf("%s/%s_cfsms", extract.outdir, extract.prefix)109 cfsmFile, err := os.OpenFile(cfsmPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)110 if err != nil {111 panic(err)112 }113 defer cfsmFile.Close()114 cfsms := sesstype.NewCFSMs(extract.session)115 if _, err := cfsms.WriteTo(cfsmFile); err != nil {116 log.Fatalf("Cannot write CFSMs to file: %v", err)117 }118 fmt.Fprintf(os.Stderr, "CFSMs written to %s\n", cfsmPath)119 cfsms.PrintSummary()120}...

Full Screen

Full Screen

fields_test.go

Source:fields_test.go Github

copy

Full Screen

1package stf2import (3 "errors"4 "github.com/stretchr/testify/assert"5 "testing"6)7func TestExtractFields_errors_on_nil(t *testing.T) {8 _, err := NewExtractor().ExtractFields(nil)9 assert.Equal(t, errors.New("needs struct or pointer to struct type, got: invalid"), err)10}11func TestExtractFields_errors_on_non_struct(t *testing.T) {12 d := []string{"one"}13 _, err := NewExtractor().ExtractFields(d)14 assert.Equal(t, errors.New("needs struct or pointer to struct type, got: slice"), err)15}16func TestExtractFields_recursive_data(t *testing.T) {17 type Data struct {18 Name string `json:"name"`19 Main *Data `json:"main"`20 }21 b := &Data{Name: "sub"}22 d := Data{Main: b, Name: "Root"}23 b.Main = &d24 tags, err := NewExtractor().ExtractFields(d)25 assert.Nil(t, err)26 assert.Equal(t, 3, len(tags))27 root := tags["name"]28 assert.Equal(t, "Root", root)29 sub := tags["main.name"]30 assert.Equal(t, "sub", sub)31 recursiveRoot := tags["main.main.name"]32 assert.Equal(t, "Root", recursiveRoot)33}34func TestExtractFields_handles_nils(t *testing.T) {35 type Four struct {36 Sub string `json:"s3"`37 }38 type Three struct {39 Sub *Four `json:"s2"`40 }41 type Two struct {42 Sub *Three `json:"s1"`43 }44 type One struct {45 Main Two `json:"main"`46 }47 d := One{Main: Two{Sub: &Three{Sub: nil}}}48 tags, err := NewExtractor().ExtractFields(d)49 assert.Nil(t, err)50 assert.Equal(t, len(tags), 1)51 var expected *Four52 assert.Equal(t, expected, tags["main.s1.s2"])53}54func TestExtractFields_handles_pointers(t *testing.T) {55 type Four struct {56 Sub string `json:"s3"`57 }58 type Three struct {59 Sub *Four `json:"s2"`60 }61 type Two struct {62 Sub *Three `json:"s1"`63 }64 type One struct {65 Main Two `json:"main"`66 }67 key := "12312"68 d := One{Main: Two{Sub: &Three{Sub: &Four{Sub: key}}}}69 tags, err := NewExtractor().ExtractFields(d)70 assert.Nil(t, err)71 assert.Equal(t, len(tags), 1)72 assert.Equal(t, key, tags["main.s1.s2.s3"])73}74func TestExtractFields_handles_structs(t *testing.T) {75 type Three struct {76 Sub []string `json:"sub_sub"`77 }78 type Two struct {79 Sub Three `json:"sub"`80 }81 type One struct {82 Main Two `json:"main"`83 }84 slice := []string{"1234", "6789"}85 d := One{Main: Two{Sub: Three{Sub: slice}}}86 tags, err := NewExtractor().ExtractFields(d)87 assert.Nil(t, err)88 assert.Equal(t, len(tags), 1)89 assert.Equal(t, slice, tags["main.sub.sub_sub"])90}91func TestExtractFields_defaults(t *testing.T) {92 data := struct {93 Tag string94 }{95 Tag: "boop",96 }97 tags, err := NewExtractor().ExtractFields(data)98 assert.Nil(t, err)99 assert.Equal(t, len(tags), 1)100 assert.Equal(t, "boop", tags["Tag"])101}102func TestExtractFields_prefers_json(t *testing.T) {103 data := struct {104 Tag string `json:"taggy",stf:"json"`105 }{106 Tag: "boop",107 }108 tags, err := NewExtractor().ExtractFields(data)109 assert.Nil(t, err)110 assert.Equal(t, len(tags), 1)111 assert.Equal(t, "boop", tags["taggy"])112}113func TestExtractFields_prefers_stf_tag(t *testing.T) {114 data := struct {115 Tag string `json:"tag",stf:"stf_tag"`116 }{117 Tag: "boop",118 }119 tags, err := NewExtractor().ExtractFields(data)120 assert.Nil(t, err)121 assert.Equal(t, len(tags), 1)122 assert.Equal(t, "boop", tags["stf_tag"])123}124func TestExtractFields_ignored(t *testing.T) {125 data := struct {126 Ignored string `json:"stew",stf:"-"`127 }{128 Ignored: "boop",129 }130 tags, err := NewExtractor().ExtractFields(data)131 assert.Nil(t, err)132 assert.Equal(t, len(tags), 0)133}...

Full Screen

Full Screen

extract

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(extract.Extract("Hello World"))4}5import (6func main() {7 fmt.Println(extract.Extract("Hello World"))8}9import (10func main() {11 fmt.Println(extract.Extract("Hello World"))12}13import (14func main() {15 fmt.Println(extract.Extract("Hello World"))16}17import (18func main() {19 fmt.Println(extract.Extract("Hello World"))20}21import (22func main() {23 fmt.Println(extract.Extract("Hello World"))24}25import (26func main() {27 fmt.Println(extract.Extract("Hello World"))28}29import (30func main() {31 fmt.Println(extract.Extract("Hello World"))32}33import (34func main() {35 fmt.Println(extract.Extract("Hello World"))36}37import (38func main() {39 fmt.Println(extract.Extract("Hello World"))40}

Full Screen

Full Screen

extract

Using AI Code Generation

copy

Full Screen

1{2public static void main(String args[])3{4int a=10;5int b=20;6int c=a+b;7System.out.println(c);8}9}10{11public static void main(String args[])12{13int a=10;14int b=20;15int c=a+b;16System.out.println(c);17}18}19{20public static void main(String args[])21{22int a=10;23int b=20;24int c=a+b;25System.out.println(c);26}27}28{29public static void main(String args[])30{31int a=10;32int b=20;33int c=a+b;34System.out.println(c);35}36}37{38public static void main(String args[])39{40int a=10;41int b=20;42int c=a+b;43System.out.println(c);44}45}46{47public static void main(String args[])48{49int a=10;50int b=20;51int c=a+b;52System.out.println(c);53}54}

Full Screen

Full Screen

extract

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 out, err := exec.Command("go", "build", path).Output()4 if err != nil {5 log.Fatal(err)6 }7 fmt.Printf("%s", out)8 file := strings.Split(path, "/")9 fmt.Println(file[len(file)-1])10}11import (12func main() {13 fmt.Println("Hello, World!")14 fmt.Println(os.Args[1])15}16ProcessBuilder pb = new ProcessBuilder("java", "-cp", "C:\\Users\\username\\Documents\\NetBeansProjects\\JavaApplication1\\dist\\JavaApplication1.jar;C:\\Users\\username\\Documents\\NetBeansProjects\\JavaApplication1\\lib\\jfxrt.jar", "JavaApplication1");17Process p = pb.start();18java -cp "C:\Users\username\Documents\NetBeansProjects\JavaApplication1\dist\JavaApplication1.jar;C:\Users\username\Documents\NetBeansProjects\JavaApplication1\lib\jfxrt.jar" JavaApplication119Exception in thread "main" java.lang.UnsupportedClassVersionError: JavaApplication1 has been compiled by a more recent version of the Java Runtime (class file version 52.0), this version of the Java Runtime only recognizes class file versions up to 51.020 at java.lang.ClassLoader.defineClass1(Native Method)21 at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)

Full Screen

Full Screen

extract

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 fmt.Println(extract.Extract())5}6import (7func main() {8 fmt.Println("Hello World")9 fmt.Println(extract.Extract())10}11import (12func main() {13 fmt.Println("Hello World")14 fmt.Println(extract.Extract())15}16import (17func main() {18 fmt.Println("Hello World")19 fmt.Println(extract.Extract())20}21import (22func main() {23 fmt.Println("Hello World")24 fmt.Println(extract.Extract())25}26import (27func main() {28 fmt.Println("Hello World")29 fmt.Println(extract.Extract())30}31import (32func main() {33 fmt.Println("Hello World")34 fmt.Println(extract.Extract())35}36import (37func main() {38 fmt.Println("Hello World")39 fmt.Println(extract.Extract())40}

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful