1package iam_test
2
3import (
4	"errors"
5
6	"github.com/aws/aws-sdk-go/aws"
7	awsiam "github.com/aws/aws-sdk-go/service/iam"
8	"github.com/genevieve/leftovers/aws/iam"
9	"github.com/genevieve/leftovers/aws/iam/fakes"
10	. "github.com/onsi/ginkgo"
11	. "github.com/onsi/gomega"
12)
13
14var _ = Describe("Policies", func() {
15	var (
16		client *fakes.PoliciesClient
17		logger *fakes.Logger
18		filter string
19
20		policies iam.Policies
21	)
22
23	BeforeEach(func() {
24		client = &fakes.PoliciesClient{}
25		logger = &fakes.Logger{}
26		filter = "banana"
27
28		policies = iam.NewPolicies(client, logger)
29	})
30
31	Describe("List", func() {
32		BeforeEach(func() {
33			logger.PromptWithDetailsCall.Returns.Proceed = true
34			client.ListPoliciesCall.Returns.Output = &awsiam.ListPoliciesOutput{
35				Policies: []*awsiam.Policy{{
36					Arn:        aws.String("the-policy-arn"),
37					PolicyName: aws.String("banana-policy"),
38				}},
39			}
40		})
41
42		It("returns a list of policies to delete", func() {
43			items, err := policies.List(filter)
44			Expect(err).NotTo(HaveOccurred())
45
46			Expect(client.ListPoliciesCall.CallCount).To(Equal(1))
47
48			Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(1))
49			Expect(logger.PromptWithDetailsCall.Receives.Type).To(Equal("IAM Policy"))
50			Expect(logger.PromptWithDetailsCall.Receives.Name).To(Equal("banana-policy"))
51
52			Expect(items).To(HaveLen(1))
53		})
54
55		Context("when the client fails to list policies", func() {
56			BeforeEach(func() {
57				client.ListPoliciesCall.Returns.Error = errors.New("some error")
58			})
59
60			It("returns the error and does not try deleting them", func() {
61				_, err := policies.List(filter)
62				Expect(err).To(MatchError("List IAM Policies: some error"))
63
64				Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(0))
65			})
66		})
67
68		Context("when the policy name does not contain the filter", func() {
69			It("does not try to delete it", func() {
70				items, err := policies.List("kiwi")
71				Expect(err).NotTo(HaveOccurred())
72
73				Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(0))
74
75				Expect(items).To(HaveLen(0))
76			})
77		})
78
79		Context("when the user responds no to the prompt", func() {
80			BeforeEach(func() {
81				logger.PromptWithDetailsCall.Returns.Proceed = false
82			})
83
84			It("does not return it in the list", func() {
85				items, err := policies.List(filter)
86				Expect(err).NotTo(HaveOccurred())
87
88				Expect(logger.PromptWithDetailsCall.Receives.Type).To(Equal("IAM Policy"))
89				Expect(logger.PromptWithDetailsCall.Receives.Name).To(Equal("banana-policy"))
90
91				Expect(items).To(HaveLen(0))
92			})
93		})
94	})
95})
96