github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/random/resource_id_test.go (about)

     1  package random
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/hashicorp/terraform/helper/resource"
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  type idLens struct {
    12  	b64Len    int
    13  	b64UrlLen int
    14  	b64StdLen int
    15  	hexLen    int
    16  }
    17  
    18  func TestAccResourceID(t *testing.T) {
    19  	resource.Test(t, resource.TestCase{
    20  		PreCheck:  func() { testAccPreCheck(t) },
    21  		Providers: testAccProviders,
    22  		Steps: []resource.TestStep{
    23  			{
    24  				Config: testAccResourceIDConfig,
    25  				Check: resource.ComposeTestCheckFunc(
    26  					testAccResourceIDCheck("random_id.foo", &idLens{
    27  						b64Len:    6,
    28  						b64UrlLen: 6,
    29  						b64StdLen: 8,
    30  						hexLen:    8,
    31  					}),
    32  					testAccResourceIDCheck("random_id.bar", &idLens{
    33  						b64Len:    12,
    34  						b64UrlLen: 12,
    35  						b64StdLen: 14,
    36  						hexLen:    14,
    37  					}),
    38  				),
    39  			},
    40  		},
    41  	})
    42  }
    43  
    44  func testAccResourceIDCheck(id string, want *idLens) resource.TestCheckFunc {
    45  	return func(s *terraform.State) error {
    46  		rs, ok := s.RootModule().Resources[id]
    47  		if !ok {
    48  			return fmt.Errorf("Not found: %s", id)
    49  		}
    50  		if rs.Primary.ID == "" {
    51  			return fmt.Errorf("No ID is set")
    52  		}
    53  
    54  		b64Str := rs.Primary.Attributes["b64"]
    55  		b64UrlStr := rs.Primary.Attributes["b64_url"]
    56  		b64StdStr := rs.Primary.Attributes["b64_std"]
    57  		hexStr := rs.Primary.Attributes["hex"]
    58  		decStr := rs.Primary.Attributes["dec"]
    59  
    60  		if got, want := len(b64Str), want.b64Len; got != want {
    61  			return fmt.Errorf("base64 string length is %d; want %d", got, want)
    62  		}
    63  		if got, want := len(b64UrlStr), want.b64UrlLen; got != want {
    64  			return fmt.Errorf("base64 URL string length is %d; want %d", got, want)
    65  		}
    66  		if got, want := len(b64StdStr), want.b64StdLen; got != want {
    67  			return fmt.Errorf("base64 STD string length is %d; want %d", got, want)
    68  		}
    69  		if got, want := len(hexStr), want.hexLen; got != want {
    70  			return fmt.Errorf("hex string length is %d; want %d", got, want)
    71  		}
    72  		if len(decStr) < 1 {
    73  			return fmt.Errorf("decimal string is empty; want at least one digit")
    74  		}
    75  
    76  		return nil
    77  	}
    78  }
    79  
    80  const (
    81  	testAccResourceIDConfig = `
    82  resource "random_id" "foo" {
    83    byte_length = 4
    84  }
    85  
    86  resource "random_id" "bar" {
    87    byte_length = 4
    88  	prefix      = "cloud-"
    89  }
    90  `
    91  )