Example #1
1
func TestConfigureSecurityGroupsMixed(t *testing.T) {
	groups := []string{"existingGroup", "newGroup"}
	recorder := fakeEC2SecurityGroupTestRecorder{}

	// First, a check is made for which groups already exist.
	initialLookupResult := ec2.DescribeSecurityGroupsOutput{SecurityGroups: []*ec2.SecurityGroup{
		{
			GroupName:     aws.String("existingGroup"),
			GroupId:       aws.String("existingGroupId"),
			IpPermissions: []*ec2.IpPermission{ipPermission(testSSHPort)},
		},
	}}
	recorder.On("DescribeSecurityGroups", mock.MatchedBy(matchGroupLookup(groups))).Return(
		&initialLookupResult, nil)

	// An ingress permission is added to the existing group.
	recorder.On("AuthorizeSecurityGroupIngress", &ec2.AuthorizeSecurityGroupIngressInput{
		GroupId:       aws.String("existingGroupId"),
		IpPermissions: []*ec2.IpPermission{ipPermission(testDockerPort)},
	}).Return(
		&ec2.AuthorizeSecurityGroupIngressOutput{}, nil)

	// The new security group is created.
	recorder.On("CreateSecurityGroup", &ec2.CreateSecurityGroupInput{
		GroupName:   aws.String("newGroup"),
		Description: aws.String("Docker Machine"),
		VpcId:       aws.String(""),
	}).Return(
		&ec2.CreateSecurityGroupOutput{GroupId: aws.String("newGroupId")}, nil)

	// Ensuring the new security group exists.
	postCreateLookupResult := ec2.DescribeSecurityGroupsOutput{SecurityGroups: []*ec2.SecurityGroup{
		{
			GroupName: aws.String("newGroup"),
			GroupId:   aws.String("newGroupId"),
		},
	}}
	recorder.On("DescribeSecurityGroups",
		&ec2.DescribeSecurityGroupsInput{GroupIds: []*string{aws.String("newGroupId")}}).Return(
		&postCreateLookupResult, nil)

	// Permissions are added to the new security group.
	recorder.On("AuthorizeSecurityGroupIngress", &ec2.AuthorizeSecurityGroupIngressInput{
		GroupId:       aws.String("newGroupId"),
		IpPermissions: []*ec2.IpPermission{ipPermission(testSSHPort), ipPermission(testDockerPort)},
	}).Return(
		&ec2.AuthorizeSecurityGroupIngressOutput{}, nil)

	driver := NewCustomTestDriver(&recorder)
	err := driver.configureSecurityGroups(groups)

	assert.Nil(t, err)
	recorder.AssertExpectations(t)
}
Example #2
1
func TestConfigureSecurityGroupsErrLookupExist(t *testing.T) {
	groups := []string{"group"}
	recorder := fakeEC2SecurityGroupTestRecorder{}

	lookupExistErr := errors.New("lookup failed")
	recorder.On("DescribeSecurityGroups", mock.MatchedBy(matchGroupLookup(groups))).Return(
		nil, lookupExistErr)

	driver := NewCustomTestDriver(&recorder)
	err := driver.configureSecurityGroups(groups)

	assert.Exactly(t, lookupExistErr, err)
	recorder.AssertExpectations(t)
}
Example #3
1
func (m *MockQueue) ReportFailed(taskID, runID string) (*queue.TaskStatusResponse, error) {
	args := m.Called(taskID, runID)
	return args.Get(0).(*queue.TaskStatusResponse), args.Error(1)
}
func (m *MockQueue) ReportException(taskID, runID string, payload *queue.TaskExceptionRequest) (*queue.TaskStatusResponse, error) {
	args := m.Called(taskID, runID, payload)
	return args.Get(0).(*queue.TaskStatusResponse), args.Error(1)
}

func (m *MockQueue) CreateArtifact(taskID, runID, name string, payload *queue.PostArtifactRequest) (*queue.PostArtifactResponse, error) {
	args := m.Called(taskID, runID, name, payload)
	return args.Get(0).(*queue.PostArtifactResponse), args.Error(1)
}

var PostAnyArtifactRequest = mock.MatchedBy(func(i interface{}) bool {
	_, ok := i.(*queue.PostArtifactRequest)
	return ok
})

var PostS3ArtifactRequest = mock.MatchedBy(func(i interface{}) bool {
	r, ok := i.(*queue.PostArtifactRequest)
	if !ok {
		return false
	}
	var s3req queue.S3ArtifactRequest
	if json.Unmarshal(*r, &s3req) != nil {
		return false
	}
	return s3req.StorageType == "s3"
})

// ExpectS3Artifact will setup queue to expect an S3 artifact with given
	AfterEach(func() {
		gitRepo.AssertExpectations(GinkgoT())
	})

	Context("with autosquash failing", func() {
		BeforeEach(func() {
			gitRepo.
				On("RebaseAutosquash", "origin/"+baseRef, headSHA).
				Return(errors.New("merge conflict"))
		})

		It("reports the failure", func() {
			repositories.
				On("CreateStatus", repositoryOwner, repositoryName, headSHA, mock.MatchedBy(func(status *github.RepoStatus) bool {
					return *status.State == "failure" && *status.Context == "review/squash"
				})).
				Return(nil, nil, nil)

			handle()

			Expect(responseRecorder.Code).To(Equal(http.StatusOK))
		})
	})

	Context("with autosquash succeeding", func() {
		BeforeEach(func() {
			gitRepo.
				On("RebaseAutosquash", "origin/"+baseRef, headSHA).
				Return(nil)
		})
func mockServices(r *MockRegistry, healthyServicesAndCategories map[string][]string, unhealthyServicesAndCategories map[string][]string) {
	any := func(x interface{}) bool { return true }

	c := new(MockHealthChecker)
	c.On("IsHighSeverity", mock.MatchedBy(any)).Return(false)
	r.On("checker").Return(c)

	measuredServices := make(map[string]MeasuredService)

	for service, categories := range healthyServicesAndCategories {
		key := strings.ToLower(strings.Replace(service, " ", "-", -1))
		s := Service{Name: service, ServiceKey: key, Categories: categories}
		measuredService := MeasuredService{service: &s}
		measuredServices[service] = measuredService
		c.On("Check", s).Return("ok", nil)
	}

	for service, categories := range unhealthyServicesAndCategories {
		key := strings.ToLower(strings.Replace(service, " ", "-", -1))
		s := Service{Name: service, ServiceKey: key, Categories: categories}
		measuredService := MeasuredService{service: &s}
		measuredServices[service] = measuredService
		c.On("Check", s).Return("nok", errors.New("Service "+service+" is unhealthy"))
	}

	r.On("measuredServices").Return(measuredServices)
	r.On("getAck", mock.MatchedBy(any)).Return("")
	r.On("updateCachedAndBufferedHealth", mock.MatchedBy(any), mock.MatchedBy(any)).Return()
}
func TestHandleGtgUnhealthySetsUnhealthyCategoriesOnlyDisabled(t *testing.T) {
	initLogs(os.Stdout, os.Stdout, os.Stderr)
	any := func(x interface{}) bool { return true }

	registry := new(MockRegistry)

	healthy := make(map[string][]string)
	healthy["Test Service 1"] = []string{"foo"}

	unhealthy := make(map[string][]string)
	unhealthy["Test Service 2"] = []string{"bar"}

	mockServices(registry, healthy, unhealthy)

	env := "test"
	controller := NewController(registry, &env)

	mockCategories(registry, []string{"foo", "bar"}, []string{})
	registry.On("matchingCategories", []string{"foo", "bar"}).Return([]string{"Test Service 1", "Test Service 2"})
	registry.On("areResilient", mock.MatchedBy(any)).Return(false)
	registry.On("disableCategoryIfSticky", "bar").Return() // only expect to be called for category "bar"

	req, _ := http.NewRequest("GET", "http://www.example.com/__gtg?categories=foo,bar&cache=false", nil)
	w := httptest.NewRecorder()

	controller.handleGoodToGo(w, req)

	assert.Equal(t, http.StatusServiceUnavailable, w.Code, "HTTP status")
	registry.AssertExpectations(t)
}
func TestHandleGtgOk(t *testing.T) {
	initLogs(os.Stdout, os.Stdout, os.Stderr)
	any := func(x interface{}) bool { return true }

	registry := new(MockRegistry)

	healthy := make(map[string][]string)
	healthy["Test Service"] = []string{"foo"}

	unhealthy := make(map[string][]string)

	mockServices(registry, healthy, unhealthy)

	env := "test"
	controller := NewController(registry, &env)

	mockCategories(registry, []string{"foo"}, []string{})
	registry.On("matchingCategories", []string{"foo"}).Return([]string{"Test Service"})
	registry.On("areResilient", mock.MatchedBy(any)).Return(false)

	req, _ := http.NewRequest("GET", "http://www.example.com/__gtg?categories=foo&cache=false", nil)
	w := httptest.NewRecorder()

	controller.handleGoodToGo(w, req)

	assert.Equal(t, http.StatusOK, w.Code, "HTTP status")
	registry.AssertExpectations(t)
}
func TestPaymentListener(t *testing.T) {
	mockEntityManager := new(mocks.MockEntityManager)
	mockHorizon := new(mocks.MockHorizon)
	mockRepository := new(mocks.MockRepository)
	mockHTTPClient := new(mocks.MockHTTPClient)

	config := &config.Config{
		Assets: []config.Asset{
			{Code: "USD", Issuer: "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"},
			{Code: "EUR", Issuer: "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"},
		},
		Accounts: config.Accounts{
			IssuingAccountID:   "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB",
			ReceivingAccountID: "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB",
		},
		Callbacks: config.Callbacks{
			Receive: "http://receive_callback",
		},
	}

	paymentListener, err := NewPaymentListener(
		config,
		mockEntityManager,
		mockHorizon,
		mockRepository,
		mocks.Now,
	)
	require.NoError(t, err)

	paymentListener.client = mockHTTPClient

	Convey("PaymentListener", t, func() {
		operation := horizon.PaymentResponse{
			ID:          "1",
			From:        "GBIHSMPXC2KJ3NJVHEYTG3KCHYEUQRT45X6AWYWXMAXZOAX4F5LFZYYQ",
			PagingToken: "2",
			Amount:      "200",
		}

		mocks.PredefinedTime = time.Now()

		dbPayment := entities.ReceivedPayment{
			OperationID: operation.ID,
			ProcessedAt: mocks.PredefinedTime,
			PagingToken: operation.PagingToken,
		}

		Convey("When operation exists", func() {
			operation.Type = "payment"
			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(&entities.ReceivedPayment{}, nil).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When operation is not a payment", func() {
			operation.Type = "create_account"
			dbPayment.Status = "Not a payment operation"
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()
			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When payment is sent not received", func() {
			operation.Type = "payment"
			operation.To = "GDNXBMIJLLLXZYKZBHXJ45WQ4AJQBRVT776YKGQTDBHTSPMNAFO3OZOS"
			dbPayment.Status = "Operation sent not received"
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()
			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When asset is not allowed (issuer)", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GC4WWLMUGZJMRVJM7JUVVZBY3LJ5HL4RKIPADEGKEMLAAJEDRONUGYG7"
			dbPayment.Status = "Asset not allowed"
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()
			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When asset is not allowed (code)", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "GBP"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"
			dbPayment.Status = "Asset not allowed"
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()
			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When unable to load transaction memo", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"

			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()
			mockHorizon.On("LoadMemo", &operation).Return(errors.New("Connection error")).Once()

			Convey("it should return error", func() {
				err := paymentListener.onPayment(operation)
				assert.Error(t, err)
				mockHorizon.AssertExpectations(t)
				mockEntityManager.AssertNotCalled(t, "Persist")
			})
		})

		Convey("When receive callback returns error", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"
			operation.Memo.Type = "text"
			operation.Memo.Value = "testing"

			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()
			mockHorizon.On("LoadMemo", &operation).Return(nil).Once()

			mockHTTPClient.On(
				"Do",
				mock.MatchedBy(func(req *http.Request) bool {
					return req.URL.String() == "http://receive_callback"
				}),
			).Return(
				net.BuildHTTPResponse(503, "ok"),
				nil,
			).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Error(t, err)
				mockHorizon.AssertExpectations(t)
				mockEntityManager.AssertNotCalled(t, "Persist")
			})
		})

		Convey("When receive callback returns success", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"
			operation.Memo.Type = "text"
			operation.Memo.Value = "testing"

			dbPayment.Status = "Success"

			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()
			mockHorizon.On("LoadMemo", &operation).Return(nil).Once()
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()

			mockHTTPClient.On(
				"Do",
				mock.MatchedBy(func(req *http.Request) bool {
					return req.URL.String() == "http://receive_callback"
				}),
			).Return(
				net.BuildHTTPResponse(200, "ok"),
				nil,
			).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockHorizon.AssertExpectations(t)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When receive callback returns success (no memo)", func() {
			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"

			dbPayment.Status = "Success"

			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()
			mockHorizon.On("LoadMemo", &operation).Return(nil).Once()
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()

			mockHTTPClient.On(
				"Do",
				mock.MatchedBy(func(req *http.Request) bool {
					return req.URL.String() == "http://receive_callback"
				}),
			).Return(
				net.BuildHTTPResponse(200, "ok"),
				nil,
			).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockHorizon.AssertExpectations(t)
				mockEntityManager.AssertExpectations(t)
			})
		})

		Convey("When receive callback returns success and compliance server is connected", func() {
			paymentListener.config.Compliance = "http://compliance"

			operation.Type = "payment"
			operation.To = "GATKP6ZQM5CSLECPMTAC5226PE367QALCPM6AFHTSULPPZMT62OOPMQB"
			operation.AssetCode = "USD"
			operation.AssetIssuer = "GD4I7AFSLZGTDL34TQLWJOM2NHLIIOEKD5RHHZUW54HERBLSIRKUOXRR"
			operation.Memo.Type = "hash"
			operation.Memo.Value = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"

			dbPayment.Status = "Success"

			mockRepository.On("GetReceivedPaymentByID", int64(1)).Return(nil, nil).Once()
			mockHorizon.On("LoadMemo", &operation).Return(nil).Once()
			mockEntityManager.On("Persist", &dbPayment).Return(nil).Once()

			memo := memo.Memo{
				Transaction: memo.Transaction{
					Route: "jed*stellar.org",
				},
			}

			memoString, _ := json.Marshal(memo)

			auth := compliance.AuthData{
				Memo: string(memoString),
			}

			authString, _ := json.Marshal(auth)

			response := compliance.ReceiveResponse{
				Data: string(authString),
			}

			responseString, _ := json.Marshal(response)

			mockHTTPClient.On(
				"Do",
				mock.MatchedBy(func(req *http.Request) bool {
					return req.URL.String() == "http://compliance/receive"
				}),
			).Return(
				net.BuildHTTPResponse(200, string(responseString)),
				nil,
			).Once()

			mockHTTPClient.On(
				"Do",
				mock.MatchedBy(func(req *http.Request) bool {
					return req.URL.String() == "http://receive_callback"
				}),
			).Return(
				net.BuildHTTPResponse(200, "ok"),
				nil,
			).Once()

			Convey("it should save the status", func() {
				err := paymentListener.onPayment(operation)
				assert.Nil(t, err)
				mockHorizon.AssertExpectations(t)
				mockEntityManager.AssertExpectations(t)
			})
		})
	})
}