github.com/koding/terraform@v0.6.4-0.20170608090606-5d7e0339779d/builtin/providers/aws/resource_aws_sns_topic_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/aws/aws-sdk-go/aws"
     8  	"github.com/aws/aws-sdk-go/aws/awserr"
     9  	"github.com/aws/aws-sdk-go/service/sns"
    10  	"github.com/hashicorp/terraform/helper/acctest"
    11  	"github.com/hashicorp/terraform/helper/resource"
    12  	"github.com/hashicorp/terraform/terraform"
    13  	"github.com/jen20/awspolicyequivalence"
    14  )
    15  
    16  func TestAccAWSSNSTopic_basic(t *testing.T) {
    17  	rName := acctest.RandString(10)
    18  
    19  	resource.Test(t, resource.TestCase{
    20  		PreCheck:      func() { testAccPreCheck(t) },
    21  		IDRefreshName: "aws_sns_topic.test_topic",
    22  		Providers:     testAccProviders,
    23  		CheckDestroy:  testAccCheckAWSSNSTopicDestroy,
    24  		Steps: []resource.TestStep{
    25  			resource.TestStep{
    26  				Config: testAccAWSSNSTopicConfig(rName),
    27  				Check: resource.ComposeTestCheckFunc(
    28  					testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic"),
    29  				),
    30  			},
    31  		},
    32  	})
    33  }
    34  
    35  func TestAccAWSSNSTopic_policy(t *testing.T) {
    36  	rName := acctest.RandString(10)
    37  	expectedPolicy := `{"Statement":[{"Sid":"Stmt1445931846145","Effect":"Allow","Principal":{"AWS":"*"},"Action":"sns:Publish","Resource":"arn:aws:sns:us-west-2::example"}],"Version":"2012-10-17","Id":"Policy1445931846145"}`
    38  	resource.Test(t, resource.TestCase{
    39  		PreCheck:      func() { testAccPreCheck(t) },
    40  		IDRefreshName: "aws_sns_topic.test_topic",
    41  		Providers:     testAccProviders,
    42  		CheckDestroy:  testAccCheckAWSSNSTopicDestroy,
    43  		Steps: []resource.TestStep{
    44  			resource.TestStep{
    45  				Config: testAccAWSSNSTopicWithPolicy(rName),
    46  				Check: resource.ComposeTestCheckFunc(
    47  					testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic"),
    48  					testAccCheckAWSNSTopicHasPolicy("aws_sns_topic.test_topic", expectedPolicy),
    49  				),
    50  			},
    51  		},
    52  	})
    53  }
    54  
    55  func TestAccAWSSNSTopic_withIAMRole(t *testing.T) {
    56  	rName := acctest.RandString(10)
    57  	resource.Test(t, resource.TestCase{
    58  		PreCheck:      func() { testAccPreCheck(t) },
    59  		IDRefreshName: "aws_sns_topic.test_topic",
    60  		Providers:     testAccProviders,
    61  		CheckDestroy:  testAccCheckAWSSNSTopicDestroy,
    62  		Steps: []resource.TestStep{
    63  			resource.TestStep{
    64  				Config: testAccAWSSNSTopicConfig_withIAMRole(rName),
    65  				Check: resource.ComposeTestCheckFunc(
    66  					testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic"),
    67  				),
    68  			},
    69  		},
    70  	})
    71  }
    72  
    73  func TestAccAWSSNSTopic_withDeliveryPolicy(t *testing.T) {
    74  	rName := acctest.RandString(10)
    75  	expectedPolicy := `{"http":{"defaultHealthyRetryPolicy": {"minDelayTarget": 20,"maxDelayTarget": 20,"numMaxDelayRetries": 0,"numRetries": 3,"numNoDelayRetries": 0,"numMinDelayRetries": 0,"backoffFunction": "linear"},"disableSubscriptionOverrides": false}}`
    76  	resource.Test(t, resource.TestCase{
    77  		PreCheck:      func() { testAccPreCheck(t) },
    78  		IDRefreshName: "aws_sns_topic.test_topic",
    79  		Providers:     testAccProviders,
    80  		CheckDestroy:  testAccCheckAWSSNSTopicDestroy,
    81  		Steps: []resource.TestStep{
    82  			resource.TestStep{
    83  				Config: testAccAWSSNSTopicConfig_withDeliveryPolicy(rName),
    84  				Check: resource.ComposeTestCheckFunc(
    85  					testAccCheckAWSSNSTopicExists("aws_sns_topic.test_topic"),
    86  					testAccCheckAWSNSTopicHasDeliveryPolicy("aws_sns_topic.test_topic", expectedPolicy),
    87  				),
    88  			},
    89  		},
    90  	})
    91  }
    92  
    93  func testAccCheckAWSNSTopicHasPolicy(n string, expectedPolicyText string) resource.TestCheckFunc {
    94  	return func(s *terraform.State) error {
    95  		rs, ok := s.RootModule().Resources[n]
    96  		if !ok {
    97  			return fmt.Errorf("Not found: %s", n)
    98  		}
    99  
   100  		if rs.Primary.ID == "" {
   101  			return fmt.Errorf("No Queue URL specified!")
   102  		}
   103  
   104  		if !ok {
   105  			return fmt.Errorf("Not found: %s", n)
   106  		}
   107  
   108  		if rs.Primary.ID == "" {
   109  			return fmt.Errorf("No SNS topic with that ARN exists")
   110  		}
   111  
   112  		conn := testAccProvider.Meta().(*AWSClient).snsconn
   113  
   114  		params := &sns.GetTopicAttributesInput{
   115  			TopicArn: aws.String(rs.Primary.ID),
   116  		}
   117  		resp, err := conn.GetTopicAttributes(params)
   118  		if err != nil {
   119  			return err
   120  		}
   121  
   122  		var actualPolicyText string
   123  		for k, v := range resp.Attributes {
   124  			if k == "Policy" {
   125  				actualPolicyText = *v
   126  				break
   127  			}
   128  		}
   129  
   130  		equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicyText)
   131  		if err != nil {
   132  			return fmt.Errorf("Error testing policy equivalence: %s", err)
   133  		}
   134  		if !equivalent {
   135  			return fmt.Errorf("Non-equivalent policy error:\n\nexpected: %s\n\n     got: %s\n",
   136  				expectedPolicyText, actualPolicyText)
   137  		}
   138  
   139  		return nil
   140  	}
   141  }
   142  
   143  func testAccCheckAWSNSTopicHasDeliveryPolicy(n string, expectedPolicyText string) resource.TestCheckFunc {
   144  	return func(s *terraform.State) error {
   145  		rs, ok := s.RootModule().Resources[n]
   146  		if !ok {
   147  			return fmt.Errorf("Not found: %s", n)
   148  		}
   149  
   150  		if rs.Primary.ID == "" {
   151  			return fmt.Errorf("No Queue URL specified!")
   152  		}
   153  
   154  		conn := testAccProvider.Meta().(*AWSClient).snsconn
   155  
   156  		params := &sns.GetTopicAttributesInput{
   157  			TopicArn: aws.String(rs.Primary.ID),
   158  		}
   159  		resp, err := conn.GetTopicAttributes(params)
   160  		if err != nil {
   161  			return err
   162  		}
   163  
   164  		var actualPolicyText string
   165  		for k, v := range resp.Attributes {
   166  			if k == "DeliveryPolicy" {
   167  				actualPolicyText = *v
   168  				break
   169  			}
   170  		}
   171  
   172  		equivalent := suppressEquivalentJsonDiffs("", actualPolicyText, expectedPolicyText, nil)
   173  
   174  		if !equivalent {
   175  			return fmt.Errorf("Non-equivalent delivery policy error:\n\nexpected: %s\n\n     got: %s\n",
   176  				expectedPolicyText, actualPolicyText)
   177  		}
   178  
   179  		return nil
   180  	}
   181  }
   182  
   183  func testAccCheckAWSSNSTopicDestroy(s *terraform.State) error {
   184  	conn := testAccProvider.Meta().(*AWSClient).snsconn
   185  
   186  	for _, rs := range s.RootModule().Resources {
   187  		if rs.Type != "aws_sns_topic" {
   188  			continue
   189  		}
   190  
   191  		// Check if the topic exists by fetching its attributes
   192  		params := &sns.GetTopicAttributesInput{
   193  			TopicArn: aws.String(rs.Primary.ID),
   194  		}
   195  		_, err := conn.GetTopicAttributes(params)
   196  		if err == nil {
   197  			return fmt.Errorf("Topic exists when it should be destroyed!")
   198  		}
   199  
   200  		// Verify the error is an API error, not something else
   201  		_, ok := err.(awserr.Error)
   202  		if !ok {
   203  			return err
   204  		}
   205  	}
   206  
   207  	return nil
   208  }
   209  
   210  func testAccCheckAWSSNSTopicExists(n string) resource.TestCheckFunc {
   211  	return func(s *terraform.State) error {
   212  		rs, ok := s.RootModule().Resources[n]
   213  		if !ok {
   214  			return fmt.Errorf("Not found: %s", n)
   215  		}
   216  
   217  		if rs.Primary.ID == "" {
   218  			return fmt.Errorf("No SNS topic with that ARN exists")
   219  		}
   220  
   221  		conn := testAccProvider.Meta().(*AWSClient).snsconn
   222  
   223  		params := &sns.GetTopicAttributesInput{
   224  			TopicArn: aws.String(rs.Primary.ID),
   225  		}
   226  		_, err := conn.GetTopicAttributes(params)
   227  
   228  		if err != nil {
   229  			return err
   230  		}
   231  
   232  		return nil
   233  	}
   234  }
   235  
   236  func testAccAWSSNSTopicConfig(r string) string {
   237  	return fmt.Sprintf(`
   238  resource "aws_sns_topic" "test_topic" {
   239      name = "terraform-test-topic-%s"
   240  }
   241  `, r)
   242  }
   243  
   244  func testAccAWSSNSTopicWithPolicy(r string) string {
   245  	return fmt.Sprintf(`
   246  resource "aws_sns_topic" "test_topic" {
   247    name = "example-%s"
   248    policy = <<EOF
   249  {
   250    "Statement": [
   251      {
   252        "Sid": "Stmt1445931846145",
   253        "Effect": "Allow",
   254        "Principal": {
   255          "AWS": "*"
   256         },
   257        "Action": "sns:Publish",
   258        "Resource": "arn:aws:sns:us-west-2::example"
   259      }
   260    ],
   261    "Version": "2012-10-17",
   262    "Id": "Policy1445931846145"
   263  }
   264  EOF
   265  }
   266  `, r)
   267  }
   268  
   269  // Test for https://github.com/hashicorp/terraform/issues/3660
   270  func testAccAWSSNSTopicConfig_withIAMRole(r string) string {
   271  	return fmt.Sprintf(`
   272  resource "aws_iam_role" "example" {
   273    name = "tf_acc_test_%s"
   274    path = "/test/"
   275    assume_role_policy = <<EOF
   276  {
   277    "Version": "2012-10-17",
   278    "Statement": [
   279      {
   280        "Action": "sts:AssumeRole",
   281        "Principal": {
   282          "Service": "ec2.amazonaws.com"
   283        },
   284        "Effect": "Allow",
   285        "Sid": ""
   286      }
   287    ]
   288  }
   289  EOF
   290  }
   291  
   292  resource "aws_sns_topic" "test_topic" {
   293    name = "tf-acc-test-with-iam-role-%s"
   294    policy = <<EOF
   295  {
   296    "Statement": [
   297      {
   298        "Sid": "Stmt1445931846145",
   299        "Effect": "Allow",
   300        "Principal": {
   301          "AWS": "${aws_iam_role.example.arn}"
   302  			},
   303        "Action": "sns:Publish",
   304        "Resource": "arn:aws:sns:us-west-2::example"
   305      }
   306    ],
   307    "Version": "2012-10-17",
   308    "Id": "Policy1445931846145"
   309  }
   310  EOF
   311  }
   312  `, r, r)
   313  }
   314  
   315  // Test for https://github.com/hashicorp/terraform/issues/14024
   316  func testAccAWSSNSTopicConfig_withDeliveryPolicy(r string) string {
   317  	return fmt.Sprintf(`
   318  resource "aws_sns_topic" "test_topic" {
   319    name = "tf_acc_test_delivery_policy_%s"
   320    delivery_policy = <<EOF
   321  {
   322    "http": {
   323      "defaultHealthyRetryPolicy": {
   324        "minDelayTarget": 20,
   325        "maxDelayTarget": 20,
   326        "numRetries": 3,
   327        "numMaxDelayRetries": 0,
   328        "numNoDelayRetries": 0,
   329        "numMinDelayRetries": 0,
   330        "backoffFunction": "linear"
   331      },
   332      "disableSubscriptionOverrides": false
   333    }
   334  }
   335  EOF
   336  }
   337  `, r)
   338  }