Best Rod code snippet using main.test
resource_aws_api_gateway_usage_plan_test.go
Source:resource_aws_api_gateway_usage_plan_test.go
1package aws2import (3 "fmt"4 "testing"5 "github.com/aws/aws-sdk-go/aws"6 "github.com/aws/aws-sdk-go/aws/awserr"7 "github.com/aws/aws-sdk-go/service/apigateway"8 "github.com/hashicorp/terraform/helper/acctest"9 "github.com/hashicorp/terraform/helper/resource"10 "github.com/hashicorp/terraform/terraform"11)12func TestAccAWSAPIGatewayUsagePlan_basic(t *testing.T) {13 var conf apigateway.UsagePlan14 name := acctest.RandString(10)15 updatedName := acctest.RandString(10)16 resource.Test(t, resource.TestCase{17 PreCheck: func() { testAccPreCheck(t) },18 Providers: testAccProviders,19 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,20 Steps: []resource.TestStep{21 {22 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),23 Check: resource.ComposeTestCheckFunc(24 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),25 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),26 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", ""),27 ),28 },29 {30 Config: testAccAWSApiGatewayUsagePlanBasicUpdatedConfig(updatedName),31 Check: resource.ComposeTestCheckFunc(32 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", updatedName),33 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", ""),34 ),35 },36 {37 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),38 Check: resource.ComposeTestCheckFunc(39 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),40 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),41 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", ""),42 ),43 },44 },45 })46}47func TestAccAWSAPIGatewayUsagePlan_description(t *testing.T) {48 var conf apigateway.UsagePlan49 name := acctest.RandString(10)50 resource.Test(t, resource.TestCase{51 PreCheck: func() { testAccPreCheck(t) },52 Providers: testAccProviders,53 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,54 Steps: []resource.TestStep{55 {56 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),57 Check: resource.ComposeTestCheckFunc(58 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),59 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", ""),60 ),61 },62 {63 Config: testAccAWSApiGatewayUsagePlanDescriptionConfig(name),64 Check: resource.ComposeTestCheckFunc(65 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),66 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", "This is a description"),67 ),68 },69 {70 Config: testAccAWSApiGatewayUsagePlanDescriptionUpdatedConfig(name),71 Check: resource.ComposeTestCheckFunc(72 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", "This is a new description"),73 ),74 },75 {76 Config: testAccAWSApiGatewayUsagePlanDescriptionConfig(name),77 Check: resource.ComposeTestCheckFunc(78 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),79 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", "This is a description"),80 ),81 },82 {83 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),84 Check: resource.ComposeTestCheckFunc(85 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),86 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "description", ""),87 ),88 },89 },90 })91}92func TestAccAWSAPIGatewayUsagePlan_productCode(t *testing.T) {93 var conf apigateway.UsagePlan94 name := acctest.RandString(10)95 resource.Test(t, resource.TestCase{96 PreCheck: func() { testAccPreCheck(t) },97 Providers: testAccProviders,98 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,99 Steps: []resource.TestStep{100 {101 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),102 Check: resource.ComposeTestCheckFunc(103 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),104 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "product_code", ""),105 ),106 },107 {108 Config: testAccAWSApiGatewayUsagePlanProductCodeConfig(name),109 Check: resource.ComposeTestCheckFunc(110 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),111 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "product_code", "MYCODE"),112 ),113 },114 {115 Config: testAccAWSApiGatewayUsagePlanProductCodeUpdatedConfig(name),116 Check: resource.ComposeTestCheckFunc(117 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "product_code", "MYCODE2"),118 ),119 },120 {121 Config: testAccAWSApiGatewayUsagePlanProductCodeConfig(name),122 Check: resource.ComposeTestCheckFunc(123 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),124 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "product_code", "MYCODE"),125 ),126 },127 {128 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),129 Check: resource.ComposeTestCheckFunc(130 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),131 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "product_code", ""),132 ),133 },134 },135 })136}137func TestAccAWSAPIGatewayUsagePlan_throttling(t *testing.T) {138 var conf apigateway.UsagePlan139 name := acctest.RandString(10)140 resource.Test(t, resource.TestCase{141 PreCheck: func() { testAccPreCheck(t) },142 Providers: testAccProviders,143 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,144 Steps: []resource.TestStep{145 {146 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),147 Check: resource.ComposeTestCheckFunc(148 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),149 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),150 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings"),151 ),152 },153 {154 Config: testAccAWSApiGatewayUsagePlanThrottlingConfig(name),155 Check: resource.ComposeTestCheckFunc(156 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),157 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),158 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings.4173790118.burst_limit", "2"),159 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings.4173790118.rate_limit", "5"),160 ),161 },162 {163 Config: testAccAWSApiGatewayUsagePlanThrottlingModifiedConfig(name),164 Check: resource.ComposeTestCheckFunc(165 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),166 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),167 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings.1779463053.burst_limit", "3"),168 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings.1779463053.rate_limit", "6"),169 ),170 },171 {172 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),173 Check: resource.ComposeTestCheckFunc(174 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),175 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),176 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "throttle_settings"),177 ),178 },179 },180 })181}182func TestAccAWSAPIGatewayUsagePlan_quota(t *testing.T) {183 var conf apigateway.UsagePlan184 name := acctest.RandString(10)185 resource.Test(t, resource.TestCase{186 PreCheck: func() { testAccPreCheck(t) },187 Providers: testAccProviders,188 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,189 Steps: []resource.TestStep{190 {191 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),192 Check: resource.ComposeTestCheckFunc(193 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),194 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),195 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings"),196 ),197 },198 {199 Config: testAccAWSApiGatewayUsagePlanQuotaConfig(name),200 Check: resource.ComposeTestCheckFunc(201 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),202 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),203 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.1956747625.limit", "100"),204 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.1956747625.offset", "6"),205 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.1956747625.period", "WEEK"),206 ),207 },208 {209 Config: testAccAWSApiGatewayUsagePlanQuotaModifiedConfig(name),210 Check: resource.ComposeTestCheckFunc(211 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),212 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),213 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.3909168194.limit", "200"),214 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.3909168194.offset", "20"),215 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings.3909168194.period", "MONTH"),216 ),217 },218 {219 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),220 Check: resource.ComposeTestCheckFunc(221 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),222 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),223 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "quota_settings"),224 ),225 },226 },227 })228}229func TestAccAWSAPIGatewayUsagePlan_apiStages(t *testing.T) {230 var conf apigateway.UsagePlan231 name := acctest.RandString(10)232 resource.Test(t, resource.TestCase{233 PreCheck: func() { testAccPreCheck(t) },234 Providers: testAccProviders,235 CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,236 Steps: []resource.TestStep{237 // Create UsagePlan WITH Stages as the API calls are different238 // when creating or updating.239 {240 Config: testAccAWSApiGatewayUsagePlanApiStagesConfig(name),241 Check: resource.ComposeTestCheckFunc(242 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),243 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),244 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "api_stages.0.stage", "test"),245 ),246 },247 // Handle api stages removal248 {249 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),250 Check: resource.ComposeTestCheckFunc(251 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),252 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),253 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "api_stages"),254 ),255 },256 // Handle api stages additions257 {258 Config: testAccAWSApiGatewayUsagePlanApiStagesConfig(name),259 Check: resource.ComposeTestCheckFunc(260 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),261 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),262 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "api_stages.0.stage", "test"),263 ),264 },265 // Handle api stages updates266 {267 Config: testAccAWSApiGatewayUsagePlanApiStagesModifiedConfig(name),268 Check: resource.ComposeTestCheckFunc(269 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),270 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),271 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "api_stages.0.stage", "foo"),272 ),273 },274 {275 Config: testAccAWSApiGatewayUsagePlanBasicConfig(name),276 Check: resource.ComposeTestCheckFunc(277 testAccCheckAWSAPIGatewayUsagePlanExists("aws_api_gateway_usage_plan.main", &conf),278 resource.TestCheckResourceAttr("aws_api_gateway_usage_plan.main", "name", name),279 resource.TestCheckNoResourceAttr("aws_api_gateway_usage_plan.main", "api_stages"),280 ),281 },282 },283 })284}285func testAccCheckAWSAPIGatewayUsagePlanExists(n string, res *apigateway.UsagePlan) resource.TestCheckFunc {286 return func(s *terraform.State) error {287 rs, ok := s.RootModule().Resources[n]288 if !ok {289 return fmt.Errorf("Not found: %s", n)290 }291 if rs.Primary.ID == "" {292 return fmt.Errorf("No API Gateway Usage Plan ID is set")293 }294 conn := testAccProvider.Meta().(*AWSClient).apigateway295 req := &apigateway.GetUsagePlanInput{296 UsagePlanId: aws.String(rs.Primary.ID),297 }298 up, err := conn.GetUsagePlan(req)299 if err != nil {300 return err301 }302 if *up.Id != rs.Primary.ID {303 return fmt.Errorf("APIGateway Usage Plan not found")304 }305 *res = *up306 return nil307 }308}309func testAccCheckAWSAPIGatewayUsagePlanDestroy(s *terraform.State) error {310 conn := testAccProvider.Meta().(*AWSClient).apigateway311 for _, rs := range s.RootModule().Resources {312 if rs.Type != "aws_api_gateway_usage_plan" {313 continue314 }315 req := &apigateway.GetUsagePlanInput{316 UsagePlanId: aws.String(s.RootModule().Resources["aws_api_gateway_rest_api.test"].Primary.ID),317 }318 describe, err := conn.GetUsagePlan(req)319 if err == nil {320 if describe.Id != nil && *describe.Id == rs.Primary.ID {321 return fmt.Errorf("API Gateway Usage Plan still exists")322 }323 }324 aws2err, ok := err.(awserr.Error)325 if !ok {326 return err327 }328 if aws2err.Code() != "NotFoundException" {329 return err330 }331 return nil332 }333 return nil334}335const testAccAWSAPIGatewayUsagePlanConfig = `336resource "aws_api_gateway_rest_api" "test" {337 name = "test"338}339resource "aws_api_gateway_resource" "test" {340 rest_api_id = "${aws_api_gateway_rest_api.test.id}"341 parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}"342 path_part = "test"343}344resource "aws_api_gateway_method" "test" {345 rest_api_id = "${aws_api_gateway_rest_api.test.id}"346 resource_id = "${aws_api_gateway_resource.test.id}"347 http_method = "GET"348 authorization = "NONE"349}350resource "aws_api_gateway_method_response" "error" {351 rest_api_id = "${aws_api_gateway_rest_api.test.id}"352 resource_id = "${aws_api_gateway_resource.test.id}"353 http_method = "${aws_api_gateway_method.test.http_method}"354 status_code = "400"355}356resource "aws_api_gateway_integration" "test" {357 rest_api_id = "${aws_api_gateway_rest_api.test.id}"358 resource_id = "${aws_api_gateway_resource.test.id}"359 http_method = "${aws_api_gateway_method.test.http_method}"360 type = "HTTP"361 uri = "https://www.google.de"362 integration_http_method = "GET"363}364resource "aws_api_gateway_integration_response" "test" {365 rest_api_id = "${aws_api_gateway_rest_api.test.id}"366 resource_id = "${aws_api_gateway_resource.test.id}"367 http_method = "${aws_api_gateway_integration.test.http_method}"368 status_code = "${aws_api_gateway_method_response.error.status_code}"369}370resource "aws_api_gateway_deployment" "test" {371 depends_on = ["aws_api_gateway_integration.test"]372 rest_api_id = "${aws_api_gateway_rest_api.test.id}"373 stage_name = "test"374 description = "This is a test"375 variables = {376 "a" = "2"377 }378}379resource "aws_api_gateway_deployment" "foo" {380 depends_on = ["aws_api_gateway_integration.test"]381 rest_api_id = "${aws_api_gateway_rest_api.test.id}"382 stage_name = "foo"383 description = "This is a prod stage"384}385`386func testAccAWSApiGatewayUsagePlanBasicConfig(rName string) string {387 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`388resource "aws_api_gateway_usage_plan" "main" {389 name = "%s"390}391`, rName)392}393func testAccAWSApiGatewayUsagePlanDescriptionConfig(rName string) string {394 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`395resource "aws_api_gateway_usage_plan" "main" {396 name = "%s"397 description = "This is a description"398}399`, rName)400}401func testAccAWSApiGatewayUsagePlanDescriptionUpdatedConfig(rName string) string {402 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`403resource "aws_api_gateway_usage_plan" "main" {404 name = "%s"405 description = "This is a new description"406}407`, rName)408}409func testAccAWSApiGatewayUsagePlanProductCodeConfig(rName string) string {410 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`411resource "aws_api_gateway_usage_plan" "main" {412 name = "%s"413 product_code = "MYCODE"414}415`, rName)416}417func testAccAWSApiGatewayUsagePlanProductCodeUpdatedConfig(rName string) string {418 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`419resource "aws_api_gateway_usage_plan" "main" {420 name = "%s"421 product_code = "MYCODE2"422}423`, rName)424}425func testAccAWSApiGatewayUsagePlanBasicUpdatedConfig(rName string) string {426 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`427resource "aws_api_gateway_usage_plan" "main" {428 name = "%s"429}430`, rName)431}432func testAccAWSApiGatewayUsagePlanThrottlingConfig(rName string) string {433 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`434resource "aws_api_gateway_usage_plan" "main" {435 name = "%s"436 throttle_settings {437 burst_limit = 2438 rate_limit = 5439 }440}441`, rName)442}443func testAccAWSApiGatewayUsagePlanThrottlingModifiedConfig(rName string) string {444 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`445resource "aws_api_gateway_usage_plan" "main" {446 name = "%s"447 throttle_settings {448 burst_limit = 3449 rate_limit = 6450 }451}452`, rName)453}454func testAccAWSApiGatewayUsagePlanQuotaConfig(rName string) string {455 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`456resource "aws_api_gateway_usage_plan" "main" {457 name = "%s"458 quota_settings {459 limit = 100460 offset = 6461 period = "WEEK"462 }463}464`, rName)465}466func testAccAWSApiGatewayUsagePlanQuotaModifiedConfig(rName string) string {467 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`468resource "aws_api_gateway_usage_plan" "main" {469 name = "%s"470 quota_settings {471 limit = 200472 offset = 20473 period = "MONTH"474 }475}476`, rName)477}478func testAccAWSApiGatewayUsagePlanApiStagesConfig(rName string) string {479 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`480resource "aws_api_gateway_usage_plan" "main" {481 name = "%s"482 api_stages {483 api_id = "${aws_api_gateway_rest_api.test.id}"484 stage = "${aws_api_gateway_deployment.test.stage_name}"485 }486}487`, rName)488}489func testAccAWSApiGatewayUsagePlanApiStagesModifiedConfig(rName string) string {490 return fmt.Sprintf(testAccAWSAPIGatewayUsagePlanConfig+`491resource "aws_api_gateway_usage_plan" "main" {492 name = "%s"493 api_stages {494 api_id = "${aws_api_gateway_rest_api.test.id}"495 stage = "${aws_api_gateway_deployment.foo.stage_name}"496 }497}498`, rName)499}...
imports_test.go
Source:imports_test.go
...9 "go/parser"10 "go/token"11 "reflect"12 "strconv"13 "testing"14)15var fset = token.NewFileSet()16func parse(t *testing.T, name, in string) *ast.File {17 file, err := parser.ParseFile(fset, name, in, parser.ParseComments)18 if err != nil {19 t.Fatalf("%s parse: %v", name, err)20 }21 return file22}23func print(t *testing.T, name string, f *ast.File) string {24 var buf bytes.Buffer25 if err := format.Node(&buf, fset, f); err != nil {26 t.Fatalf("%s gofmt: %v", name, err)27 }28 return string(buf.Bytes())29}30type test struct {31 name string32 renamedPkg string33 pkg string34 in string35 out string36 broken bool // known broken37}38var addTests = []test{39 {40 name: "leave os alone",41 pkg: "os",42 in: `package main43import (44 "os"45)46`,47 out: `package main48import (49 "os"50)51`,52 },53 {54 name: "import.1",55 pkg: "os",56 in: `package main57`,58 out: `package main59import "os"60`,61 },62 {63 name: "import.2",64 pkg: "os",65 in: `package main66// Comment67import "C"68`,69 out: `package main70// Comment71import "C"72import "os"73`,74 },75 {76 name: "import.3",77 pkg: "os",78 in: `package main79// Comment80import "C"81import (82 "io"83 "utf8"84)85`,86 out: `package main87// Comment88import "C"89import (90 "io"91 "os"92 "utf8"93)94`,95 },96 {97 name: "import.17",98 pkg: "x/y/z",99 in: `package main100// Comment101import "C"102import (103 "a"104 "b"105 "x/w"106 "d/f"107)108`,109 out: `package main110// Comment111import "C"112import (113 "a"114 "b"115 "x/w"116 "x/y/z"117 "d/f"118)119`,120 },121 {122 name: "import into singular group",123 pkg: "bytes",124 in: `package main125import "os"126`,127 out: `package main128import (129 "bytes"130 "os"131)132`,133 },134 {135 name: "import into singular group with comment",136 pkg: "bytes",137 in: `package main138import /* why */ /* comment here? */ "os"139`,140 out: `package main141import /* why */ /* comment here? */ (142 "bytes"143 "os"144)145`,146 },147 {148 name: "import into group with leading comment",149 pkg: "strings",150 in: `package main151import (152 // comment before bytes153 "bytes"154 "os"155)156`,157 out: `package main158import (159 // comment before bytes160 "bytes"161 "os"162 "strings"163)164`,165 },166 {167 name: "",168 renamedPkg: "fmtpkg",169 pkg: "fmt",170 in: `package main171import "os"172`,173 out: `package main174import (175 fmtpkg "fmt"176 "os"177)178`,179 },180 {181 name: "struct comment",182 pkg: "time",183 in: `package main184// This is a comment before a struct.185type T struct {186 t time.Time187}188`,189 out: `package main190import "time"191// This is a comment before a struct.192type T struct {193 t time.Time194}195`,196 },197 {198 name: "issue 8729 import C",199 pkg: "time",200 in: `package main201import "C"202// comment203type T time.Time204`,205 out: `package main206import "C"207import "time"208// comment209type T time.Time210`,211 },212 {213 name: "issue 8729 empty import",214 pkg: "time",215 in: `package main216import ()217// comment218type T time.Time219`,220 out: `package main221import "time"222// comment223type T time.Time224`,225 },226 {227 name: "issue 8729 comment on package line",228 pkg: "time",229 in: `package main // comment230type T time.Time231`,232 out: `package main // comment233import "time"234type T time.Time235`,236 },237 {238 name: "issue 8729 comment after package",239 pkg: "time",240 in: `package main241// comment242type T time.Time243`,244 out: `package main245import "time"246// comment247type T time.Time248`,249 },250 {251 name: "issue 8729 comment before and on package line",252 pkg: "time",253 in: `// comment before254package main // comment on255type T time.Time256`,257 out: `// comment before258package main // comment on259import "time"260type T time.Time261`,262 },263 // Issue 9961: Match prefixes using path segments rather than bytes264 {265 name: "issue 9961",266 pkg: "regexp",267 in: `package main268import (269 "flag"270 "testing"271 "rsc.io/p"272)273`,274 out: `package main275import (276 "flag"277 "regexp"278 "testing"279 "rsc.io/p"280)281`,282 },283}284func TestAddImport(t *testing.T) {285 for _, test := range addTests {286 file := parse(t, test.name, test.in)287 var before bytes.Buffer288 ast.Fprint(&before, fset, file, nil)289 AddNamedImport(fset, file, test.renamedPkg, test.pkg)290 if got := print(t, test.name, file); got != test.out {291 if test.broken {292 t.Logf("%s is known broken:\ngot: %s\nwant: %s", test.name, got, test.out)293 } else {294 t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)295 }296 var after bytes.Buffer297 ast.Fprint(&after, fset, file, nil)298 t.Logf("AST before:\n%s\nAST after:\n%s\n", before.String(), after.String())299 }300 }301}302func TestDoubleAddImport(t *testing.T) {303 file := parse(t, "doubleimport", "package main\n")304 AddImport(fset, file, "os")305 AddImport(fset, file, "bytes")306 want := `package main307import (308 "bytes"309 "os"310)311`312 if got := print(t, "doubleimport", file); got != want {313 t.Errorf("got: %s\nwant: %s", got, want)314 }315}316// Part of issue 8729.317func TestDoubleAddImportWithDeclComment(t *testing.T) {318 file := parse(t, "doubleimport", `package main319import (320)321// comment322type I int323`)324 // The AddImport order here matters.325 AddImport(fset, file, "llvm.org/llgo/third_party/gotools/go/ast/astutil")326 AddImport(fset, file, "os")327 want := `package main328import (329 "llvm.org/llgo/third_party/gotools/go/ast/astutil"330 "os"331)332// comment333type I int334`335 if got := print(t, "doubleimport_with_decl_comment", file); got != want {336 t.Errorf("got: %s\nwant: %s", got, want)337 }338}339var deleteTests = []test{340 {341 name: "import.4",342 pkg: "os",343 in: `package main344import (345 "os"346)347`,348 out: `package main349`,350 },351 {352 name: "import.5",353 pkg: "os",354 in: `package main355// Comment356import "C"357import "os"358`,359 out: `package main360// Comment361import "C"362`,363 },364 {365 name: "import.6",366 pkg: "os",367 in: `package main368// Comment369import "C"370import (371 "io"372 "os"373 "utf8"374)375`,376 out: `package main377// Comment378import "C"379import (380 "io"381 "utf8"382)383`,384 },385 {386 name: "import.7",387 pkg: "io",388 in: `package main389import (390 "io" // a391 "os" // b392 "utf8" // c393)394`,395 out: `package main396import (397 // a398 "os" // b399 "utf8" // c400)401`,402 },403 {404 name: "import.8",405 pkg: "os",406 in: `package main407import (408 "io" // a409 "os" // b410 "utf8" // c411)412`,413 out: `package main414import (415 "io" // a416 // b417 "utf8" // c418)419`,420 },421 {422 name: "import.9",423 pkg: "utf8",424 in: `package main425import (426 "io" // a427 "os" // b428 "utf8" // c429)430`,431 out: `package main432import (433 "io" // a434 "os" // b435 // c436)437`,438 },439 {440 name: "import.10",441 pkg: "io",442 in: `package main443import (444 "io"445 "os"446 "utf8"447)448`,449 out: `package main450import (451 "os"452 "utf8"453)454`,455 },456 {457 name: "import.11",458 pkg: "os",459 in: `package main460import (461 "io"462 "os"463 "utf8"464)465`,466 out: `package main467import (468 "io"469 "utf8"470)471`,472 },473 {474 name: "import.12",475 pkg: "utf8",476 in: `package main477import (478 "io"479 "os"480 "utf8"481)482`,483 out: `package main484import (485 "io"486 "os"487)488`,489 },490 {491 name: "handle.raw.quote.imports",492 pkg: "os",493 in: "package main\n\nimport `os`",494 out: `package main495`,496 },497 {498 name: "import.13",499 pkg: "io",500 in: `package main501import (502 "fmt"503 "io"504 "os"505 "utf8"506 "go/format"507)508`,509 out: `package main510import (511 "fmt"512 "os"513 "utf8"514 "go/format"515)516`,517 },518 {519 name: "import.14",520 pkg: "io",521 in: `package main522import (523 "fmt" // a524 "io" // b525 "os" // c526 "utf8" // d527 "go/format" // e528)529`,530 out: `package main531import (532 "fmt" // a533 // b534 "os" // c535 "utf8" // d536 "go/format" // e537)538`,539 },540 {541 name: "import.15",542 pkg: "double",543 in: `package main544import (545 "double"546 "double"547)548`,549 out: `package main550`,551 },552 {553 name: "import.16",554 pkg: "bubble",555 in: `package main556import (557 "toil"558 "bubble"559 "bubble"560 "trouble"561)562`,563 out: `package main564import (565 "toil"566 "trouble"567)568`,569 },570 {571 name: "import.17",572 pkg: "quad",573 in: `package main574import (575 "quad"576 "quad"577)578import (579 "quad"580 "quad"581)582`,583 out: `package main584`,585 },586}587func TestDeleteImport(t *testing.T) {588 for _, test := range deleteTests {589 file := parse(t, test.name, test.in)590 DeleteImport(fset, file, test.pkg)591 if got := print(t, test.name, file); got != test.out {592 t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)593 }594 }595}596type rewriteTest struct {597 name string598 srcPkg string599 dstPkg string600 in string601 out string602}603var rewriteTests = []rewriteTest{604 {605 name: "import.13",606 srcPkg: "utf8",607 dstPkg: "encoding/utf8",608 in: `package main609import (610 "io"611 "os"612 "utf8" // thanks ken613)614`,615 out: `package main616import (617 "encoding/utf8" // thanks ken618 "io"619 "os"620)621`,622 },623 {624 name: "import.14",625 srcPkg: "asn1",626 dstPkg: "encoding/asn1",627 in: `package main628import (629 "asn1"630 "crypto"631 "crypto/rsa"632 _ "crypto/sha1"633 "crypto/x509"634 "crypto/x509/pkix"635 "time"636)637var x = 1638`,639 out: `package main640import (641 "crypto"642 "crypto/rsa"643 _ "crypto/sha1"644 "crypto/x509"645 "crypto/x509/pkix"646 "encoding/asn1"647 "time"648)649var x = 1650`,651 },652 {653 name: "import.15",654 srcPkg: "url",655 dstPkg: "net/url",656 in: `package main657import (658 "bufio"659 "net"660 "path"661 "url"662)663var x = 1 // comment on x, not on url664`,665 out: `package main666import (667 "bufio"668 "net"669 "net/url"670 "path"671)672var x = 1 // comment on x, not on url673`,674 },675 {676 name: "import.16",677 srcPkg: "http",678 dstPkg: "net/http",679 in: `package main680import (681 "flag"682 "http"683 "log"684 "text/template"685)686var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18687`,688 out: `package main689import (690 "flag"691 "log"692 "net/http"693 "text/template"694)695var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18696`,697 },698}699func TestRewriteImport(t *testing.T) {700 for _, test := range rewriteTests {701 file := parse(t, test.name, test.in)702 RewriteImport(fset, file, test.srcPkg, test.dstPkg)703 if got := print(t, test.name, file); got != test.out {704 t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)705 }706 }707}708var importsTests = []struct {709 name string710 in string711 want [][]string712}{713 {714 name: "no packages",715 in: `package foo716`,717 want: nil,718 },719 {720 name: "one group",721 in: `package foo722import (723 "fmt"724 "testing"725)726`,727 want: [][]string{{"fmt", "testing"}},728 },729 {730 name: "four groups",731 in: `package foo732import "C"733import (734 "fmt"735 "testing"736 "appengine"737 "myproject/mylib1"738 "myproject/mylib2"739)740`,741 want: [][]string{742 {"C"},743 {"fmt", "testing"},744 {"appengine"},745 {"myproject/mylib1", "myproject/mylib2"},746 },747 },748 {749 name: "multiple factored groups",750 in: `package foo751import (752 "fmt"753 "testing"754 "appengine"755)756import (757 "reflect"758 "bytes"759)760`,761 want: [][]string{762 {"fmt", "testing"},763 {"appengine"},764 {"reflect"},765 {"bytes"},766 },767 },768}769func unquote(s string) string {770 res, err := strconv.Unquote(s)771 if err != nil {772 return "could_not_unquote"773 }774 return res775}776func TestImports(t *testing.T) {777 fset := token.NewFileSet()778 for _, test := range importsTests {779 f, err := parser.ParseFile(fset, "test.go", test.in, 0)780 if err != nil {781 t.Errorf("%s: %v", test.name, err)782 continue783 }784 var got [][]string785 for _, group := range Imports(fset, f) {786 var b []string787 for _, spec := range group {788 b = append(b, unquote(spec.Path.Value))789 }790 got = append(got, b)791 }792 if !reflect.DeepEqual(got, test.want) {793 t.Errorf("Imports(%s)=%v, want %v", test.name, got, test.want)794 }795 }796}...
testmain.go
Source:testmain.go
2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package ssa5// CreateTestMainPackage synthesizes a main package that runs all the6// tests of the supplied packages.7// It is closely coupled to $GOROOT/src/cmd/go/test.go and $GOROOT/src/testing.8import (9 "go/ast"10 "go/token"11 "os"12 "sort"13 "strings"14 "llvm.org/llgo/third_party/gotools/go/exact"15 "llvm.org/llgo/third_party/gotools/go/types"16)17// FindTests returns the list of packages that define at least one Test,18// Example or Benchmark function (as defined by "go test"), and the19// lists of all such functions.20//21func FindTests(pkgs []*Package) (testpkgs []*Package, tests, benchmarks, examples []*Function) {22 if len(pkgs) == 0 {23 return24 }25 prog := pkgs[0].Prog26 // The first two of these may be nil: if the program doesn't import "testing",27 // it can't contain any tests, but it may yet contain Examples.28 var testSig *types.Signature // func(*testing.T)29 var benchmarkSig *types.Signature // func(*testing.B)30 var exampleSig = types.NewSignature(nil, nil, nil, nil, false) // func()31 // Obtain the types from the parameters of testing.Main().32 if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {33 params := testingPkg.Func("Main").Signature.Params()34 testSig = funcField(params.At(1).Type())35 benchmarkSig = funcField(params.At(2).Type())36 }37 seen := make(map[*Package]bool)38 for _, pkg := range pkgs {39 if pkg.Prog != prog {40 panic("wrong Program")41 }42 // TODO(adonovan): use a stable order, e.g. lexical.43 for _, mem := range pkg.Members {44 if f, ok := mem.(*Function); ok &&45 ast.IsExported(f.Name()) &&46 strings.HasSuffix(prog.Fset.Position(f.Pos()).Filename, "_test.go") {47 switch {48 case testSig != nil && isTestSig(f, "Test", testSig):49 tests = append(tests, f)50 case benchmarkSig != nil && isTestSig(f, "Benchmark", benchmarkSig):51 benchmarks = append(benchmarks, f)52 case isTestSig(f, "Example", exampleSig):53 examples = append(examples, f)54 default:55 continue56 }57 if !seen[pkg] {58 seen[pkg] = true59 testpkgs = append(testpkgs, pkg)60 }61 }62 }63 }64 return65}66// Like isTest, but checks the signature too.67func isTestSig(f *Function, prefix string, sig *types.Signature) bool {68 return isTest(f.Name(), prefix) && types.Identical(f.Signature, sig)69}70// If non-nil, testMainStartBodyHook is called immediately after71// startBody for main.init and main.main, making it easy for users to72// add custom imports and initialization steps for proprietary build73// systems that don't exactly follow 'go test' conventions.74var testMainStartBodyHook func(*Function)75// CreateTestMainPackage creates and returns a synthetic "main"76// package that runs all the tests of the supplied packages, similar77// to the one that would be created by the 'go test' tool.78//79// It returns nil if the program contains no tests.80//81func (prog *Program) CreateTestMainPackage(pkgs ...*Package) *Package {82 pkgs, tests, benchmarks, examples := FindTests(pkgs)83 if len(pkgs) == 0 {84 return nil85 }86 testmain := &Package{87 Prog: prog,88 Members: make(map[string]Member),89 values: make(map[types.Object]Value),90 Object: types.NewPackage("test$main", "main"),91 }92 // Build package's init function.93 init := &Function{94 name: "init",95 Signature: new(types.Signature),96 Synthetic: "package initializer",97 Pkg: testmain,98 Prog: prog,99 }100 init.startBody()101 if testMainStartBodyHook != nil {102 testMainStartBodyHook(init)103 }104 // Initialize packages to test.105 var pkgpaths []string106 for _, pkg := range pkgs {107 var v Call108 v.Call.Value = pkg.init109 v.setType(types.NewTuple())110 init.emit(&v)111 pkgpaths = append(pkgpaths, pkg.Object.Path())112 }113 sort.Strings(pkgpaths)114 init.emit(new(Return))115 init.finishBody()116 testmain.init = init117 testmain.Object.MarkComplete()118 testmain.Members[init.name] = init119 // For debugging convenience, define an unexported const120 // that enumerates the packages.121 packagesConst := types.NewConst(token.NoPos, testmain.Object, "packages", tString,122 exact.MakeString(strings.Join(pkgpaths, " ")))123 memberFromObject(testmain, packagesConst, nil)124 // Create main *types.Func and *ssa.Function125 mainFunc := types.NewFunc(token.NoPos, testmain.Object, "main", new(types.Signature))126 memberFromObject(testmain, mainFunc, nil)127 main := testmain.Func("main")128 main.Synthetic = "test main function"129 main.startBody()130 if testMainStartBodyHook != nil {131 testMainStartBodyHook(main)132 }133 if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {134 testingMain := testingPkg.Func("Main")135 testingMainParams := testingMain.Signature.Params()136 // The generated code is as if compiled from this:137 //138 // func main() {139 // match := func(_, _ string) (bool, error) { return true, nil }140 // tests := []testing.InternalTest{{"TestFoo", TestFoo}, ...}141 // benchmarks := []testing.InternalBenchmark{...}142 // examples := []testing.InternalExample{...}143 // testing.Main(match, tests, benchmarks, examples)144 // }145 matcher := &Function{146 name: "matcher",147 Signature: testingMainParams.At(0).Type().(*types.Signature),148 Synthetic: "test matcher predicate",149 parent: main,150 Pkg: testmain,151 Prog: prog,152 }153 main.AnonFuncs = append(main.AnonFuncs, matcher)154 matcher.startBody()155 matcher.emit(&Return{Results: []Value{vTrue, nilConst(types.Universe.Lookup("error").Type())}})156 matcher.finishBody()157 // Emit call: testing.Main(matcher, tests, benchmarks, examples).158 var c Call159 c.Call.Value = testingMain160 c.Call.Args = []Value{161 matcher,162 testMainSlice(main, tests, testingMainParams.At(1).Type()),163 testMainSlice(main, benchmarks, testingMainParams.At(2).Type()),164 testMainSlice(main, examples, testingMainParams.At(3).Type()),165 }166 emitTailCall(main, &c)167 } else {168 // The program does not import "testing", but FindTests169 // returned non-nil, which must mean there were Examples170 // but no Tests or Benchmarks.171 // We'll simply call them from testmain.main; this will172 // ensure they don't panic, but will not check any173 // "Output:" comments.174 for _, eg := range examples {175 var c Call176 c.Call.Value = eg177 c.setType(types.NewTuple())178 main.emit(&c)179 }180 main.emit(&Return{})181 main.currentBlock = nil182 }183 main.finishBody()184 testmain.Members["main"] = main185 if prog.mode&PrintPackages != 0 {186 printMu.Lock()187 testmain.WriteTo(os.Stdout)188 printMu.Unlock()189 }190 if prog.mode&SanityCheckFunctions != 0 {191 sanityCheckPackage(testmain)192 }193 prog.packages[testmain.Object] = testmain194 return testmain195}196// testMainSlice emits to fn code to construct a slice of type slice197// (one of []testing.Internal{Test,Benchmark,Example}) for all198// functions in testfuncs. It returns the slice value.199//200func testMainSlice(fn *Function, testfuncs []*Function, slice types.Type) Value {201 if testfuncs == nil {202 return nilConst(slice)203 }204 tElem := slice.(*types.Slice).Elem()205 tPtrString := types.NewPointer(tString)206 tPtrElem := types.NewPointer(tElem)207 tPtrFunc := types.NewPointer(funcField(slice))208 // Emit: array = new [n]testing.InternalTest209 tArray := types.NewArray(tElem, int64(len(testfuncs)))210 array := emitNew(fn, tArray, token.NoPos)211 array.Comment = "test main"212 for i, testfunc := range testfuncs {213 // Emit: pitem = &array[i]214 ia := &IndexAddr{X: array, Index: intConst(int64(i))}215 ia.setType(tPtrElem)216 pitem := fn.emit(ia)217 // Emit: pname = &pitem.Name218 fa := &FieldAddr{X: pitem, Field: 0} // .Name219 fa.setType(tPtrString)220 pname := fn.emit(fa)221 // Emit: *pname = "testfunc"222 emitStore(fn, pname, stringConst(testfunc.Name()), token.NoPos)223 // Emit: pfunc = &pitem.F224 fa = &FieldAddr{X: pitem, Field: 1} // .F225 fa.setType(tPtrFunc)226 pfunc := fn.emit(fa)227 // Emit: *pfunc = testfunc228 emitStore(fn, pfunc, testfunc, token.NoPos)229 }230 // Emit: slice array[:]231 sl := &Slice{X: array}232 sl.setType(slice)233 return fn.emit(sl)234}235// Given the type of one of the three slice parameters of testing.Main,236// returns the function type.237func funcField(slice types.Type) *types.Signature {238 return slice.(*types.Slice).Elem().Underlying().(*types.Struct).Field(1).Type().(*types.Signature)239}240// Plundered from $GOROOT/src/cmd/go/test.go241// isTest tells whether name looks like a test (or benchmark, according to prefix).242// It is a Test (say) if there is a character after Test that is not a lower-case letter.243// We don't want TesticularCancer.244func isTest(name, prefix string) bool {245 if !strings.HasPrefix(name, prefix) {246 return false247 }248 if len(name) == len(prefix) { // "Test" is ok249 return true250 }251 return ast.IsExported(name[len(prefix):])252}...
output_test.go
Source:output_test.go
2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4//go:build race5// +build race6package race_test7import (8 "fmt"9 "internal/testenv"10 "os"11 "os/exec"12 "path/filepath"13 "regexp"14 "runtime"15 "strings"16 "testing"17)18func TestOutput(t *testing.T) {19 pkgdir := t.TempDir()20 out, err := exec.Command(testenv.GoToolPath(t), "install", "-race", "-pkgdir="+pkgdir, "testing").CombinedOutput()21 if err != nil {22 t.Fatalf("go install -race: %v\n%s", err, out)23 }24 for _, test := range tests {25 if test.goos != "" && test.goos != runtime.GOOS {26 t.Logf("test %v runs only on %v, skipping: ", test.name, test.goos)27 continue28 }29 dir := t.TempDir()30 source := "main.go"31 if test.run == "test" {32 source = "main_test.go"33 }34 src := filepath.Join(dir, source)35 f, err := os.Create(src)36 if err != nil {37 t.Fatalf("failed to create file: %v", err)38 }39 _, err = f.WriteString(test.source)40 if err != nil {41 f.Close()42 t.Fatalf("failed to write: %v", err)43 }44 if err := f.Close(); err != nil {45 t.Fatalf("failed to close file: %v", err)46 }47 cmd := exec.Command(testenv.GoToolPath(t), test.run, "-race", "-pkgdir="+pkgdir, src)48 // GODEBUG spoils program output, GOMAXPROCS makes it flaky.49 for _, env := range os.Environ() {50 if strings.HasPrefix(env, "GODEBUG=") ||51 strings.HasPrefix(env, "GOMAXPROCS=") ||52 strings.HasPrefix(env, "GORACE=") {53 continue54 }55 cmd.Env = append(cmd.Env, env)56 }57 cmd.Env = append(cmd.Env,58 "GOMAXPROCS=1", // see comment in race_test.go59 "GORACE="+test.gorace,60 )61 got, _ := cmd.CombinedOutput()62 matched := false63 for _, re := range test.re {64 if regexp.MustCompile(re).MatchString(string(got)) {65 matched = true66 break67 }68 }69 if !matched {70 exp := fmt.Sprintf("expect:\n%v\n", test.re[0])71 if len(test.re) > 1 {72 exp = fmt.Sprintf("expected one of %d patterns:\n",73 len(test.re))74 for k, re := range test.re {75 exp += fmt.Sprintf("pattern %d:\n%v\n", k, re)76 }77 }78 t.Fatalf("failed test case %v, %sgot:\n%s",79 test.name, exp, got)80 }81 }82}83var tests = []struct {84 name string85 run string86 goos string87 gorace string88 source string89 re []string90}{91 {"simple", "run", "", "atexit_sleep_ms=0", `92package main93import "time"94var xptr *int95var donechan chan bool96func main() {97 done := make(chan bool)98 x := 099 startRacer(&x, done)100 store(&x, 43)101 <-done102}103func store(x *int, v int) {104 *x = v105}106func startRacer(x *int, done chan bool) {107 xptr = x108 donechan = done109 go racer()110}111func racer() {112 time.Sleep(10*time.Millisecond)113 store(xptr, 42)114 donechan <- true115}116`, []string{`==================117WARNING: DATA RACE118Write at 0x[0-9,a-f]+ by goroutine [0-9]:119 main\.store\(\)120 .+/main\.go:14 \+0x[0-9,a-f]+121 main\.racer\(\)122 .+/main\.go:23 \+0x[0-9,a-f]+123Previous write at 0x[0-9,a-f]+ by main goroutine:124 main\.store\(\)125 .+/main\.go:14 \+0x[0-9,a-f]+126 main\.main\(\)127 .+/main\.go:10 \+0x[0-9,a-f]+128Goroutine [0-9] \(running\) created at:129 main\.startRacer\(\)130 .+/main\.go:19 \+0x[0-9,a-f]+131 main\.main\(\)132 .+/main\.go:9 \+0x[0-9,a-f]+133==================134Found 1 data race\(s\)135exit status 66136`}},137 {"exitcode", "run", "", "atexit_sleep_ms=0 exitcode=13", `138package main139func main() {140 done := make(chan bool)141 x := 0142 go func() {143 x = 42144 done <- true145 }()146 x = 43147 <-done148}149`, []string{`exit status 13`}},150 {"strip_path_prefix", "run", "", "atexit_sleep_ms=0 strip_path_prefix=/main.", `151package main152func main() {153 done := make(chan bool)154 x := 0155 go func() {156 x = 42157 done <- true158 }()159 x = 43160 <-done161}162`, []string{`163 go:7 \+0x[0-9,a-f]+164`}},165 {"halt_on_error", "run", "", "atexit_sleep_ms=0 halt_on_error=1", `166package main167func main() {168 done := make(chan bool)169 x := 0170 go func() {171 x = 42172 done <- true173 }()174 x = 43175 <-done176}177`, []string{`178==================179exit status 66180`}},181 {"test_fails_on_race", "test", "", "atexit_sleep_ms=0", `182package main_test183import "testing"184func TestFail(t *testing.T) {185 done := make(chan bool)186 x := 0187 _ = x188 go func() {189 x = 42190 done <- true191 }()192 x = 43193 <-done194 t.Log(t.Failed())195}196`, []string{`197==================198--- FAIL: TestFail \(0...s\)199.*main_test.go:14: true200.*testing.go:.*: race detected during execution of test201FAIL`}},202 {"slicebytetostring_pc", "run", "", "atexit_sleep_ms=0", `203package main204func main() {205 done := make(chan string)206 data := make([]byte, 10)207 go func() {208 done <- string(data)209 }()210 data[0] = 1211 <-done212}213`, []string{`214 runtime\.slicebytetostring\(\)215 .*/runtime/string\.go:.*216 main\.main\.func1\(\)217 .*/main.go:7`}},218 // Test for https://golang.org/issue/33309219 {"midstack_inlining_traceback", "run", "linux", "atexit_sleep_ms=0", `220package main221var x int222var c chan int223func main() {224 c = make(chan int)225 go f()226 x = 1227 <-c228}229func f() {230 g(c)231}232func g(c chan int) {233 h(c)234}235func h(c chan int) {236 c <- x237}238`, []string{`==================239WARNING: DATA RACE240Read at 0x[0-9,a-f]+ by goroutine [0-9]:241 main\.h\(\)242 .+/main\.go:22 \+0x[0-9,a-f]+243 main\.g\(\)244 .+/main\.go:18 \+0x[0-9,a-f]+245 main\.f\(\)246 .+/main\.go:14 \+0x[0-9,a-f]+247Previous write at 0x[0-9,a-f]+ by main goroutine:248 main\.main\(\)249 .+/main\.go:9 \+0x[0-9,a-f]+250Goroutine [0-9] \(running\) created at:251 main\.main\(\)252 .+/main\.go:8 \+0x[0-9,a-f]+253==================254Found 1 data race\(s\)255exit status 66256`}},257 // Test for https://golang.org/issue/17190258 {"external_cgo_thread", "run", "linux", "atexit_sleep_ms=0", `259package main260/*261#include <pthread.h>262typedef struct cb {263 int foo;264} cb;265extern void goCallback();266static inline void *threadFunc(void *p) {267 goCallback();268 return 0;269}270static inline void startThread(cb* c) {271 pthread_t th;272 pthread_create(&th, 0, threadFunc, 0);273}274*/275import "C"276var done chan bool277var racy int278//export goCallback279func goCallback() {280 racy++281 done <- true282}283func main() {284 done = make(chan bool)285 var c C.cb286 C.startThread(&c)287 racy++288 <- done289}290`, []string{`==================291WARNING: DATA RACE292Read at 0x[0-9,a-f]+ by main goroutine:293 main\.main\(\)294 .*/main\.go:34 \+0x[0-9,a-f]+295Previous write at 0x[0-9,a-f]+ by goroutine [0-9]:296 main\.goCallback\(\)297 .*/main\.go:27 \+0x[0-9,a-f]+298 _cgoexp_[0-9a-z]+_goCallback\(\)299 .*_cgo_gotypes\.go:[0-9]+ \+0x[0-9,a-f]+300 _cgoexp_[0-9a-z]+_goCallback\(\)301 <autogenerated>:1 \+0x[0-9,a-f]+302Goroutine [0-9] \(running\) created at:303 runtime\.newextram\(\)304 .*/runtime/proc.go:[0-9]+ \+0x[0-9,a-f]+305==================`,306 `==================307WARNING: DATA RACE308Read at 0x[0-9,a-f]+ by .*:309 main\..*310 .*/main\.go:[0-9]+ \+0x[0-9,a-f]+(?s).*311Previous write at 0x[0-9,a-f]+ by .*:312 main\..*313 .*/main\.go:[0-9]+ \+0x[0-9,a-f]+(?s).*314Goroutine [0-9] \(running\) created at:315 runtime\.newextram\(\)316 .*/runtime/proc.go:[0-9]+ \+0x[0-9,a-f]+317==================`}},318 {"second_test_passes", "test", "", "atexit_sleep_ms=0", `319package main_test320import "testing"321func TestFail(t *testing.T) {322 done := make(chan bool)323 x := 0324 _ = x325 go func() {326 x = 42327 done <- true328 }()329 x = 43330 <-done331}332func TestPass(t *testing.T) {333}334`, []string{`335==================336--- FAIL: TestFail \(0...s\)337.*testing.go:.*: race detected during execution of test338FAIL`}},339 {"mutex", "run", "", "atexit_sleep_ms=0", `340package main341import (342 "sync"343 "fmt"344)345func main() {346 c := make(chan bool, 1)347 threads := 1348 iterations := 20000349 data := 0350 var wg sync.WaitGroup351 for i := 0; i < threads; i++ {...
code_test.go
Source:code_test.go
...5import (6 "fmt"7 "html/template"8 "strings"9 "testing"10)11func TestParseCode(t *testing.T) {12 // Enable play but revert the change at the end.13 defer func(play bool) { PlayEnabled = play }(PlayEnabled)14 PlayEnabled = true15 helloTest := []byte(`16package main17import "fmt"18func main() {19 fmt.Println("hello, test")20}21`)22 helloTestHTML := template.HTML(`23<pre><span num="2">package main</span>24<span num="3"></span>25<span num="4">import "fmt"</span>26<span num="5"></span>27<span num="6">func main() {</span>28<span num="7"> fmt.Println("hello, test")</span>29<span num="8">}</span>30</pre>31`)32 helloTestHL := []byte(`33package main34import "fmt" // HLimport35func main() { // HLfunc36 fmt.Println("hello, test") // HL37}38`)39 highlight := func(h template.HTML, s string) template.HTML {40 return template.HTML(strings.Replace(string(h), s, "<b>"+s+"</b>", -1))41 }42 read := func(b []byte, err error) func(string) ([]byte, error) {43 return func(string) ([]byte, error) { return b, err }44 }45 tests := []struct {46 name string47 readFile func(string) ([]byte, error)48 sourceFile string49 cmd string50 err string51 Code52 }{53 {54 name: "all code, no play",55 readFile: read(helloTest, nil),56 sourceFile: "main.go",57 cmd: ".code main.go",58 Code: Code{59 Ext: ".go",60 FileName: "main.go",61 Raw: helloTest,62 Text: helloTestHTML,63 },64 },65 {66 name: "all code, play",67 readFile: read(helloTest, nil),68 sourceFile: "main.go",69 cmd: ".play main.go",70 Code: Code{71 Ext: ".go",72 FileName: "main.go",73 Play: true,74 Raw: helloTest,75 Text: helloTestHTML,76 },77 },78 {79 name: "all code, highlighted",80 readFile: read(helloTestHL, nil),81 sourceFile: "main.go",82 cmd: ".code main.go",83 Code: Code{84 Ext: ".go",85 FileName: "main.go",86 Raw: helloTestHL,87 Text: highlight(helloTestHTML, "fmt.Println("hello, test")"),88 },89 },90 {91 name: "highlight only func",92 readFile: read(helloTestHL, nil),93 sourceFile: "main.go",94 cmd: ".code main.go HLfunc",95 Code: Code{96 Ext: ".go",97 FileName: "main.go",98 Play: false,99 Raw: []byte("package main\n\nimport \"fmt\" // HLimport\n\nfunc main() { // HLfunc\n\tfmt.Println(\"hello, test\") // HL\n}"),100 Text: highlight(helloTestHTML, "func main() {"),101 },102 },103 {104 name: "bad highlight syntax",105 readFile: read(helloTest, nil),106 sourceFile: "main.go",107 cmd: ".code main.go HL",108 err: "invalid highlight syntax",109 },110 {111 name: "error reading file",112 readFile: read(nil, fmt.Errorf("nope")),113 sourceFile: "main.go",114 cmd: ".code main.go",115 err: "main.go:0: nope",116 },117 {118 name: "from func main to the end",119 readFile: read(helloTest, nil),120 sourceFile: "main.go",121 cmd: ".code main.go /func main/,",122 Code: Code{123 Ext: ".go",124 FileName: "main.go",125 Play: false,126 Raw: []byte("func main() {\n\tfmt.Println(\"hello, test\")\n}"),127 Text: "<pre><span num=\"6\">func main() {</span>\n<span num=\"7\"> fmt.Println("hello, test")</span>\n<span num=\"8\">}</span>\n</pre>",128 },129 },130 {131 name: "just func main",132 readFile: read(helloTest, nil),133 sourceFile: "main.go",134 cmd: ".code main.go /func main/",135 Code: Code{136 Ext: ".go",137 FileName: "main.go",138 Play: false,139 Raw: []byte("func main() {"),140 Text: "<pre><span num=\"6\">func main() {</span>\n</pre>",141 },142 },143 {144 name: "bad address",145 readFile: read(helloTest, nil),146 sourceFile: "main.go",147 cmd: ".code main.go /function main/",148 err: "main.go:0: no match for function main",149 },150 {151 name: "all code with numbers",152 readFile: read(helloTest, nil),153 sourceFile: "main.go",154 cmd: ".code -numbers main.go",155 Code: Code{156 Ext: ".go",157 FileName: "main.go",158 Raw: helloTest,159 // Replacing the first "<pre>"160 Text: "<pre class=\"numbers\">" + helloTestHTML[6:],161 },162 },163 {164 name: "all code editable",165 readFile: read(helloTest, nil),166 sourceFile: "main.go",167 cmd: ".code -edit main.go",168 Code: Code{169 Ext: ".go",170 FileName: "main.go",171 Raw: helloTest,172 Text: "<pre contenteditable=\"true\" spellcheck=\"false\">" + helloTestHTML[6:],173 },174 },175 }176 trimHTML := func(t template.HTML) string { return strings.TrimSpace(string(t)) }177 trimBytes := func(b []byte) string { return strings.TrimSpace(string(b)) }178 for _, tt := range tests {179 ctx := &Context{tt.readFile}180 e, err := parseCode(ctx, tt.sourceFile, 0, tt.cmd)181 if err != nil {182 if tt.err == "" {183 t.Errorf("%s: unexpected error %v", tt.name, err)184 } else if !strings.Contains(err.Error(), tt.err) {185 t.Errorf("%s: expected error %s; got %v", tt.name, tt.err, err)186 }187 continue188 }189 if tt.err != "" {190 t.Errorf("%s: expected error %s; but got none", tt.name, tt.err)191 continue192 }...
test
Using AI Code Generation
1import (2func main() {3 ret = max(a, b)4 fmt.Printf("Max value is : %d\n", ret)5}6func max(num1, num2 int) int {7 if (num1 > num2) {8 } else {9 }10}11import (12func main() {13 ret = max(a, b)14 fmt.Printf("Max value is : %d\n", ret)15}16func max(num1, num2 int) int {17 if (num1 > num2) {18 } else {19 }20}21import (22func main() {23 ret = max(a, b)24 fmt.Printf("Max value is : %d\n", ret)25}26func max(num1, num2 int) int {27 if (num1 > num2) {28 } else {29 }30}31import (32func main() {33 ret = max(a, b)34 fmt.Printf("Max value is : %d\n", ret)35}36func max(num1, num2 int) int {37 if (num1 > num2) {38 } else {39 }40}
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!!