| 25 | ) |
| 26 | |
| 27 | func TestURLOpener(t *testing.T) { |
| 28 | // This test will be skipped unless the project is set up with Terraform. |
| 29 | // Before running go test, run in this directory: |
| 30 | // |
| 31 | // terraform init |
| 32 | // terraform apply |
| 33 | |
| 34 | tfOut, err := terraform.ReadOutput(".") |
| 35 | if err != nil || len(tfOut) == 0 { |
| 36 | t.Skipf("Could not obtain harness info: %v", err) |
| 37 | } |
| 38 | project, _ := tfOut["project"].Value.(string) |
| 39 | region, _ := tfOut["region"].Value.(string) |
| 40 | instance, _ := tfOut["instance"].Value.(string) |
| 41 | username, _ := tfOut["username"].Value.(string) |
| 42 | password, _ := tfOut["password"].Value.(string) |
| 43 | databaseName, _ := tfOut["database"].Value.(string) |
| 44 | userEmail, _ := tfOut["user_email"].Value.(string) |
| 45 | if project == "" || region == "" || instance == "" || username == "" || databaseName == "" || userEmail == "" { |
| 46 | t.Fatalf("Missing one or more required Terraform outputs; got project=%q region=%q instance=%q username=%q database=%q userEmail=%q", project, region, instance, username, databaseName, userEmail) |
| 47 | } |
| 48 | tests := []struct { |
| 49 | name string |
| 50 | urlstr string |
| 51 | wantErr bool |
| 52 | }{ |
| 53 | { |
| 54 | name: "SuccessIam", |
| 55 | urlstr: fmt.Sprintf("gcppostgres://%s@%s/%s/%s/%s", userEmail, project, region, instance, databaseName), |
| 56 | }, |
| 57 | { |
| 58 | name: "SuccessBuiltin", |
| 59 | urlstr: fmt.Sprintf("gcppostgres://%s:%s@%s/%s/%s/%s", username, password, project, region, instance, databaseName), |
| 60 | }, |
| 61 | { |
| 62 | name: "SSLModeForbidden", |
| 63 | urlstr: fmt.Sprintf("gcppostgres://%s:%s@%s/%s/%s/%s?sslmode=require", username, password, project, region, instance, databaseName), |
| 64 | wantErr: true, |
| 65 | }, |
| 66 | } |
| 67 | |
| 68 | ctx := context.Background() |
| 69 | for _, test := range tests { |
| 70 | t.Run(test.name, func(t *testing.T) { |
| 71 | db, err := postgres.Open(ctx, test.urlstr) |
| 72 | if err != nil { |
| 73 | t.Log(err) |
| 74 | if !test.wantErr { |
| 75 | t.Fail() |
| 76 | } |
| 77 | return |
| 78 | } |
| 79 | if test.wantErr { |
| 80 | db.Close() |
| 81 | t.Fatal("Open succeeded; want error") |
| 82 | } |
| 83 | if err := db.Ping(); err != nil { |
| 84 | t.Error("Ping:", err) |