Ref/want err from err expected (#82)

consistent naming for test values using 'want' instead of 'expect/ed'
This commit is contained in:
datosh 2022-04-26 16:54:05 +02:00 committed by GitHub
parent 6265b307af
commit 51068abc27
91 changed files with 2319 additions and 2319 deletions

View File

@ -9,6 +9,6 @@ import (
func TestAutoscalingNodeGroup(t *testing.T) {
assert := assert.New(t)
nodeGroups := AutoscalingNodeGroup("scale-set", 0, 100)
expectedNodeGroups := "0:100:scale-set"
assert.Equal(expectedNodeGroups, nodeGroups)
wantNodeGroups := "0:100:scale-set"
assert.Equal(wantNodeGroups, nodeGroups)
}

View File

@ -23,7 +23,7 @@ func TestCreateServicePrincipal(t *testing.T) {
servicePrincipalsAPI servicePrincipalsAPI
roleAssignmentsAPI roleAssignmentsAPI
resourceGroupAPI resourceGroupAPI
errExpected bool
wantErr bool
}{
"successful create": {
applicationsAPI: stubApplicationsAPI{},
@ -39,14 +39,14 @@ func TestCreateServicePrincipal(t *testing.T) {
applicationsAPI: stubApplicationsAPI{
createErr: someErr,
},
errExpected: true,
wantErr: true,
},
"failed service principal create": {
applicationsAPI: stubApplicationsAPI{},
servicePrincipalsAPI: stubServicePrincipalsAPI{
createErr: someErr,
},
errExpected: true,
wantErr: true,
},
"failed role assignment": {
applicationsAPI: stubApplicationsAPI{},
@ -59,7 +59,7 @@ func TestCreateServicePrincipal(t *testing.T) {
ID: to.StringPtr("resource-group-id"),
},
},
errExpected: true,
wantErr: true,
},
"failed update creds": {
applicationsAPI: stubApplicationsAPI{
@ -72,7 +72,7 @@ func TestCreateServicePrincipal(t *testing.T) {
ID: to.StringPtr("resource-group-id"),
},
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -93,7 +93,7 @@ func TestCreateServicePrincipal(t *testing.T) {
}
_, err := client.CreateServicePrincipal(ctx)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -107,7 +107,7 @@ func TestTerminateServicePrincipal(t *testing.T) {
testCases := map[string]struct {
appObjectID string
applicationsAPI applicationsAPI
errExpected bool
wantErr bool
}{
"successful terminate": {
appObjectID: "object-id",
@ -121,7 +121,7 @@ func TestTerminateServicePrincipal(t *testing.T) {
applicationsAPI: stubApplicationsAPI{
deleteErr: someErr,
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -139,7 +139,7 @@ func TestTerminateServicePrincipal(t *testing.T) {
}
err := client.TerminateServicePrincipal(ctx)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -152,7 +152,7 @@ func TestCreateADApplication(t *testing.T) {
someErr := errors.New("failed")
testCases := map[string]struct {
applicationsAPI applicationsAPI
errExpected bool
wantErr bool
}{
"successful create": {
applicationsAPI: stubApplicationsAPI{},
@ -161,7 +161,7 @@ func TestCreateADApplication(t *testing.T) {
applicationsAPI: stubApplicationsAPI{
createErr: someErr,
},
errExpected: true,
wantErr: true,
},
"app create returns invalid appid": {
applicationsAPI: stubApplicationsAPI{
@ -169,7 +169,7 @@ func TestCreateADApplication(t *testing.T) {
ObjectID: proto.String("00000000-0000-0000-0000-000000000001"),
},
},
errExpected: true,
wantErr: true,
},
"app create returns invalid objectid": {
applicationsAPI: stubApplicationsAPI{
@ -177,7 +177,7 @@ func TestCreateADApplication(t *testing.T) {
AppID: proto.String("00000000-0000-0000-0000-000000000000"),
},
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -193,7 +193,7 @@ func TestCreateADApplication(t *testing.T) {
}
appCredentials, err := client.createADApplication(ctx)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -207,7 +207,7 @@ func TestCreateAppServicePrincipal(t *testing.T) {
someErr := errors.New("failed")
testCases := map[string]struct {
servicePrincipalsAPI servicePrincipalsAPI
errExpected bool
wantErr bool
}{
"successful create": {
servicePrincipalsAPI: stubServicePrincipalsAPI{},
@ -216,13 +216,13 @@ func TestCreateAppServicePrincipal(t *testing.T) {
servicePrincipalsAPI: stubServicePrincipalsAPI{
createErr: someErr,
},
errExpected: true,
wantErr: true,
},
"service principal create returns invalid objectid": {
servicePrincipalsAPI: stubServicePrincipalsAPI{
createServicePrincipal: &graphrbac.ServicePrincipal{},
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -238,7 +238,7 @@ func TestCreateAppServicePrincipal(t *testing.T) {
}
_, err := client.createAppServicePrincipal(ctx, "app-id")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -252,7 +252,7 @@ func TestAssignOwnerOfResourceGroup(t *testing.T) {
testCases := map[string]struct {
roleAssignmentsAPI roleAssignmentsAPI
resourceGroupAPI resourceGroupAPI
errExpected bool
wantErr bool
}{
"successful assign": {
roleAssignmentsAPI: &stubRoleAssignmentsAPI{},
@ -271,21 +271,21 @@ func TestAssignOwnerOfResourceGroup(t *testing.T) {
ID: to.StringPtr("resource-group-id"),
},
},
errExpected: true,
wantErr: true,
},
"failed resource group get": {
roleAssignmentsAPI: &stubRoleAssignmentsAPI{},
resourceGroupAPI: stubResourceGroupAPI{
getErr: someErr,
},
errExpected: true,
wantErr: true,
},
"resource group get returns invalid id": {
roleAssignmentsAPI: &stubRoleAssignmentsAPI{},
resourceGroupAPI: stubResourceGroupAPI{
getResourceGroup: armresources.ResourceGroup{},
},
errExpected: true,
wantErr: true,
},
"create returns PrincipalNotFound the first time": {
roleAssignmentsAPI: &stubRoleAssignmentsAPI{
@ -313,7 +313,7 @@ func TestAssignOwnerOfResourceGroup(t *testing.T) {
ID: to.StringPtr("resource-group-id"),
},
},
errExpected: true,
wantErr: true,
},
"create service error code is unknown": {
roleAssignmentsAPI: &stubRoleAssignmentsAPI{
@ -331,7 +331,7 @@ func TestAssignOwnerOfResourceGroup(t *testing.T) {
ID: to.StringPtr("resource-group-id"),
},
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -350,7 +350,7 @@ func TestAssignOwnerOfResourceGroup(t *testing.T) {
}
err := client.assignResourceGroupRole(ctx, "principal-id", "role-definition-id")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -13,7 +13,7 @@ import (
func TestSetGetState(t *testing.T) {
testCases := map[string]struct {
state state.ConstellationState
errExpected bool
wantErr bool
}{
"valid state": {
state: state.ConstellationState{
@ -62,7 +62,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing coordinator": {
state: state.ConstellationState{
@ -84,7 +84,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing name": {
state: state.ConstellationState{
@ -111,7 +111,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing uid": {
state: state.ConstellationState{
@ -138,7 +138,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing resource group": {
state: state.ConstellationState{
@ -165,7 +165,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing location": {
state: state.ConstellationState{
@ -192,7 +192,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing subscription": {
state: state.ConstellationState{
@ -219,7 +219,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing tenant": {
state: state.ConstellationState{
@ -246,7 +246,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing subnet": {
state: state.ConstellationState{
@ -273,7 +273,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing network security group": {
state: state.ConstellationState{
@ -300,7 +300,7 @@ func TestSetGetState(t *testing.T) {
AzureNodesScaleSet: "node-scale-set",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing node scale set": {
state: state.ConstellationState{
@ -327,7 +327,7 @@ func TestSetGetState(t *testing.T) {
AzureNetworkSecurityGroup: "network-security-group",
AzureCoordinatorsScaleSet: "coordinator-scale-set",
},
errExpected: true,
wantErr: true,
},
"missing coordinator scale set": {
state: state.ConstellationState{
@ -354,7 +354,7 @@ func TestSetGetState(t *testing.T) {
AzureNetworkSecurityGroup: "network-security-group",
AzureNodesScaleSet: "node-scale-set",
},
errExpected: true,
wantErr: true,
},
}
@ -364,7 +364,7 @@ func TestSetGetState(t *testing.T) {
assert := assert.New(t)
client := Client{}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.SetState(tc.state))
} else {
assert.NoError(client.SetState(tc.state))
@ -404,7 +404,7 @@ func TestSetGetState(t *testing.T) {
nodesScaleSet: tc.state.AzureNodesScaleSet,
coordinatorsScaleSet: tc.state.AzureCoordinatorsScaleSet,
}
if tc.errExpected {
if tc.wantErr {
_, err := client.GetState()
assert.Error(err)
} else {

View File

@ -17,14 +17,14 @@ func TestCreateResourceGroup(t *testing.T) {
someErr := errors.New("failed")
testCases := map[string]struct {
resourceGroupAPI resourceGroupAPI
errExpected bool
wantErr bool
}{
"successful create": {
resourceGroupAPI: stubResourceGroupAPI{},
},
"failed create": {
resourceGroupAPI: stubResourceGroupAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -42,7 +42,7 @@ func TestCreateResourceGroup(t *testing.T) {
coordinators: make(azure.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateResourceGroup(ctx))
} else {
assert.NoError(client.CreateResourceGroup(ctx))
@ -77,7 +77,7 @@ func TestTerminateResourceGroup(t *testing.T) {
resourceGroup string
resourceGroupAPI resourceGroupAPI
client Client
errExpected bool
wantErr bool
}{
"successful terminate": {
resourceGroupAPI: stubResourceGroupAPI{},
@ -91,12 +91,12 @@ func TestTerminateResourceGroup(t *testing.T) {
"failed terminate": {
resourceGroupAPI: stubResourceGroupAPI{terminateErr: someErr},
client: clientWithResourceGroup,
errExpected: true,
wantErr: true,
},
"failed to poll terminate response": {
resourceGroupAPI: stubResourceGroupAPI{stubResponse: stubResourceGroupsDeletePollerResponse{pollerErr: someErr}},
client: clientWithResourceGroup,
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -105,7 +105,7 @@ func TestTerminateResourceGroup(t *testing.T) {
tc.client.resourceGroupAPI = tc.resourceGroupAPI
ctx := context.Background()
if tc.errExpected {
if tc.wantErr {
assert.Error(tc.client.TerminateResourceGroup(ctx))
return
}
@ -129,7 +129,7 @@ func TestCreateInstances(t *testing.T) {
resourceGroupAPI resourceGroupAPI
roleAssignmentsAPI roleAssignmentsAPI
createInstancesInput CreateInstancesInput
errExpected bool
wantErr bool
}{
"successful create": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -166,7 +166,7 @@ func TestCreateInstances(t *testing.T) {
Image: "image",
UserAssingedIdentity: "identity",
},
errExpected: true,
wantErr: true,
},
"error when polling create scale set response": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -181,7 +181,7 @@ func TestCreateInstances(t *testing.T) {
Image: "image",
UserAssingedIdentity: "identity",
},
errExpected: true,
wantErr: true,
},
"error when retrieving private IPs": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -195,7 +195,7 @@ func TestCreateInstances(t *testing.T) {
Image: "image",
UserAssingedIdentity: "identity",
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -218,7 +218,7 @@ func TestCreateInstances(t *testing.T) {
coordinators: make(azure.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateInstances(ctx, tc.createInstancesInput))
} else {
assert.NoError(client.CreateInstances(ctx, tc.createInstancesInput))
@ -243,7 +243,7 @@ func TestCreateInstancesVMs(t *testing.T) {
resourceGroupAPI resourceGroupAPI
roleAssignmentsAPI roleAssignmentsAPI
createInstancesInput CreateInstancesInput
errExpected bool
wantErr bool
}{
"successful create": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -278,7 +278,7 @@ func TestCreateInstancesVMs(t *testing.T) {
InstanceType: "type",
Image: "image",
},
errExpected: true,
wantErr: true,
},
"error when polling create scale set response": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -292,7 +292,7 @@ func TestCreateInstancesVMs(t *testing.T) {
InstanceType: "type",
Image: "image",
},
errExpected: true,
wantErr: true,
},
"error when creating NIC": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -306,7 +306,7 @@ func TestCreateInstancesVMs(t *testing.T) {
InstanceType: "type",
Image: "image",
},
errExpected: true,
wantErr: true,
},
"error when creating public IP": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{createErr: someErr},
@ -320,7 +320,7 @@ func TestCreateInstancesVMs(t *testing.T) {
InstanceType: "type",
Image: "image",
},
errExpected: true,
wantErr: true,
},
"error when retrieving public IP": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{getErr: someErr},
@ -334,7 +334,7 @@ func TestCreateInstancesVMs(t *testing.T) {
InstanceType: "type",
Image: "image",
},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -358,7 +358,7 @@ func TestCreateInstancesVMs(t *testing.T) {
coordinators: make(azure.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateInstancesVMs(ctx, tc.createInstancesInput))
return
}

View File

@ -14,18 +14,18 @@ func TestCreateVirtualNetwork(t *testing.T) {
someErr := errors.New("failed")
testCases := map[string]struct {
networksAPI networksAPI
errExpected bool
wantErr bool
}{
"successful create": {
networksAPI: stubNetworksAPI{},
},
"failed to get response from successful create": {
networksAPI: stubNetworksAPI{stubResponse: stubVirtualNetworksCreateOrUpdatePollerResponse{pollerErr: someErr}},
errExpected: true,
wantErr: true,
},
"failed create": {
networksAPI: stubNetworksAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -44,7 +44,7 @@ func TestCreateVirtualNetwork(t *testing.T) {
coordinators: make(azure.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateVirtualNetwork(ctx))
} else {
assert.NoError(client.CreateVirtualNetwork(ctx))
@ -78,18 +78,18 @@ func TestCreateSecurityGroup(t *testing.T) {
testCases := map[string]struct {
networkSecurityGroupsAPI networkSecurityGroupsAPI
errExpected bool
wantErr bool
}{
"successful create": {
networkSecurityGroupsAPI: stubNetworkSecurityGroupsAPI{},
},
"failed to get response from successful create": {
networkSecurityGroupsAPI: stubNetworkSecurityGroupsAPI{stubPoller: stubNetworkSecurityGroupsCreateOrUpdatePollerResponse{pollerErr: someErr}},
errExpected: true,
wantErr: true,
},
"failed create": {
networkSecurityGroupsAPI: stubNetworkSecurityGroupsAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -108,7 +108,7 @@ func TestCreateSecurityGroup(t *testing.T) {
networkSecurityGroupsAPI: tc.networkSecurityGroupsAPI,
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateSecurityGroup(ctx, testNetworkSecurityGroupInput))
} else {
assert.NoError(client.CreateSecurityGroup(ctx, testNetworkSecurityGroupInput))
@ -126,7 +126,7 @@ func TestCreateNIC(t *testing.T) {
networkInterfacesAPI networkInterfacesAPI
name string
publicIPAddressID string
errExpected bool
wantErr bool
}{
"successful create": {
networkInterfacesAPI: stubNetworkInterfacesAPI{},
@ -135,11 +135,11 @@ func TestCreateNIC(t *testing.T) {
},
"failed to get response from successful create": {
networkInterfacesAPI: stubNetworkInterfacesAPI{stubResp: stubInterfacesClientCreateOrUpdatePollerResponse{pollErr: someErr}},
errExpected: true,
wantErr: true,
},
"failed create": {
networkInterfacesAPI: stubNetworkInterfacesAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -159,7 +159,7 @@ func TestCreateNIC(t *testing.T) {
}
ip, id, err := client.createNIC(ctx, tc.name, tc.publicIPAddressID)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -177,7 +177,7 @@ func TestCreatePublicIPAddress(t *testing.T) {
testCases := map[string]struct {
publicIPAddressesAPI publicIPAddressesAPI
name string
errExpected bool
wantErr bool
}{
"successful create": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{},
@ -185,11 +185,11 @@ func TestCreatePublicIPAddress(t *testing.T) {
},
"failed to get response from successful create": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{stubCreateResponse: stubPublicIPAddressesClientCreateOrUpdatePollerResponse{pollErr: someErr}},
errExpected: true,
wantErr: true,
},
"failed create": {
publicIPAddressesAPI: stubPublicIPAddressesAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -209,7 +209,7 @@ func TestCreatePublicIPAddress(t *testing.T) {
}
id, err := client.createPublicIPAddress(ctx, tc.name)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -9,22 +9,22 @@ import (
func TestIDs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(expectedIDs, testState.IDs())
wantIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(wantIDs, testState.IDs())
}
func TestPublicIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(expectedIPs, testState.PublicIPs())
wantIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(wantIPs, testState.PublicIPs())
}
func TestPrivateIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(expectedIPs, testState.PrivateIPs())
wantIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(wantIPs, testState.PrivateIPs())
}
func TestGetOne(t *testing.T) {
@ -43,9 +43,9 @@ func TestGetOthers(t *testing.T) {
for _, id := range testCases {
others := testInstances().GetOthers(id)
assert.NotContains(others, id)
expectedInstances := testInstances()
delete(expectedInstances, id)
assert.ElementsMatch(others.IDs(), expectedInstances.IDs())
wantInstances := testInstances()
delete(wantInstances, id)
assert.ElementsMatch(others.IDs(), wantInstances.IDs())
}
}

View File

@ -75,7 +75,7 @@ func TestFirewallAzure(t *testing.T) {
Port: 4433,
},
}
expectedOutput := []*armnetwork.SecurityRule{
wantOutput := []*armnetwork.SecurityRule{
{
Name: proto.String("perm1"),
Properties: &armnetwork.SecurityRulePropertiesFormat{
@ -121,7 +121,7 @@ func TestFirewallAzure(t *testing.T) {
}
out := input.Azure()
assert.Equal(expectedOutput, out)
assert.Equal(wantOutput, out)
}
func TestIPPermissonsToAWS(t *testing.T) {
@ -147,7 +147,7 @@ func TestIPPermissonsToAWS(t *testing.T) {
Port: 4433,
},
}
expectedOutput := []ec2types.IpPermission{
wantOutput := []ec2types.IpPermission{
{
FromPort: proto.Int32(int32(22)),
ToPort: proto.Int32(int32(22)),
@ -184,5 +184,5 @@ func TestIPPermissonsToAWS(t *testing.T) {
}
out := input.AWS()
assert.Equal(expectedOutput, out)
assert.Equal(wantOutput, out)
}

View File

@ -77,7 +77,7 @@ func TestInitialize(t *testing.T) {
privKey string
vpnHandler vpnHandler
initVPN bool
errExpected bool
wantErr bool
}{
"initialize some gcp instances": {
existingState: testGcpState,
@ -116,7 +116,7 @@ func TestInitialize(t *testing.T) {
vpnHandler: &stubVPNHandler{applyErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
wantErr: true,
},
"invalid create vpn config": {
existingState: testAzureState,
@ -127,7 +127,7 @@ func TestInitialize(t *testing.T) {
vpnHandler: &stubVPNHandler{createErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
wantErr: true,
},
"invalid write vpn config": {
existingState: testAzureState,
@ -138,7 +138,7 @@ func TestInitialize(t *testing.T) {
vpnHandler: &stubVPNHandler{marshalErr: someErr},
initVPN: true,
privKey: testKey,
errExpected: true,
wantErr: true,
},
"no state exists": {
existingState: state.ConstellationState{},
@ -146,7 +146,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"no instances to pick one": {
existingState: state.ConstellationState{
@ -157,7 +157,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"public key to short": {
existingState: testGcpState,
@ -165,7 +165,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: base64.StdEncoding.EncodeToString([]byte("tooShortKey")),
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"public key to long": {
existingState: testGcpState,
@ -173,7 +173,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: base64.StdEncoding.EncodeToString([]byte("thisWireguardKeyIsToLongAndHasTooManyBytes")),
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"public key not base64": {
existingState: testGcpState,
@ -181,7 +181,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: "this is not base64 encoded",
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail Connect": {
existingState: testGcpState,
@ -189,7 +189,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail Activate": {
existingState: testGcpState,
@ -197,7 +197,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient WriteLogStream": {
existingState: testGcpState,
@ -205,7 +205,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient getKubeconfig": {
existingState: testGcpState,
@ -213,7 +213,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient getCoordinatorVpnKey": {
existingState: testGcpState,
@ -221,7 +221,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient getClientVpnIp": {
existingState: testGcpState,
@ -229,7 +229,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient getOwnerID": {
existingState: testGcpState,
@ -237,7 +237,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail respClient getClusterID": {
existingState: testGcpState,
@ -245,7 +245,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail to wait for required status": {
existingState: testGcpState,
@ -253,7 +253,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{waitForAllErr: someErr},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
"fail to create service account": {
existingState: testGcpState,
@ -262,7 +262,7 @@ func TestInitialize(t *testing.T) {
waiter: &stubStatusWaiter{},
privKey: testKey,
vpnHandler: &stubVPNHandler{},
errExpected: true,
wantErr: true,
},
}
@ -294,7 +294,7 @@ func TestInitialize(t *testing.T) {
err := initialize(ctx, cmd, tc.client, &tc.serviceAccountCreator, fileHandler, tc.waiter, tc.vpnHandler)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
require.NoError(err)
@ -345,26 +345,26 @@ func TestInitCompletion(t *testing.T) {
testCases := map[string]struct {
args []string
toComplete string
resultExpected []string
shellCDExpected cobra.ShellCompDirective
wantResult []string
wantShellCD cobra.ShellCompDirective
}{
"first arg": {
args: []string{},
toComplete: "hello",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveDefault,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveDefault,
},
"secnod arg": {
args: []string{"23"},
toComplete: "/test/h",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveError,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveError,
},
"third arg": {
args: []string{"./file", "sth"},
toComplete: "./file",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveError,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveError,
},
}
@ -374,8 +374,8 @@ func TestInitCompletion(t *testing.T) {
cmd := &cobra.Command{}
result, shellCD := initCompletion(cmd, tc.args, tc.toComplete)
assert.Equal(tc.resultExpected, result)
assert.Equal(tc.shellCDExpected, shellCD)
assert.Equal(tc.wantResult, result)
assert.Equal(tc.wantShellCD, shellCD)
})
}
}
@ -406,55 +406,55 @@ func TestReadOrGeneratedMasterSecret(t *testing.T) {
filecontent string
createFile bool
fs func() afero.Fs
errExpected bool
wantErr bool
}{
"file with secret exists": {
filename: "someSecret",
filecontent: base64.StdEncoding.EncodeToString([]byte("ConstellationSecret")),
createFile: true,
fs: afero.NewMemMapFs,
errExpected: false,
wantErr: false,
},
"no file given": {
filename: "",
filecontent: "",
fs: afero.NewMemMapFs,
errExpected: false,
wantErr: false,
},
"file does not exist": {
filename: "nonExistingSecret",
filecontent: "",
createFile: false,
fs: afero.NewMemMapFs,
errExpected: true,
wantErr: true,
},
"file is empty": {
filename: "emptySecret",
filecontent: "",
createFile: true,
fs: afero.NewMemMapFs,
errExpected: true,
wantErr: true,
},
"secret too short": {
filename: "shortSecret",
filecontent: base64.StdEncoding.EncodeToString([]byte("short")),
createFile: true,
fs: afero.NewMemMapFs,
errExpected: true,
wantErr: true,
},
"secret not encoded": {
filename: "unencodedSecret",
filecontent: "Constellation",
createFile: true,
fs: afero.NewMemMapFs,
errExpected: true,
wantErr: true,
},
"file not writeable": {
filename: "",
filecontent: "",
createFile: false,
fs: func() afero.Fs { return afero.NewReadOnlyFs(afero.NewMemMapFs()) },
errExpected: true,
wantErr: true,
},
}
@ -472,7 +472,7 @@ func TestReadOrGeneratedMasterSecret(t *testing.T) {
var out bytes.Buffer
secret, err := readOrGeneratedMasterSecret(&out, fileHandler, tc.filename)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -16,7 +16,7 @@ import (
func TestTerminateCmdArgumentValidation(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"no args": {[]string{}, false},
"some args": {[]string{"hello", "test"}, true},
@ -30,7 +30,7 @@ func TestTerminateCmdArgumentValidation(t *testing.T) {
cmd := newTerminateCmd()
err := cmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -31,7 +31,7 @@ func TestAskToConfirm(t *testing.T) {
testCases := map[string]struct {
input string
expectedErr error
wantErr error
}{
"user confirms": {"y\n", nil},
"user confirms long": {"yes\n", nil},
@ -53,7 +53,7 @@ func TestAskToConfirm(t *testing.T) {
cmd.SetIn(in)
err := cmd.Execute()
assert.ErrorIs(err, tc.expectedErr)
assert.ErrorIs(err, tc.wantErr)
output, err := io.ReadAll(out)
assert.NoError(err)
@ -68,8 +68,8 @@ func TestWarnAboutPCRs(t *testing.T) {
testCases := map[string]struct {
pcrs map[uint32][]byte
dontWarnInit bool
expectedWarnings []string
errExpected bool
wantWarnings []string
wantErr bool
}{
"no warnings": {
pcrs: map[uint32][]byte{
@ -114,7 +114,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
12: zero,
},
expectedWarnings: []string{"BIOS"},
wantWarnings: []string{"BIOS"},
},
"warn for OPROM": {
pcrs: map[uint32][]byte{
@ -128,7 +128,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
12: zero,
},
expectedWarnings: []string{"OPROM"},
wantWarnings: []string{"OPROM"},
},
"warn for MBR": {
pcrs: map[uint32][]byte{
@ -142,7 +142,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
12: zero,
},
expectedWarnings: []string{"MBR"},
wantWarnings: []string{"MBR"},
},
"warn for kernel": {
pcrs: map[uint32][]byte{
@ -156,7 +156,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
12: zero,
},
expectedWarnings: []string{"kernel"},
wantWarnings: []string{"kernel"},
},
"warn for initrd": {
pcrs: map[uint32][]byte{
@ -170,7 +170,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
12: zero,
},
expectedWarnings: []string{"initrd"},
wantWarnings: []string{"initrd"},
},
"warn for initialization": {
pcrs: map[uint32][]byte{
@ -185,7 +185,7 @@ func TestWarnAboutPCRs(t *testing.T) {
11: zero,
},
dontWarnInit: false,
expectedWarnings: []string{"initialization"},
wantWarnings: []string{"initialization"},
},
"don't warn for initialization": {
pcrs: map[uint32][]byte{
@ -203,7 +203,7 @@ func TestWarnAboutPCRs(t *testing.T) {
},
"multi warning": {
pcrs: map[uint32][]byte{},
expectedWarnings: []string{
wantWarnings: []string{
"BIOS",
"OPROM",
"MBR",
@ -216,7 +216,7 @@ func TestWarnAboutPCRs(t *testing.T) {
pcrs: map[uint32][]byte{
0: []byte("000"),
},
errExpected: true,
wantErr: true,
},
}
@ -231,14 +231,14 @@ func TestWarnAboutPCRs(t *testing.T) {
cmd.SetErr(&errOut)
err := warnAboutPCRs(cmd, tc.pcrs, !tc.dontWarnInit)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
if len(tc.expectedWarnings) == 0 {
if len(tc.wantWarnings) == 0 {
assert.Empty(errOut.String())
} else {
for _, warning := range tc.expectedWarnings {
for _, warning := range tc.wantWarnings {
assert.Contains(errOut.String(), warning)
}
}

View File

@ -10,7 +10,7 @@ import (
func TestIsIntArg(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"valid int 1": {[]string{"1"}, false},
"valid int 2": {[]string{"42"}, false},
@ -31,7 +31,7 @@ func TestIsIntArg(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -43,7 +43,7 @@ func TestIsIntArg(t *testing.T) {
func TestIsIntGreaterArg(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"valid int 1": {[]string{"13"}, false},
"valid int 2": {[]string{"42"}, false},
@ -61,7 +61,7 @@ func TestIsIntGreaterArg(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -73,7 +73,7 @@ func TestIsIntGreaterArg(t *testing.T) {
func TestIsIntGreaterZeroArg(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"valid int 1": {[]string{"13"}, false},
"valid int 2": {[]string{"42"}, false},
@ -91,7 +91,7 @@ func TestIsIntGreaterZeroArg(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -103,7 +103,7 @@ func TestIsIntGreaterZeroArg(t *testing.T) {
func TestIsEC2InstanceType(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"is instance type 1": {[]string{"4xl"}, false},
"is instance type 2": {[]string{"12xlarge", "something else"}, false},
@ -119,7 +119,7 @@ func TestIsEC2InstanceType(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -131,7 +131,7 @@ func TestIsEC2InstanceType(t *testing.T) {
func TestIsGCPInstanceType(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"is instance type 1": {[]string{"n2d-standard-4"}, false},
"is instance type 2": {[]string{"n2d-standard-16", "something else"}, false},
@ -147,7 +147,7 @@ func TestIsGCPInstanceType(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -159,7 +159,7 @@ func TestIsGCPInstanceType(t *testing.T) {
func TestIsAzureInstanceType(t *testing.T) {
testCases := map[string]struct {
args []string
expectErr bool
wantErr bool
}{
"is instance type 1": {[]string{"Standard_DC2as_v5"}, false},
"is instance type 2": {[]string{"Standard_DC8as_v5", "something else"}, false},
@ -175,7 +175,7 @@ func TestIsAzureInstanceType(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -189,7 +189,7 @@ func TestIsInstanceTypeForProvider(t *testing.T) {
typePos int
providerPos int
args []string
expectErr bool
wantErr bool
}{
"valid gcp type 1": {1, 0, []string{"gcp", "n2d-standard-4"}, false},
"valid gcp type 2": {1, 0, []string{"gcp", "n2d-standard-16", "foo"}, false},
@ -213,7 +213,7 @@ func TestIsInstanceTypeForProvider(t *testing.T) {
err := testCmd.ValidateArgs(tc.args)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -13,27 +13,27 @@ func TestGetAzureValidator(t *testing.T) {
testCases := map[string]struct {
ownerID string
clusterID string
errExpected bool
wantErr bool
}{
"no input": {
ownerID: "",
clusterID: "",
errExpected: true,
wantErr: true,
},
"unencoded secret ID": {
ownerID: "owner-id",
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: true,
wantErr: true,
},
"unencoded cluster ID": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: "unique-id",
errExpected: true,
wantErr: true,
},
"correct input": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: false,
wantErr: false,
},
}
@ -56,7 +56,7 @@ func TestGetAzureValidator(t *testing.T) {
0: []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
1: []byte("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"),
})
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -13,27 +13,27 @@ func TestGetGCPNonCVMValidator(t *testing.T) {
testCases := map[string]struct {
ownerID string
clusterID string
errExpected bool
wantErr bool
}{
"no input": {
ownerID: "",
clusterID: "",
errExpected: true,
wantErr: true,
},
"unencoded secret ID": {
ownerID: "owner-id",
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: true,
wantErr: true,
},
"unencoded cluster ID": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: "unique-id",
errExpected: true,
wantErr: true,
},
"correct input": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: false,
wantErr: false,
},
}
@ -53,7 +53,7 @@ func TestGetGCPNonCVMValidator(t *testing.T) {
cmd.SetErr(&errOut)
_, err := getGCPNonCVMValidator(cmd, map[uint32][]byte{})
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -13,27 +13,27 @@ func TestGetGCPValidator(t *testing.T) {
testCases := map[string]struct {
ownerID string
clusterID string
errExpected bool
wantErr bool
}{
"no input": {
ownerID: "",
clusterID: "",
errExpected: true,
wantErr: true,
},
"unencoded secret ID": {
ownerID: "owner-id",
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: true,
wantErr: true,
},
"unencoded cluster ID": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: "unique-id",
errExpected: true,
wantErr: true,
},
"correct input": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: false,
wantErr: false,
},
}
@ -56,7 +56,7 @@ func TestGetGCPValidator(t *testing.T) {
0: []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
1: []byte("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"),
})
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -26,37 +26,37 @@ func TestVerify(t *testing.T) {
connErr error
checkErr error
state state.State
errExpected bool
wantErr bool
}{
"connection error": {
connErr: errors.New("connection error"),
checkErr: nil,
state: 0,
errExpected: true,
wantErr: true,
},
"check error": {
connErr: nil,
checkErr: errors.New("check error"),
state: 0,
errExpected: true,
wantErr: true,
},
"check error, rpc status": {
connErr: nil,
checkErr: rpcStatus.Error(codes.Unavailable, "check error"),
state: 0,
errExpected: true,
wantErr: true,
},
"verify on worker node": {
connErr: nil,
checkErr: nil,
state: state.IsNode,
errExpected: false,
wantErr: false,
},
"verify on master node": {
connErr: nil,
checkErr: nil,
state: state.ActivatingNodes,
errExpected: false,
wantErr: false,
},
}
@ -81,7 +81,7 @@ func TestVerify(t *testing.T) {
}
err := verify(ctx, &out, "", []atls.Validator{gcp.NewValidator(pcrs)}, verifier)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -132,27 +132,27 @@ func TestPrepareValidator(t *testing.T) {
testCases := map[string]struct {
ownerID string
clusterID string
errExpected bool
wantErr bool
}{
"no input": {
ownerID: "",
clusterID: "",
errExpected: true,
wantErr: true,
},
"unencoded secret ID": {
ownerID: "owner-id",
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: true,
wantErr: true,
},
"unencoded cluster ID": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: "unique-id",
errExpected: true,
wantErr: true,
},
"correct input": {
ownerID: base64.StdEncoding.EncodeToString([]byte("owner-id")),
clusterID: base64.StdEncoding.EncodeToString([]byte("unique-id")),
errExpected: false,
wantErr: false,
},
}
@ -177,7 +177,7 @@ func TestPrepareValidator(t *testing.T) {
}
err := prepareValidator(cmd, pcrs)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -207,57 +207,57 @@ func TestAddOrSkipPcr(t *testing.T) {
pcrMap map[uint32][]byte
pcrIndex uint32
encoded string
expectedEntries int
errExpected bool
wantEntries int
wantErr bool
}{
"empty input, empty map": {
pcrMap: emptyMap,
pcrIndex: 10,
encoded: "",
expectedEntries: 0,
errExpected: false,
wantEntries: 0,
wantErr: false,
},
"empty input, default map": {
pcrMap: defaultMap,
pcrIndex: 10,
encoded: "",
expectedEntries: len(defaultMap),
errExpected: false,
wantEntries: len(defaultMap),
wantErr: false,
},
"correct input, empty map": {
pcrMap: emptyMap,
pcrIndex: 10,
encoded: base64.StdEncoding.EncodeToString([]byte("Constellation")),
expectedEntries: 1,
errExpected: false,
wantEntries: 1,
wantErr: false,
},
"correct input, default map": {
pcrMap: defaultMap,
pcrIndex: 10,
encoded: base64.StdEncoding.EncodeToString([]byte("Constellation")),
expectedEntries: len(defaultMap) + 1,
errExpected: false,
wantEntries: len(defaultMap) + 1,
wantErr: false,
},
"unencoded input, empty map": {
pcrMap: emptyMap,
pcrIndex: 10,
encoded: "Constellation",
expectedEntries: 0,
errExpected: true,
wantEntries: 0,
wantErr: true,
},
"unencoded input, default map": {
pcrMap: defaultMap,
pcrIndex: 10,
encoded: "Constellation",
expectedEntries: len(defaultMap),
errExpected: true,
wantEntries: len(defaultMap),
wantErr: true,
},
"empty input at occupied index": {
pcrMap: defaultMap,
pcrIndex: 0,
encoded: "",
expectedEntries: len(defaultMap) - 1,
errExpected: false,
wantEntries: len(defaultMap) - 1,
wantErr: false,
},
}
@ -272,12 +272,12 @@ func TestAddOrSkipPcr(t *testing.T) {
err := addOrSkipPCR(res, tc.pcrIndex, tc.encoded)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
}
assert.Len(res, tc.expectedEntries)
assert.Len(res, tc.wantEntries)
for _, v := range res {
assert.Len(v, 32)
}
@ -289,26 +289,26 @@ func TestVerifyCompletion(t *testing.T) {
testCases := map[string]struct {
args []string
toComplete string
resultExpected []string
shellCDExpected cobra.ShellCompDirective
wantResult []string
wantShellCD cobra.ShellCompDirective
}{
"first arg": {
args: []string{},
toComplete: "192.0.2.1",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveNoFileComp,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveNoFileComp,
},
"second arg": {
args: []string{"192.0.2.1"},
toComplete: "443",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveNoFileComp,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveNoFileComp,
},
"third arg": {
args: []string{"192.0.2.1", "443"},
toComplete: "./file",
resultExpected: []string{},
shellCDExpected: cobra.ShellCompDirectiveError,
wantResult: []string{},
wantShellCD: cobra.ShellCompDirectiveError,
},
}
@ -318,8 +318,8 @@ func TestVerifyCompletion(t *testing.T) {
cmd := &cobra.Command{}
result, shellCD := verifyCompletion(cmd, tc.args, tc.toComplete)
assert.Equal(tc.resultExpected, result)
assert.Equal(tc.shellCDExpected, shellCD)
assert.Equal(tc.wantResult, result)
assert.Equal(tc.wantShellCD, shellCD)
})
}
}

View File

@ -41,7 +41,7 @@ func TestCreateInstances(t *testing.T) {
api stubAPI
instances ec2.Instances
securityGroup string
errExpected bool
wantErr bool
wantInstances ec2.Instances
}{
"create": {
@ -69,7 +69,7 @@ func TestCreateInstances(t *testing.T) {
api: stubAPI{instances: testInstances},
instances: ec2.Instances{"id-1": {}, "id-4": {}, "id-5": {}},
securityGroup: "sg-test",
errExpected: false,
wantErr: false,
wantInstances: ec2.Instances{
"id-1": {PublicIP: "192.0.2.1", PrivateIP: "192.0.2.2"},
"id-2": {PublicIP: "192.0.2.3", PrivateIP: "192.0.2.4"},
@ -80,22 +80,22 @@ func TestCreateInstances(t *testing.T) {
},
"client has no security group": {
api: stubAPI{},
errExpected: true,
wantErr: true,
},
"run API error": {
api: stubAPI{runInstancesErr: someErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
"runDryRun API error": {
api: stubAPI{runInstancesDryRunErr: &someErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
"runDryRun missing expected API error": {
api: stubAPI{runInstancesDryRunErr: &noErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
}
@ -120,7 +120,7 @@ func TestCreateInstances(t *testing.T) {
err := client.CreateInstances(context.Background(), input)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -144,12 +144,12 @@ func TestTerminateInstances(t *testing.T) {
testCases := map[string]struct {
api stubAPI
instances ec2.Instances
errExpected bool
wantErr bool
}{
"client with instances": {
api: stubAPI{instances: testAWSInstances},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"client no instances set": {
api: stubAPI{},
@ -157,17 +157,17 @@ func TestTerminateInstances(t *testing.T) {
"terminate API error": {
api: stubAPI{terminateInstancesErr: someErr},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"terminateDryRun API error": {
api: stubAPI{terminateInstancesDryRunErr: &someErr},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"terminateDryRun miss expected API error": {
api: stubAPI{terminateInstancesDryRunErr: &noErr},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
}
@ -185,7 +185,7 @@ func TestTerminateInstances(t *testing.T) {
}
err := client.TerminateInstances(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -199,7 +199,7 @@ func TestWaitStateRunning(t *testing.T) {
testCases := map[string]struct {
api api
instances ec2.Instances
errExpected bool
wantErr bool
}{
"instances are running": {
api: stubAPI{instances: []types.Instance{
@ -217,7 +217,7 @@ func TestWaitStateRunning(t *testing.T) {
},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"one instance running, rest nil": {
api: stubAPI{instances: []types.Instance{
@ -229,7 +229,7 @@ func TestWaitStateRunning(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"one instance terminated, rest nil": {
api: stubAPI{instances: []types.Instance{
@ -241,7 +241,7 @@ func TestWaitStateRunning(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"instances with different state": {
api: stubAPI{instances: []types.Instance{
@ -256,7 +256,7 @@ func TestWaitStateRunning(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"all instances have nil state": {
api: stubAPI{instances: []types.Instance{
@ -265,11 +265,11 @@ func TestWaitStateRunning(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"client has no instances": {
api: &stubAPI{},
errExpected: true,
wantErr: true,
},
}
@ -286,7 +286,7 @@ func TestWaitStateRunning(t *testing.T) {
}
err := client.waitStateRunning(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -299,7 +299,7 @@ func TestWaitStateTerminated(t *testing.T) {
testCases := map[string]struct {
api api
instances ec2.Instances
errExpected bool
wantErr bool
}{
"instances are terminated": {
api: stubAPI{instances: []types.Instance{
@ -317,7 +317,7 @@ func TestWaitStateTerminated(t *testing.T) {
},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"one instance terminated, rest nil": {
api: stubAPI{instances: []types.Instance{
@ -329,7 +329,7 @@ func TestWaitStateTerminated(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"one instance running, rest nil": {
api: stubAPI{instances: []types.Instance{
@ -341,7 +341,7 @@ func TestWaitStateTerminated(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"instances with different state": {
api: stubAPI{instances: []types.Instance{
@ -356,7 +356,7 @@ func TestWaitStateTerminated(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"all instances have nil state": {
api: stubAPI{instances: []types.Instance{
@ -365,11 +365,11 @@ func TestWaitStateTerminated(t *testing.T) {
{InstanceId: aws.String("id-3")},
}},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
"client has no instances": {
api: &stubAPI{},
errExpected: true,
wantErr: true,
},
}
@ -387,7 +387,7 @@ func TestWaitStateTerminated(t *testing.T) {
}
err := client.waitStateTerminated(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -405,21 +405,21 @@ func TestTagInstances(t *testing.T) {
testCases := map[string]struct {
api stubAPI
instances ec2.Instances
errExpected bool
wantErr bool
}{
"tag": {
api: stubAPI{},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: false,
wantErr: false,
},
"client without instances": {
api: stubAPI{createTagsErr: errors.New("failed")},
errExpected: true,
wantErr: true,
},
"tag API error": {
api: stubAPI{createTagsErr: errors.New("failed")},
instances: ec2.Instances{"id-1": {}, "id-2": {}, "id-3": {}},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -436,7 +436,7 @@ func TestTagInstances(t *testing.T) {
}
err := client.tagInstances(context.Background(), testTags)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -450,7 +450,7 @@ func TestEc2RunInstanceInput(t *testing.T) {
testCases := []struct {
in CreateInput
outExpected awsec2.RunInstancesInput
wantOutput awsec2.RunInstancesInput
}{
{
in: CreateInput{
@ -459,7 +459,7 @@ func TestEc2RunInstanceInput(t *testing.T) {
Count: 13,
securityGroupIds: []string{"test-sec-group"},
},
outExpected: awsec2.RunInstancesInput{
wantOutput: awsec2.RunInstancesInput{
ImageId: aws.String("test-image"),
InstanceType: types.InstanceTypeC5a4xlarge,
MinCount: aws.Int32(int32(13)),
@ -475,7 +475,7 @@ func TestEc2RunInstanceInput(t *testing.T) {
Count: 2,
securityGroupIds: []string{"test-sec-group-2"},
},
outExpected: awsec2.RunInstancesInput{
wantOutput: awsec2.RunInstancesInput{
ImageId: aws.String("test-image-2"),
InstanceType: types.InstanceTypeC5a12xlarge,
MinCount: aws.Int32(int32(2)),
@ -488,6 +488,6 @@ func TestEc2RunInstanceInput(t *testing.T) {
for _, tc := range testCases {
out := tc.in.AWS()
assert.Equal(tc.outExpected, *out)
assert.Equal(tc.wantOutput, *out)
}
}

View File

@ -44,44 +44,44 @@ func TestCreateSecurityGroup(t *testing.T) {
api stubAPI
securityGroup string
input SecurityGroupInput
errExpected bool
securityGroupExpected string
wantErr bool
wantSecurityGroup string
}{
"create security group": {
api: stubAPI{securityGroup: types.SecurityGroup{GroupId: aws.String("sg-test")}},
input: testInput,
securityGroupExpected: "sg-test",
wantSecurityGroup: "sg-test",
},
"create security group without permissions": {
api: stubAPI{securityGroup: types.SecurityGroup{GroupId: aws.String("sg-test")}},
input: SecurityGroupInput{},
securityGroupExpected: "sg-test",
wantSecurityGroup: "sg-test",
},
"client already has security group": {
api: stubAPI{},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"create returns nil security group ID": {
api: stubAPI{securityGroup: types.SecurityGroup{GroupId: nil}},
input: testInput,
errExpected: true,
wantErr: true,
},
"create API error": {
api: stubAPI{createSecurityGroupErr: someErr},
input: testInput,
errExpected: true,
wantErr: true,
},
"create DryRun API error": {
api: stubAPI{createSecurityGroupDryRunErr: &someErr},
input: testInput,
errExpected: true,
wantErr: true,
},
"create DryRun missing expected error": {
api: stubAPI{createSecurityGroupDryRunErr: &noErr},
input: testInput,
errExpected: true,
wantErr: true,
},
"authorize error": {
api: stubAPI{
@ -89,7 +89,7 @@ func TestCreateSecurityGroup(t *testing.T) {
authorizeSecurityGroupIngressErr: someErr,
},
input: testInput,
errExpected: true,
wantErr: true,
},
}
@ -103,11 +103,11 @@ func TestCreateSecurityGroup(t *testing.T) {
client.securityGroup = tc.securityGroup
err = client.CreateSecurityGroup(context.Background(), tc.input)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
assert.Equal(tc.securityGroupExpected, client.securityGroup)
assert.Equal(tc.wantSecurityGroup, client.securityGroup)
}
})
}
@ -120,7 +120,7 @@ func TestDeleteSecurityGroup(t *testing.T) {
testCases := map[string]struct {
api stubAPI
securityGroup string
errExpected bool
wantErr bool
}{
"delete security group": {
api: stubAPI{},
@ -132,17 +132,17 @@ func TestDeleteSecurityGroup(t *testing.T) {
"delete API error": {
api: stubAPI{deleteSecurityGroupErr: someErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
"delete DryRun API error": {
api: stubAPI{deleteSecurityGroupDryRunErr: &someErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
"delete DryRun missing expected error": {
api: stubAPI{deleteSecurityGroupDryRunErr: &noErr},
securityGroup: "sg-test",
errExpected: true,
wantErr: true,
},
}
@ -156,7 +156,7 @@ func TestDeleteSecurityGroup(t *testing.T) {
client.securityGroup = tc.securityGroup
err = client.DeleteSecurityGroup(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -198,54 +198,54 @@ func TestAuthorizeSecurityGroup(t *testing.T) {
api stubAPI
securityGroup string
input SecurityGroupInput
errExpected bool
wantErr bool
}{
"authorize": {
api: stubAPI{},
securityGroup: "sg-test",
input: testInput,
errExpected: false,
wantErr: false,
},
"client without security group": {
api: stubAPI{},
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeIngress API error": {
api: stubAPI{authorizeSecurityGroupIngressErr: someErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeIngress DryRun API error": {
api: stubAPI{authorizeSecurityGroupIngressDryRunErr: &someErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeIngress DryRun missing expected error": {
api: stubAPI{authorizeSecurityGroupIngressDryRunErr: &noErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeEgress API error": {
api: stubAPI{authorizeSecurityGroupEgressErr: someErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeEgress DryRun API error": {
api: stubAPI{authorizeSecurityGroupEgressDryRunErr: &someErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
"authorizeEgress DryRun missing expected error": {
api: stubAPI{authorizeSecurityGroupEgressDryRunErr: &noErr},
securityGroup: "sg-test",
input: testInput,
errExpected: true,
wantErr: true,
},
}
@ -259,7 +259,7 @@ func TestAuthorizeSecurityGroup(t *testing.T) {
client.securityGroup = tc.securityGroup
err = client.authorizeSecurityGroup(context.Background(), tc.input)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -9,22 +9,22 @@ import (
func TestIDs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(expectedIDs, testState.IDs())
wantIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(wantIDs, testState.IDs())
}
func TestPublicIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(expectedIPs, testState.PublicIPs())
wantIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(wantIPs, testState.PublicIPs())
}
func TestPrivateIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(expectedIPs, testState.PrivateIPs())
wantIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(wantIPs, testState.PrivateIPs())
}
func TestGetOne(t *testing.T) {
@ -43,9 +43,9 @@ func TestGetOthers(t *testing.T) {
for _, id := range testCases {
others := testInstances().GetOthers(id)
assert.NotContains(others, id)
expectedInstances := testInstances()
delete(expectedInstances, id)
assert.ElementsMatch(others.IDs(), expectedInstances.IDs())
wantInstances := testInstances()
delete(wantInstances, id)
assert.ElementsMatch(others.IDs(), wantInstances.IDs())
}
}

View File

@ -21,7 +21,7 @@ func TestTagsAws(t *testing.T) {
Value: "Bar",
},
}
expected := []types.Tag{
wantTags := []types.Tag{
{
Key: aws.String("Name"),
Value: aws.String("Test"),
@ -33,5 +33,5 @@ func TestTagsAws(t *testing.T) {
}
awsTags := testTags.AWS()
assert.Equal(expected, awsTags)
assert.Equal(wantTags, awsTags)
}

View File

@ -9,6 +9,6 @@ import (
func TestAutoscalingNodeGroup(t *testing.T) {
assert := assert.New(t)
nodeGroups := AutoscalingNodeGroup("some-project", "some-zone", "some-group", 0, 100)
expectedNodeGroups := "0:100:https://www.googleapis.com/compute/v1/projects/some-project/zones/some-zone/instanceGroups/some-group"
assert.Equal(expectedNodeGroups, nodeGroups)
wantNodeGroups := "0:100:https://www.googleapis.com/compute/v1/projects/some-project/zones/some-zone/instanceGroups/some-group"
assert.Equal(wantNodeGroups, nodeGroups)
}

View File

@ -14,7 +14,7 @@ import (
func TestSetGetState(t *testing.T) {
testCases := map[string]struct {
state state.ConstellationState
errExpected bool
wantErr bool
}{
"valid state": {
state: state.ConstellationState{
@ -68,7 +68,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing coordinator": {
state: state.ConstellationState{
@ -92,7 +92,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing node group": {
state: state.ConstellationState{
@ -121,7 +121,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing coordinator group": {
state: state.ConstellationState{
@ -150,7 +150,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing project id": {
state: state.ConstellationState{
@ -179,7 +179,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing zone": {
state: state.ConstellationState{
@ -208,7 +208,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing region": {
state: state.ConstellationState{
@ -237,7 +237,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing name": {
state: state.ConstellationState{
@ -265,7 +265,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing uid": {
state: state.ConstellationState{
@ -294,7 +294,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing firewalls": {
state: state.ConstellationState{
@ -323,7 +323,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing network": {
state: state.ConstellationState{
@ -351,7 +351,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing external network": {
state: state.ConstellationState{
@ -380,7 +380,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing subnetwork": {
state: state.ConstellationState{
@ -409,7 +409,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing external subnetwork": {
state: state.ConstellationState{
@ -438,7 +438,7 @@ func TestSetGetState(t *testing.T) {
GCPNodeInstanceTemplate: "temp-id",
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing node template": {
state: state.ConstellationState{
@ -467,7 +467,7 @@ func TestSetGetState(t *testing.T) {
GCPFirewalls: []string{"fw-1", "fw-2"},
GCPCoordinatorInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
"missing coordinator template": {
state: state.ConstellationState{
@ -496,7 +496,7 @@ func TestSetGetState(t *testing.T) {
GCPFirewalls: []string{"fw-1", "fw-2"},
GCPNodeInstanceTemplate: "temp-id",
},
errExpected: true,
wantErr: true,
},
}
@ -506,7 +506,7 @@ func TestSetGetState(t *testing.T) {
assert := assert.New(t)
client := Client{}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.SetState(tc.state))
} else {
assert.NoError(client.SetState(tc.state))
@ -550,7 +550,7 @@ func TestSetGetState(t *testing.T) {
coordinatorTemplate: tc.state.GCPCoordinatorInstanceTemplate,
serviceAccount: tc.state.GCPServiceAccount,
}
if tc.errExpected {
if tc.wantErr {
_, err := client.GetState()
assert.Error(err)
} else {

View File

@ -57,7 +57,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI instanceGroupManagersAPI
input CreateInstancesInput
network string
errExpected bool
wantErr bool
}{
"successful create": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -75,7 +75,7 @@ func TestCreateInstances(t *testing.T) {
instanceTemplateAPI: stubInstanceTemplateAPI{},
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{instances: testManagedInstances}},
input: testInput,
errExpected: true,
wantErr: true,
},
"failed wait zonal op": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -85,7 +85,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{instances: testManagedInstances}},
network: "network",
input: testInput,
errExpected: true,
wantErr: true,
},
"failed wait global op": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -95,7 +95,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{instances: testManagedInstances}},
network: "network",
input: testInput,
errExpected: true,
wantErr: true,
},
"failed insert template": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -105,7 +105,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{instances: testManagedInstances}},
input: testInput,
network: "network",
errExpected: true,
wantErr: true,
},
"failed insert instanceGroupManager": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -115,7 +115,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{insertErr: someErr},
network: "network",
input: testInput,
errExpected: true,
wantErr: true,
},
"failed instanceGroupManager iterator": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{instances: testInstances}},
@ -125,7 +125,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{nextErr: someErr}},
network: "network",
input: testInput,
errExpected: true,
wantErr: true,
},
"failed instance iterator": {
instanceAPI: stubInstanceAPI{listIterator: &stubInstanceIterator{nextErr: someErr}},
@ -135,7 +135,7 @@ func TestCreateInstances(t *testing.T) {
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{listIterator: &stubManagedInstanceIterator{instances: testManagedInstances}},
network: "network",
input: testInput,
errExpected: true,
wantErr: true,
},
}
@ -161,7 +161,7 @@ func TestCreateInstances(t *testing.T) {
coordinators: make(gcp.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateInstances(ctx, tc.input))
} else {
assert.NoError(client.CreateInstances(ctx, tc.input))
@ -187,7 +187,7 @@ func TestTerminateInstances(t *testing.T) {
instanceGroupManagersAPI instanceGroupManagersAPI
missingNodeInstanceGroup bool
errExpected bool
wantErr bool
}{
"successful terminate": {
operationZoneAPI: stubOperationZoneAPI{},
@ -207,14 +207,14 @@ func TestTerminateInstances(t *testing.T) {
operationGlobalAPI: stubOperationGlobalAPI{},
instanceTemplateAPI: stubInstanceTemplateAPI{},
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{deleteErr: someErr},
errExpected: true,
wantErr: true,
},
"fail delete instanceTemplate": {
operationZoneAPI: stubOperationZoneAPI{},
operationGlobalAPI: stubOperationGlobalAPI{},
instanceTemplateAPI: stubInstanceTemplateAPI{deleteErr: someErr},
instanceGroupManagersAPI: stubInstanceGroupManagersAPI{},
errExpected: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -245,7 +245,7 @@ func TestTerminateInstances(t *testing.T) {
client.nodes = gcp.Instances{}
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.TerminateInstances(ctx))
} else {
assert.NoError(client.TerminateInstances(ctx))

View File

@ -23,7 +23,7 @@ func TestCreateVPCs(t *testing.T) {
operationRegionAPI operationRegionAPI
networksAPI networksAPI
subnetworksAPI subnetworksAPI
errExpected bool
wantErr bool
}{
"successful create": {
operationGlobalAPI: stubOperationGlobalAPI{},
@ -36,28 +36,28 @@ func TestCreateVPCs(t *testing.T) {
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
"failed wait region op": {
operationGlobalAPI: stubOperationGlobalAPI{},
operationRegionAPI: stubOperationRegionAPI{waitErr: someErr},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
"failed insert networks": {
operationGlobalAPI: stubOperationGlobalAPI{},
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{insertErr: someErr},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
"failed insert subnetworks": {
operationGlobalAPI: stubOperationGlobalAPI{},
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{insertErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -79,7 +79,7 @@ func TestCreateVPCs(t *testing.T) {
coordinators: make(gcp.Instances),
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateVPCs(ctx, testInput))
} else {
assert.NoError(client.CreateVPCs(ctx, testInput))
@ -97,7 +97,7 @@ func TestTerminateVPCs(t *testing.T) {
networksAPI networksAPI
subnetworksAPI subnetworksAPI
firewalls []string
errExpected bool
wantErr bool
}{
"successful terminate": {
operationGlobalAPI: stubOperationGlobalAPI{},
@ -110,21 +110,21 @@ func TestTerminateVPCs(t *testing.T) {
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
"failed delete networks": {
operationGlobalAPI: stubOperationGlobalAPI{},
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{deleteErr: someErr},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
"failed delete subnetworks": {
operationGlobalAPI: stubOperationGlobalAPI{},
operationRegionAPI: stubOperationRegionAPI{},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{deleteErr: someErr},
errExpected: true,
wantErr: true,
},
"must delete firewalls first": {
firewalls: []string{"firewall-1", "firewall-2"},
@ -132,7 +132,7 @@ func TestTerminateVPCs(t *testing.T) {
operationGlobalAPI: stubOperationGlobalAPI{},
networksAPI: stubNetworksAPI{},
subnetworksAPI: stubSubnetworksAPI{},
errExpected: true,
wantErr: true,
},
}
@ -155,7 +155,7 @@ func TestTerminateVPCs(t *testing.T) {
subnetwork: "subnetwork-id-1",
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.TerminateVPCs(ctx))
} else {
assert.NoError(client.TerminateVPCs(ctx))
@ -192,7 +192,7 @@ func TestCreateFirewall(t *testing.T) {
operationGlobalAPI operationGlobalAPI
firewallsAPI firewallsAPI
firewallInput FirewallInput
errExpected bool
wantErr bool
}{
"successful create": {
network: "network",
@ -203,18 +203,18 @@ func TestCreateFirewall(t *testing.T) {
network: "network",
operationGlobalAPI: stubOperationGlobalAPI{waitErr: someErr},
firewallsAPI: stubFirewallsAPI{},
errExpected: true,
wantErr: true,
},
"failed insert networks": {
network: "network",
operationGlobalAPI: stubOperationGlobalAPI{},
firewallsAPI: stubFirewallsAPI{insertErr: someErr},
errExpected: true,
wantErr: true,
},
"no network set": {
operationGlobalAPI: stubOperationGlobalAPI{},
firewallsAPI: stubFirewallsAPI{},
errExpected: true,
wantErr: true,
},
}
@ -233,7 +233,7 @@ func TestCreateFirewall(t *testing.T) {
firewallsAPI: tc.firewallsAPI,
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.CreateFirewall(ctx, testFirewallInput))
} else {
assert.NoError(client.CreateFirewall(ctx, testFirewallInput))
@ -250,7 +250,7 @@ func TestTerminateFirewall(t *testing.T) {
operationGlobalAPI operationGlobalAPI
firewallsAPI firewallsAPI
firewalls []string
errExpected bool
wantErr bool
}{
"successful terminate": {
operationGlobalAPI: stubOperationGlobalAPI{},
@ -266,13 +266,13 @@ func TestTerminateFirewall(t *testing.T) {
operationGlobalAPI: stubOperationGlobalAPI{waitErr: someErr},
firewallsAPI: stubFirewallsAPI{},
firewalls: []string{"firewall-1", "firewall-2"},
errExpected: true,
wantErr: true,
},
"failed to delete firewalls": {
operationGlobalAPI: stubOperationGlobalAPI{},
firewallsAPI: stubFirewallsAPI{deleteErr: someErr},
firewalls: []string{"firewall-1", "firewall-2"},
errExpected: true,
wantErr: true,
},
}
@ -291,7 +291,7 @@ func TestTerminateFirewall(t *testing.T) {
firewallsAPI: tc.firewallsAPI,
}
if tc.errExpected {
if tc.wantErr {
assert.Error(client.TerminateFirewall(ctx))
} else {
assert.NoError(client.TerminateFirewall(ctx))

View File

@ -16,7 +16,7 @@ func TestAddIAMPolicyBindings(t *testing.T) {
testCases := map[string]struct {
projectsAPI stubProjectsAPI
input AddIAMPolicyBindingInput
errExpected bool
wantErr bool
}{
"successful set without new bindings": {
input: AddIAMPolicyBindingInput{
@ -37,13 +37,13 @@ func TestAddIAMPolicyBindings(t *testing.T) {
projectsAPI: stubProjectsAPI{
getPolicyErr: someErr,
},
errExpected: true,
wantErr: true,
},
"setting iam policy fails": {
projectsAPI: stubProjectsAPI{
setPolicyErr: someErr,
},
errExpected: true,
wantErr: true,
},
}
@ -61,7 +61,7 @@ func TestAddIAMPolicyBindings(t *testing.T) {
}
err := client.addIAMPolicyBindings(ctx, tc.input)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -74,8 +74,8 @@ func TestAddIAMPolicy(t *testing.T) {
testCases := map[string]struct {
binding PolicyBinding
policy *iampb.Policy
errExpected bool
policyExpected *iampb.Policy
wantErr bool
wantPolicy *iampb.Policy
}{
"successful on empty policy": {
binding: PolicyBinding{
@ -85,7 +85,7 @@ func TestAddIAMPolicy(t *testing.T) {
policy: &iampb.Policy{
Bindings: []*iampb.Binding{},
},
policyExpected: &iampb.Policy{
wantPolicy: &iampb.Policy{
Bindings: []*iampb.Binding{
{
Role: "role",
@ -107,7 +107,7 @@ func TestAddIAMPolicy(t *testing.T) {
},
},
},
policyExpected: &iampb.Policy{
wantPolicy: &iampb.Policy{
Bindings: []*iampb.Binding{
{
Role: "other-role",
@ -133,7 +133,7 @@ func TestAddIAMPolicy(t *testing.T) {
},
},
},
policyExpected: &iampb.Policy{
wantPolicy: &iampb.Policy{
Bindings: []*iampb.Binding{
{
Role: "role",
@ -155,7 +155,7 @@ func TestAddIAMPolicy(t *testing.T) {
},
},
},
policyExpected: &iampb.Policy{
wantPolicy: &iampb.Policy{
Bindings: []*iampb.Binding{
{
Role: "role",
@ -171,7 +171,7 @@ func TestAddIAMPolicy(t *testing.T) {
assert := assert.New(t)
addIAMPolicy(tc.policy, tc.binding)
assert.True(proto.Equal(tc.policyExpected, tc.policy))
assert.True(proto.Equal(tc.wantPolicy, tc.policy))
})
}
}

View File

@ -33,7 +33,7 @@ func TestCreateServiceAccount(t *testing.T) {
iamAPI iamAPI
projectsAPI stubProjectsAPI
input ServiceAccountInput
errExpected bool
wantErr bool
}{
"successful create": {
iamAPI: stubIAMAPI{serviceAccountKeyData: keyData},
@ -46,29 +46,29 @@ func TestCreateServiceAccount(t *testing.T) {
},
"creating account fails": {
iamAPI: stubIAMAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
"creating account key fails": {
iamAPI: stubIAMAPI{createKeyErr: someErr},
errExpected: true,
wantErr: true,
},
"key data missing": {
iamAPI: stubIAMAPI{},
errExpected: true,
wantErr: true,
},
"key data corrupt": {
iamAPI: stubIAMAPI{serviceAccountKeyData: []byte("invalid key data")},
errExpected: true,
wantErr: true,
},
"retrieving iam policy bindings fails": {
iamAPI: stubIAMAPI{},
projectsAPI: stubProjectsAPI{getPolicyErr: someErr},
errExpected: true,
wantErr: true,
},
"setting iam policy bindings fails": {
iamAPI: stubIAMAPI{},
projectsAPI: stubProjectsAPI{setPolicyErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -87,7 +87,7 @@ func TestCreateServiceAccount(t *testing.T) {
}
serviceAccountKey, err := client.CreateServiceAccount(ctx, tc.input)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -101,7 +101,7 @@ func TestCreateServiceAccount(t *testing.T) {
func TestTerminateServiceAccount(t *testing.T) {
testCases := map[string]struct {
iamAPI iamAPI
errExpected bool
wantErr bool
}{
"delete works": {
iamAPI: stubIAMAPI{},
@ -110,7 +110,7 @@ func TestTerminateServiceAccount(t *testing.T) {
iamAPI: stubIAMAPI{
deleteServiceAccountErr: errors.New("someErr"),
},
errExpected: true,
wantErr: true,
},
}
@ -129,7 +129,7 @@ func TestTerminateServiceAccount(t *testing.T) {
}
err := client.TerminateServiceAccount(ctx)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -9,22 +9,22 @@ import (
func TestIDs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(expectedIDs, testState.IDs())
wantIDs := []string{"id-9", "id-10", "id-11", "id-12"}
assert.ElementsMatch(wantIDs, testState.IDs())
}
func TestPublicIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(expectedIPs, testState.PublicIPs())
wantIPs := []string{"192.0.2.1", "192.0.2.3", "192.0.2.5", "192.0.2.7"}
assert.ElementsMatch(wantIPs, testState.PublicIPs())
}
func TestPrivateIPs(t *testing.T) {
assert := assert.New(t)
testState := testInstances()
expectedIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(expectedIPs, testState.PrivateIPs())
wantIPs := []string{"192.0.2.2", "192.0.2.4", "192.0.2.6", "192.0.2.8"}
assert.ElementsMatch(wantIPs, testState.PrivateIPs())
}
func TestGetOne(t *testing.T) {
@ -43,9 +43,9 @@ func TestGetOthers(t *testing.T) {
for _, id := range testCases {
others := testInstances().GetOthers(id)
assert.NotContains(others, id)
expectedInstances := testInstances()
delete(expectedInstances, id)
assert.ElementsMatch(others.IDs(), expectedInstances.IDs())
wantInstances := testInstances()
delete(wantInstances, id)
assert.ElementsMatch(others.IDs(), wantInstances.IDs())
}
}

View File

@ -73,42 +73,42 @@ func TestActivate(t *testing.T) {
avpn *stubAVPNClient
userPublicKey string
ips []string
errExpected bool
wantErr bool
}{
"normal activation": {
avpn: &stubAVPNClient{},
userPublicKey: testKey,
ips: []string{"192.0.2.1", "192.0.2.1", "192.0.2.1"},
errExpected: false,
wantErr: false,
},
"client without avpn": {
userPublicKey: testKey,
ips: []string{"192.0.2.1", "192.0.2.1", "192.0.2.1"},
errExpected: true,
wantErr: true,
},
"empty public key parameter": {
avpn: &stubAVPNClient{},
userPublicKey: "",
ips: []string{"192.0.2.1", "192.0.2.1", "192.0.2.1"},
errExpected: true,
wantErr: true,
},
"invalid public key parameter": {
avpn: &stubAVPNClient{},
userPublicKey: "invalid Key",
ips: []string{"192.0.2.1", "192.0.2.1", "192.0.2.1"},
errExpected: true,
wantErr: true,
},
"empty ips parameter": {
avpn: &stubAVPNClient{},
userPublicKey: testKey,
ips: []string{},
errExpected: true,
wantErr: true,
},
"fail ActivateAsCoordinator": {
avpn: &stubAVPNClient{activateAsCoordinatorErr: someErr},
userPublicKey: testKey,
ips: []string{"192.0.2.1", "192.0.2.1", "192.0.2.1"},
errExpected: true,
wantErr: true,
},
}
@ -121,7 +121,7 @@ func TestActivate(t *testing.T) {
client.avpn = tc.avpn
}
_, err := client.Activate(context.Background(), []byte(tc.userPublicKey), []byte("Constellation"), tc.ips, nil, nil, "serviceaccount://test")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -90,31 +90,31 @@ func TestNextLog(t *testing.T) {
testCases := map[string]struct {
msgs []*pubproto.ActivateAsCoordinatorResponse
logLenExpected int
stateExpected bool
wantLogLen int
wantState bool
recvErr error
errExpected bool
wantErr bool
}{
"some logs": {
msgs: []*pubproto.ActivateAsCoordinatorResponse{testLogResp, testLogResp, testLogResp},
logLenExpected: 3,
wantLogLen: 3,
},
"only admin config": {
msgs: []*pubproto.ActivateAsCoordinatorResponse{testConfigResp},
stateExpected: true,
wantState: true,
},
"logs and configs": {
msgs: []*pubproto.ActivateAsCoordinatorResponse{testLogResp, testConfigResp, testLogResp, testConfigResp},
logLenExpected: 2,
stateExpected: true,
wantLogLen: 2,
wantState: true,
},
"no response": {
msgs: []*pubproto.ActivateAsCoordinatorResponse{},
logLenExpected: 0,
wantLogLen: 0,
},
"recv fail": {
recvErr: someErr,
errExpected: true,
wantErr: true,
},
}
@ -141,15 +141,15 @@ func TestNextLog(t *testing.T) {
}
assert.Error(err)
if tc.errExpected {
if tc.wantErr {
assert.NotErrorIs(err, io.EOF)
return
}
assert.ErrorIs(err, io.EOF)
assert.Len(logs, tc.logLenExpected)
assert.Len(logs, tc.wantLogLen)
if tc.stateExpected {
if tc.wantState {
ip, err := client.GetClientVpnIp()
assert.NoError(err)
assert.Equal(testClientVpnIp, ip)

View File

@ -22,7 +22,7 @@ func TestTLSConfig(t *testing.T) {
testCases := map[string]struct {
issuer Issuer
validators []Validator
expectErr bool
wantErr bool
}{
"basic": {
issuer: fakeIssuer{fakeOID: oid1},
@ -35,12 +35,12 @@ func TestTLSConfig(t *testing.T) {
"validate error": {
issuer: fakeIssuer{fakeOID: oid1},
validators: []Validator{fakeValidator{fakeOID: oid1, err: errors.New("failed")}},
expectErr: true,
wantErr: true,
},
"unknown oid": {
issuer: fakeIssuer{fakeOID: oid1},
validators: []Validator{fakeValidator{fakeOID: oid2}},
expectErr: true,
wantErr: true,
},
}
@ -79,7 +79,7 @@ func TestTLSConfig(t *testing.T) {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, http.NoBody)
require.NoError(err)
resp, err := client.Do(req)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -12,11 +12,11 @@ import (
func TestGetSNPAttestation(t *testing.T) {
testCases := map[string]struct {
tpmFunc vtpm.TPMOpenFunc
errExpected bool
wantErr bool
}{
"success": {
tpmFunc: simulator.OpenSimulatedTPM,
errExpected: false,
wantErr: false,
},
}
@ -30,7 +30,7 @@ func TestGetSNPAttestation(t *testing.T) {
defer tpm.Close()
_, err = getSNPAttestation(tpm)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -25,12 +25,12 @@ func TestTrustedKeyFromSNP(t *testing.T) {
testCases := map[string]struct {
key []byte
instanceInfo []byte
errExpected bool
wantErr bool
}{
"success": {
key: akPub,
instanceInfo: []byte{},
errExpected: false,
wantErr: false,
},
}
@ -39,7 +39,7 @@ func TestTrustedKeyFromSNP(t *testing.T) {
assert := assert.New(t)
key, err := trustedKeyFromSNP(tc.key, tc.instanceInfo)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -52,11 +52,11 @@ func TestTrustedKeyFromSNP(t *testing.T) {
func TestValidateAzureCVM(t *testing.T) {
testCases := map[string]struct {
attDoc vtpm.AttestationDocument
errExpected bool
wantErr bool
}{
"success": {
attDoc: vtpm.AttestationDocument{},
errExpected: false,
wantErr: false,
},
}
@ -65,7 +65,7 @@ func TestValidateAzureCVM(t *testing.T) {
assert := assert.New(t)
err := validateAzureCVM(tc.attDoc)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -14,7 +14,7 @@ import (
func TestGetGCEInstanceInfo(t *testing.T) {
testCases := map[string]struct {
client fakeMetadataClient
errExpected bool
wantErr bool
}{
"success": {
client: fakeMetadataClient{
@ -22,7 +22,7 @@ func TestGetGCEInstanceInfo(t *testing.T) {
instanceNameString: "instanceName",
zoneString: "zone",
},
errExpected: false,
wantErr: false,
},
"projectID error": {
client: fakeMetadataClient{
@ -31,7 +31,7 @@ func TestGetGCEInstanceInfo(t *testing.T) {
zoneString: "zone",
projecIdErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
"instanceName error": {
client: fakeMetadataClient{
@ -40,7 +40,7 @@ func TestGetGCEInstanceInfo(t *testing.T) {
zoneString: "zone",
instanceNameErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
"zone error": {
client: fakeMetadataClient{
@ -49,7 +49,7 @@ func TestGetGCEInstanceInfo(t *testing.T) {
zoneString: "zone",
zoneErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
}
@ -60,7 +60,7 @@ func TestGetGCEInstanceInfo(t *testing.T) {
var tpm io.ReadWriteCloser
out, err := getGCEInstanceInfo(tc.client)(tpm)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -20,7 +20,7 @@ import (
func TestGceNonHostInfoEvent(t *testing.T) {
testCases := map[string]struct {
attDoc vtpm.AttestationDocument
errExpected bool
wantErr bool
}{
"is cvm": {
attDoc: vtpm.AttestationDocument{
@ -33,7 +33,7 @@ func TestGceNonHostInfoEvent(t *testing.T) {
attDoc: vtpm.AttestationDocument{
Attestation: nil,
},
errExpected: true,
wantErr: true,
},
"missing GCE Non-Host info event": {
attDoc: vtpm.AttestationDocument{
@ -41,7 +41,7 @@ func TestGceNonHostInfoEvent(t *testing.T) {
EventLog: []byte("No GCE Event"),
},
},
errExpected: true,
wantErr: true,
},
"not a cvm": {
attDoc: vtpm.AttestationDocument{
@ -49,7 +49,7 @@ func TestGceNonHostInfoEvent(t *testing.T) {
EventLog: []byte("\x00\x00\x00GCE NonHostInfo\x00\x00\x00\x00"),
},
},
errExpected: true,
wantErr: true,
},
}
@ -57,7 +57,7 @@ func TestGceNonHostInfoEvent(t *testing.T) {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
err := gceNonHostInfoEvent(tc.attDoc)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -85,7 +85,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
testCases := map[string]struct {
instanceInfo []byte
getClient func(ctx context.Context, opts ...option.ClientOption) (gcpRestClient, error)
errExpected bool
wantErr bool
}{
"success": {
instanceInfo: mustMarshal(attest.GCEInstanceInfo{}, require.New(t)),
@ -94,7 +94,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
EkPub: proto.String(testPubK),
},
}, nil, nil),
errExpected: false,
wantErr: false,
},
"Unmarshal error": {
instanceInfo: []byte("error"),
@ -103,12 +103,12 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
EkPub: proto.String(testPubK),
},
}, nil, nil),
errExpected: true,
wantErr: true,
},
"empty signing key": {
instanceInfo: mustMarshal(attest.GCEInstanceInfo{}, require.New(t)),
getClient: prepareFakeClient(&computepb.ShieldedInstanceIdentity{}, nil, nil),
errExpected: true,
wantErr: true,
},
"new client error": {
instanceInfo: mustMarshal(attest.GCEInstanceInfo{}, require.New(t)),
@ -117,7 +117,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
EkPub: proto.String(testPubK),
},
}, errors.New("error"), nil),
errExpected: true,
wantErr: true,
},
"GetShieldedInstanceIdentity error": {
instanceInfo: mustMarshal(attest.GCEInstanceInfo{}, require.New(t)),
@ -126,7 +126,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
EkPub: proto.String(testPubK),
},
}, nil, errors.New("error")),
errExpected: true,
wantErr: true,
},
"Decode error": {
instanceInfo: mustMarshal(attest.GCEInstanceInfo{}, require.New(t)),
@ -135,7 +135,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
EkPub: proto.String("Not a public key"),
},
}, nil, nil),
errExpected: true,
wantErr: true,
},
}
@ -145,7 +145,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
out, err := trustedKeyFromGCEAPI(tc.getClient)(nil, tc.instanceInfo)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -86,13 +86,13 @@ func TestValidate(t *testing.T) {
validator *Validator
attDoc []byte
nonce []byte
errExpected bool
wantErr bool
}{
"invalid nonce": {
validator: NewValidator(fakeTrustedPcrs, fakeGetTrustedKey, fakeValidateCVM, VerifyPKCS1v15),
attDoc: mustMarshalAttestation(attDoc, require),
nonce: []byte{4, 3, 2, 1},
errExpected: true,
wantErr: true,
},
"invalid signature": {
validator: NewValidator(fakeTrustedPcrs, fakeGetTrustedKey, fakeValidateCVM, VerifyPKCS1v15),
@ -103,7 +103,7 @@ func TestValidate(t *testing.T) {
UserDataSignature: attDoc.UserDataSignature,
}, require),
nonce: nonce,
errExpected: true,
wantErr: true,
},
"untrusted attestation public key": {
validator: NewValidator(
@ -114,7 +114,7 @@ func TestValidate(t *testing.T) {
fakeValidateCVM, VerifyPKCS1v15),
attDoc: mustMarshalAttestation(attDoc, require),
nonce: nonce,
errExpected: true,
wantErr: true,
},
"not a CVM": {
validator: NewValidator(
@ -126,7 +126,7 @@ func TestValidate(t *testing.T) {
VerifyPKCS1v15),
attDoc: mustMarshalAttestation(attDoc, require),
nonce: nonce,
errExpected: true,
wantErr: true,
},
"untrusted PCRs": {
validator: NewValidator(
@ -138,7 +138,7 @@ func TestValidate(t *testing.T) {
VerifyPKCS1v15),
attDoc: mustMarshalAttestation(attDoc, require),
nonce: nonce,
errExpected: true,
wantErr: true,
},
"no sha256 quote": {
validator: NewValidator(fakeTrustedPcrs, fakeGetTrustedKey, fakeValidateCVM, VerifyPKCS1v15),
@ -156,13 +156,13 @@ func TestValidate(t *testing.T) {
UserDataSignature: attDoc.UserDataSignature,
}, require),
nonce: nonce,
errExpected: true,
wantErr: true,
},
"invalid attestation document": {
validator: NewValidator(fakeTrustedPcrs, fakeGetTrustedKey, fakeValidateCVM, VerifyPKCS1v15),
attDoc: []byte("invalid attestation"),
nonce: nonce,
errExpected: true,
wantErr: true,
},
}
@ -171,7 +171,7 @@ func TestValidate(t *testing.T) {
assert := assert.New(t)
_, err = tc.validator.Validate(tc.attDoc, tc.nonce)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -249,8 +249,8 @@ func TestFailIssuer(t *testing.T) {
func TestGetSHA256QuoteIndex(t *testing.T) {
testCases := map[string]struct {
quotes []*tpm.Quote
idxExpected int
errExpected bool
wantIdx int
wantErr bool
}{
"idx 0 is valid": {
quotes: []*tpm.Quote{
@ -260,8 +260,8 @@ func TestGetSHA256QuoteIndex(t *testing.T) {
},
},
},
idxExpected: 0,
errExpected: false,
wantIdx: 0,
wantErr: false,
},
"idx 1 is valid": {
quotes: []*tpm.Quote{
@ -276,16 +276,16 @@ func TestGetSHA256QuoteIndex(t *testing.T) {
},
},
},
idxExpected: 1,
errExpected: false,
wantIdx: 1,
wantErr: false,
},
"no quotes": {
quotes: nil,
errExpected: true,
wantErr: true,
},
"quotes is nil": {
quotes: make([]*tpm.Quote, 2),
errExpected: true,
wantErr: true,
},
"pcrs is nil": {
quotes: []*tpm.Quote{
@ -298,7 +298,7 @@ func TestGetSHA256QuoteIndex(t *testing.T) {
Pcrs: nil,
},
},
errExpected: true,
wantErr: true,
},
}
@ -307,12 +307,12 @@ func TestGetSHA256QuoteIndex(t *testing.T) {
assert := assert.New(t)
idx, err := GetSHA256QuoteIndex(tc.quotes)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
assert.Equal(0, idx)
} else {
assert.NoError(err)
assert.Equal(tc.idxExpected, idx)
assert.Equal(tc.wantIdx, idx)
}
})
}
@ -322,7 +322,7 @@ func TestGetSelectedPCRs(t *testing.T) {
testCases := map[string]struct {
openFunc TPMOpenFunc
pcrSelection tpm2.PCRSelection
errExpected bool
wantErr bool
}{
"error": {
openFunc: func() (io.ReadWriteCloser, error) { return nil, errors.New("error") },
@ -330,7 +330,7 @@ func TestGetSelectedPCRs(t *testing.T) {
Hash: tpm2.AlgSHA256,
PCRs: []int{0, 1, 2},
},
errExpected: true,
wantErr: true,
},
"3 PCRs": {
openFunc: tpmsim.OpenSimulatedTPM,
@ -355,7 +355,7 @@ func TestGetSelectedPCRs(t *testing.T) {
assert := assert.New(t)
pcrs, err := GetSelectedPCRs(tc.openFunc, tc.pcrSelection)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
require.NoError(err)

View File

@ -54,22 +54,22 @@ func TestIsNodeInitialized(t *testing.T) {
testCases := map[string]struct {
pcrValueOwnerID []byte
pcrValueClusterID []byte
expectInitialized bool
expectErr bool
wantInitialized bool
wantErr bool
}{
"uninitialized PCRs results in uninitialized node": {},
"initializing PCRs result in initialized node": {
pcrValueOwnerID: []byte{0x0, 0x1, 0x2, 0x3},
pcrValueClusterID: []byte{0x4, 0x5, 0x6, 0x7},
expectInitialized: true,
wantInitialized: true,
},
"initializing ownerID alone fails": {
pcrValueOwnerID: []byte{0x0, 0x1, 0x2, 0x3},
expectErr: true,
wantErr: true,
},
"initializing clusterID alone fails": {
pcrValueClusterID: []byte{0x4, 0x5, 0x6, 0x7},
expectErr: true,
wantErr: true,
},
}
@ -89,12 +89,12 @@ func TestIsNodeInitialized(t *testing.T) {
initialized, err := IsNodeInitialized(func() (io.ReadWriteCloser, error) {
return &simTPMNOPCloser{tpm}, nil
})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.Equal(tc.expectInitialized, initialized)
require.Equal(tc.wantInitialized, initialized)
})
}
}

View File

@ -15,13 +15,13 @@ func TestAutoscalerSecrets(t *testing.T) {
testCases := map[string]struct {
instance core.Instance
cloudServiceAccountURI string
expectedSecrets resources.Secrets
expectErr bool
wantSecrets resources.Secrets
wantErr bool
}{
"Secrets works": {
instance: core.Instance{ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name"},
cloudServiceAccountURI: "serviceaccount://azure?tenant_id=tenant-id&client_id=client-id&client_secret=client-secret",
expectedSecrets: resources.Secrets{
wantSecrets: resources.Secrets{
&k8s.Secret{
TypeMeta: meta.TypeMeta{
Kind: "Secret",
@ -44,12 +44,12 @@ func TestAutoscalerSecrets(t *testing.T) {
},
"invalid providerID fails": {
instance: core.Instance{ProviderID: "invalid"},
expectErr: true,
wantErr: true,
},
"invalid cloudServiceAccountURI fails": {
instance: core.Instance{ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name"},
cloudServiceAccountURI: "invalid",
expectErr: true,
wantErr: true,
},
}
@ -60,12 +60,12 @@ func TestAutoscalerSecrets(t *testing.T) {
autoscaler := Autoscaler{}
secrets, err := autoscaler.Secrets(tc.instance, tc.cloudServiceAccountURI)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSecrets, secrets)
assert.Equal(tc.wantSecrets, secrets)
})
}
}

View File

@ -15,13 +15,13 @@ func TestSecrets(t *testing.T) {
testCases := map[string]struct {
instance core.Instance
cloudServiceAccountURI string
expectedSecrets resources.Secrets
expectErr bool
wantSecrets resources.Secrets
wantErr bool
}{
"Secrets works": {
instance: core.Instance{ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name"},
cloudServiceAccountURI: "serviceaccount://azure?tenant_id=tenant-id&client_id=client-id&client_secret=client-secret&location=location",
expectedSecrets: resources.Secrets{
wantSecrets: resources.Secrets{
&k8s.Secret{
TypeMeta: meta.TypeMeta{
Kind: "Secret",
@ -40,7 +40,7 @@ func TestSecrets(t *testing.T) {
"Secrets works for scale sets": {
instance: core.Instance{ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id"},
cloudServiceAccountURI: "serviceaccount://azure?tenant_id=tenant-id&client_id=client-id&client_secret=client-secret&location=location",
expectedSecrets: resources.Secrets{
wantSecrets: resources.Secrets{
&k8s.Secret{
TypeMeta: meta.TypeMeta{
Kind: "Secret",
@ -58,12 +58,12 @@ func TestSecrets(t *testing.T) {
},
"invalid providerID fails": {
instance: core.Instance{ProviderID: "invalid"},
expectErr: true,
wantErr: true,
},
"invalid cloudServiceAccountURI fails": {
instance: core.Instance{ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name"},
cloudServiceAccountURI: "invalid",
expectErr: true,
wantErr: true,
},
}
@ -74,12 +74,12 @@ func TestSecrets(t *testing.T) {
cloud := CloudControllerManager{}
secrets, err := cloud.Secrets(tc.instance, tc.cloudServiceAccountURI)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSecrets, secrets)
assert.Equal(tc.wantSecrets, secrets)
})
}
}

View File

@ -24,18 +24,18 @@ func TestRetrieve(t *testing.T) {
}
testCases := map[string]struct {
server httpBufconnServer
expectErr bool
expectedResponse metadataResponse
wantErr bool
wantResponse metadataResponse
}{
"metadata response parsed": {
server: newHTTPBufconnServerWithMetadataResponse(response),
expectedResponse: response,
wantResponse: response,
},
"invalid imds response detected": {
server: newHTTPBufconnServer(func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintln(writer, "invalid-result")
}),
expectErr: true,
wantErr: true,
},
}
@ -59,12 +59,12 @@ func TestRetrieve(t *testing.T) {
}
resp, err := iClient.Retrieve(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedResponse, resp)
assert.Equal(tc.wantResponse, resp)
})
}
}

View File

@ -15,7 +15,7 @@ import (
)
func TestList(t *testing.T) {
expectedInstances := []core.Instance{
wantInstances := []core.Instance{
{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
@ -36,8 +36,8 @@ func TestList(t *testing.T) {
virtualMachinesAPI virtualMachinesAPI
virtualMachineScaleSetVMsAPI virtualMachineScaleSetVMsAPI
tagsAPI tagsAPI
expectErr bool
expectedInstances []core.Instance
wantErr bool
wantInstances []core.Instance
}{
"List works": {
imdsAPI: newIMDSStub(),
@ -46,20 +46,20 @@ func TestList(t *testing.T) {
virtualMachinesAPI: newVirtualMachinesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
tagsAPI: newTagsStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"providerID cannot be retrieved": {
imdsAPI: &stubIMDSAPI{retrieveErr: errors.New("imds err")},
expectErr: true,
wantErr: true,
},
"providerID cannot be parsed": {
imdsAPI: newInvalidIMDSStub(),
expectErr: true,
wantErr: true,
},
"listVMs fails": {
imdsAPI: newIMDSStub(),
virtualMachinesAPI: newFailingListsVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
"listScaleSetVMs fails": {
imdsAPI: newIMDSStub(),
@ -68,7 +68,7 @@ func TestList(t *testing.T) {
virtualMachinesAPI: newVirtualMachinesStub(),
virtualMachineScaleSetVMsAPI: newFailingListsVirtualMachineScaleSetsVMsStub(),
tagsAPI: newTagsStub(),
expectErr: true,
wantErr: true,
},
}
@ -87,24 +87,24 @@ func TestList(t *testing.T) {
}
instances, err := metadata.List(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedInstances, instances)
assert.ElementsMatch(tc.wantInstances, instances)
})
}
}
func TestSelf(t *testing.T) {
expectedVMInstance := core.Instance{
wantVMInstance := core.Instance{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
IPs: []string{"192.0.2.0"},
SSHKeys: map[string][]string{"user": {"key-data"}},
}
expectedScaleSetInstance := core.Instance{
wantScaleSetInstance := core.Instance{
Name: "scale-set-name-instance-id",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
IPs: []string{"192.0.2.0"},
@ -115,31 +115,31 @@ func TestSelf(t *testing.T) {
networkInterfacesAPI networkInterfacesAPI
virtualMachinesAPI virtualMachinesAPI
virtualMachineScaleSetVMsAPI virtualMachineScaleSetVMsAPI
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"self for individual instance works": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newVirtualMachinesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
expectedInstance: expectedVMInstance,
wantInstance: wantVMInstance,
},
"self for scale set instance works": {
imdsAPI: newScaleSetIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newVirtualMachinesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
expectedInstance: expectedScaleSetInstance,
wantInstance: wantScaleSetInstance,
},
"providerID cannot be retrieved": {
imdsAPI: &stubIMDSAPI{retrieveErr: errors.New("imds err")},
expectErr: true,
wantErr: true,
},
"GetInstance fails": {
imdsAPI: newIMDSStub(),
virtualMachinesAPI: newFailingGetVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
}
@ -156,12 +156,12 @@ func TestSelf(t *testing.T) {
}
instance, err := metadata.Self(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
@ -170,7 +170,7 @@ func TestSignalRole(t *testing.T) {
testCases := map[string]struct {
imdsAPI imdsAPI
tagsAPI tagsAPI
expectErr bool
wantErr bool
}{
"SignalRole works": {
imdsAPI: newIMDSStub(),
@ -181,12 +181,12 @@ func TestSignalRole(t *testing.T) {
},
"providerID cannot be retrieved": {
imdsAPI: &stubIMDSAPI{retrieveErr: errors.New("imds err")},
expectErr: true,
wantErr: true,
},
"setting tag fails": {
imdsAPI: newIMDSStub(),
tagsAPI: newFailingTagsStub(),
expectErr: true,
wantErr: true,
},
}
@ -201,7 +201,7 @@ func TestSignalRole(t *testing.T) {
}
err := metadata.SignalRole(context.Background(), role.Coordinator)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -225,20 +225,20 @@ func TestMetadataSupported(t *testing.T) {
func TestProviderID(t *testing.T) {
testCases := map[string]struct {
imdsAPI imdsAPI
expectErr bool
expectedProviderID string
wantErr bool
wantProviderID string
}{
"providerID for individual instance works": {
imdsAPI: newIMDSStub(),
expectedProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
wantProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
},
"providerID for scale set instance works": {
imdsAPI: newScaleSetIMDSStub(),
expectedProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
wantProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
},
"imds retrieval fails": {
imdsAPI: &stubIMDSAPI{retrieveErr: errors.New("imds err")},
expectErr: true,
wantErr: true,
},
}
@ -252,12 +252,12 @@ func TestProviderID(t *testing.T) {
}
providerID, err := metadata.providerID(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedProviderID, providerID)
assert.Equal(tc.wantProviderID, providerID)
})
}
}
@ -265,23 +265,23 @@ func TestProviderID(t *testing.T) {
func TestExtractBasicsFromProviderID(t *testing.T) {
testCases := map[string]struct {
providerID string
expectErr bool
expectedSubscriptionID string
expectedResourceGroup string
wantErr bool
wantSubscriptionID string
wantResourceGroup string
}{
"providerID for individual instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
expectedSubscriptionID: "subscription-id",
expectedResourceGroup: "resource-group",
wantSubscriptionID: "subscription-id",
wantResourceGroup: "resource-group",
},
"providerID for scale set instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
expectedSubscriptionID: "subscription-id",
expectedResourceGroup: "resource-group",
wantSubscriptionID: "subscription-id",
wantResourceGroup: "resource-group",
},
"providerID is malformed": {
providerID: "malformed-provider-id",
expectErr: true,
wantErr: true,
},
}
@ -292,13 +292,13 @@ func TestExtractBasicsFromProviderID(t *testing.T) {
subscriptionID, resourceGroup, err := extractBasicsFromProviderID(tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSubscriptionID, subscriptionID)
assert.Equal(tc.expectedResourceGroup, resourceGroup)
assert.Equal(tc.wantSubscriptionID, subscriptionID)
assert.Equal(tc.wantResourceGroup, resourceGroup)
})
}
}
@ -306,15 +306,15 @@ func TestExtractBasicsFromProviderID(t *testing.T) {
func TestExtractInstanceTags(t *testing.T) {
testCases := map[string]struct {
in map[string]*string
expectedTags map[string]string
wantTags map[string]string
}{
"tags are extracted": {
in: map[string]*string{"key": to.StringPtr("value")},
expectedTags: map[string]string{"key": "value"},
wantTags: map[string]string{"key": "value"},
},
"nil values are skipped": {
in: map[string]*string{"key": nil},
expectedTags: map[string]string{},
wantTags: map[string]string{},
},
}
@ -324,7 +324,7 @@ func TestExtractInstanceTags(t *testing.T) {
tags := extractInstanceTags(tc.in)
assert.Equal(tc.expectedTags, tags)
assert.Equal(tc.wantTags, tags)
})
}
}
@ -332,7 +332,7 @@ func TestExtractInstanceTags(t *testing.T) {
func TestExtractSSHKeys(t *testing.T) {
testCases := map[string]struct {
in armcompute.SSHConfiguration
expectedKeys map[string][]string
wantKeys map[string][]string
}{
"ssh key is extracted": {
in: armcompute.SSHConfiguration{
@ -343,7 +343,7 @@ func TestExtractSSHKeys(t *testing.T) {
},
},
},
expectedKeys: map[string][]string{"user": {"key-data"}},
wantKeys: map[string][]string{"user": {"key-data"}},
},
"invalid path is skipped": {
in: armcompute.SSHConfiguration{
@ -354,7 +354,7 @@ func TestExtractSSHKeys(t *testing.T) {
},
},
},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"key data is nil": {
in: armcompute.SSHConfiguration{
@ -364,7 +364,7 @@ func TestExtractSSHKeys(t *testing.T) {
},
},
},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"path is nil": {
in: armcompute.SSHConfiguration{
@ -374,11 +374,11 @@ func TestExtractSSHKeys(t *testing.T) {
},
},
},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"public keys are nil": {
in: armcompute.SSHConfiguration{},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
}
@ -388,7 +388,7 @@ func TestExtractSSHKeys(t *testing.T) {
keys := extractSSHKeys(tc.in)
assert.Equal(tc.expectedKeys, keys)
assert.Equal(tc.wantKeys, keys)
})
}
}

View File

@ -12,7 +12,7 @@ import (
)
func TestGetVMInterfaces(t *testing.T) {
expectedConfigs := []*armnetwork.InterfaceIPConfiguration{
wantConfigs := []*armnetwork.InterfaceIPConfiguration{
{
Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("192.0.2.0"),
@ -33,23 +33,23 @@ func TestGetVMInterfaces(t *testing.T) {
testCases := map[string]struct {
vm armcompute.VirtualMachine
networkInterfacesAPI networkInterfacesAPI
expectErr bool
expectedConfigs []*armnetwork.InterfaceIPConfiguration
wantErr bool
wantConfigs []*armnetwork.InterfaceIPConfiguration
}{
"retrieval works": {
vm: vm,
networkInterfacesAPI: newNetworkInterfacesStub(),
expectedConfigs: expectedConfigs,
wantConfigs: wantConfigs,
},
"vm can have 0 interfaces": {
vm: armcompute.VirtualMachine{},
networkInterfacesAPI: newNetworkInterfacesStub(),
expectedConfigs: []*armnetwork.InterfaceIPConfiguration{},
wantConfigs: []*armnetwork.InterfaceIPConfiguration{},
},
"interface retrieval fails": {
vm: vm,
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
}
@ -63,18 +63,18 @@ func TestGetVMInterfaces(t *testing.T) {
}
configs, err := metadata.getVMInterfaces(context.Background(), tc.vm, "resource-group")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedConfigs, configs)
assert.Equal(tc.wantConfigs, configs)
})
}
}
func TestGetScaleSetVMInterfaces(t *testing.T) {
expectedConfigs := []*armnetwork.InterfaceIPConfiguration{
wantConfigs := []*armnetwork.InterfaceIPConfiguration{
{
Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("192.0.2.0"),
@ -95,23 +95,23 @@ func TestGetScaleSetVMInterfaces(t *testing.T) {
testCases := map[string]struct {
vm armcompute.VirtualMachineScaleSetVM
networkInterfacesAPI networkInterfacesAPI
expectErr bool
expectedConfigs []*armnetwork.InterfaceIPConfiguration
wantErr bool
wantConfigs []*armnetwork.InterfaceIPConfiguration
}{
"retrieval works": {
vm: vm,
networkInterfacesAPI: newNetworkInterfacesStub(),
expectedConfigs: expectedConfigs,
wantConfigs: wantConfigs,
},
"vm can have 0 interfaces": {
vm: armcompute.VirtualMachineScaleSetVM{},
networkInterfacesAPI: newNetworkInterfacesStub(),
expectedConfigs: []*armnetwork.InterfaceIPConfiguration{},
wantConfigs: []*armnetwork.InterfaceIPConfiguration{},
},
"interface retrieval fails": {
vm: vm,
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
}
@ -125,12 +125,12 @@ func TestGetScaleSetVMInterfaces(t *testing.T) {
}
configs, err := metadata.getScaleSetVMInterfaces(context.Background(), tc.vm, "resource-group", "scale-set-name", "instance-id")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedConfigs, configs)
assert.Equal(tc.wantConfigs, configs)
})
}
}
@ -138,7 +138,7 @@ func TestGetScaleSetVMInterfaces(t *testing.T) {
func TestExtractPrivateIPs(t *testing.T) {
testCases := map[string]struct {
interfaceIPConfigs []*armnetwork.InterfaceIPConfiguration
expectedIPs []string
wantIPs []string
}{
"extraction works": {
interfaceIPConfigs: []*armnetwork.InterfaceIPConfiguration{
@ -148,7 +148,7 @@ func TestExtractPrivateIPs(t *testing.T) {
},
},
},
expectedIPs: []string{"192.0.2.0"},
wantIPs: []string{"192.0.2.0"},
},
"can be empty": {
interfaceIPConfigs: []*armnetwork.InterfaceIPConfiguration{},
@ -166,7 +166,7 @@ func TestExtractPrivateIPs(t *testing.T) {
ips := extractPrivateIPs(tc.interfaceIPConfigs)
assert.ElementsMatch(tc.expectedIPs, ips)
assert.ElementsMatch(tc.wantIPs, ips)
})
}
}
@ -174,7 +174,7 @@ func TestExtractPrivateIPs(t *testing.T) {
func TestExtractInterfaceNamesFromInterfaceReferences(t *testing.T) {
testCases := map[string]struct {
references []*armcompute.NetworkInterfaceReference
expectedNames []string
wantNames []string
}{
"extraction with individual interface reference works": {
references: []*armcompute.NetworkInterfaceReference{
@ -182,7 +182,7 @@ func TestExtractInterfaceNamesFromInterfaceReferences(t *testing.T) {
ID: to.StringPtr("/subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Network/networkInterfaces/interface-name"),
},
},
expectedNames: []string{"interface-name"},
wantNames: []string{"interface-name"},
},
"extraction with scale set interface reference works": {
references: []*armcompute.NetworkInterfaceReference{
@ -190,7 +190,7 @@ func TestExtractInterfaceNamesFromInterfaceReferences(t *testing.T) {
ID: to.StringPtr("/subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id/networkInterfaces/interface-name"),
},
},
expectedNames: []string{"interface-name"},
wantNames: []string{"interface-name"},
},
"can be empty": {
references: []*armcompute.NetworkInterfaceReference{},
@ -208,7 +208,7 @@ func TestExtractInterfaceNamesFromInterfaceReferences(t *testing.T) {
names := extractInterfaceNamesFromInterfaceReferences(tc.references)
assert.ElementsMatch(tc.expectedNames, names)
assert.ElementsMatch(tc.wantNames, names)
})
}
}

View File

@ -15,7 +15,7 @@ import (
)
func TestGetScaleSetVM(t *testing.T) {
expectedInstance := core.Instance{
wantInstance := core.Instance{
Name: "scale-set-name-instance-id",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
IPs: []string{"192.0.2.0"},
@ -25,35 +25,35 @@ func TestGetScaleSetVM(t *testing.T) {
providerID string
networkInterfacesAPI networkInterfacesAPI
virtualMachineScaleSetVMsAPI virtualMachineScaleSetVMsAPI
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"getVM for scale set instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
expectedInstance: expectedInstance,
wantInstance: wantInstance,
},
"getVM for individual instance must fail": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
expectErr: true,
wantErr: true,
},
"Get fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
virtualMachineScaleSetVMsAPI: newFailingGetScaleSetVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
"retrieving interfaces fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
"conversion fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
virtualMachineScaleSetVMsAPI: newGetInvalidScaleSetVirtualMachinesStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
}
@ -68,18 +68,18 @@ func TestGetScaleSetVM(t *testing.T) {
}
instance, err := metadata.getScaleSetVM(context.Background(), tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
func TestListScaleSetVMs(t *testing.T) {
expectedInstances := []core.Instance{
wantInstances := []core.Instance{
{
Name: "scale-set-name-instance-id",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
@ -92,50 +92,50 @@ func TestListScaleSetVMs(t *testing.T) {
networkInterfacesAPI networkInterfacesAPI
virtualMachineScaleSetVMsAPI virtualMachineScaleSetVMsAPI
scaleSetsAPI scaleSetsAPI
expectErr bool
expectedInstances []core.Instance
wantErr bool
wantInstances []core.Instance
}{
"listVMs works": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
scaleSetsAPI: newScaleSetsStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"invalid scale sets are skipped": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
scaleSetsAPI: newListContainingNilScaleSetStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"listVMs can return 0 VMs": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: &stubVirtualMachineScaleSetVMsAPI{},
scaleSetsAPI: newScaleSetsStub(),
expectedInstances: []core.Instance{},
wantInstances: []core.Instance{},
},
"can skip nil in VM list": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newListContainingNilScaleSetVirtualMachinesStub(),
scaleSetsAPI: newScaleSetsStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"retrieving network interfaces fails": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newVirtualMachineScaleSetsVMsStub(),
scaleSetsAPI: newScaleSetsStub(),
expectErr: true,
wantErr: true,
},
"converting instance fails": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachineScaleSetVMsAPI: newListContainingInvalidScaleSetVirtualMachinesStub(),
scaleSetsAPI: newScaleSetsStub(),
expectErr: true,
wantErr: true,
},
}
@ -152,12 +152,12 @@ func TestListScaleSetVMs(t *testing.T) {
}
instances, err := metadata.listScaleSetVMs(context.Background(), "resource-group")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedInstances, instances)
assert.ElementsMatch(tc.wantInstances, instances)
})
}
}
@ -165,26 +165,26 @@ func TestListScaleSetVMs(t *testing.T) {
func TestSplitScaleSetProviderID(t *testing.T) {
testCases := map[string]struct {
providerID string
expectErr bool
expectedSubscriptionID string
expectedResourceGroup string
expectedScaleSet string
expectedInstanceID string
wantErr bool
wantSubscriptionID string
wantResourceGroup string
wantScaleSet string
wantInstanceID string
}{
"providerID for scale set instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
expectedSubscriptionID: "subscription-id",
expectedResourceGroup: "resource-group",
expectedScaleSet: "scale-set-name",
expectedInstanceID: "instance-id",
wantSubscriptionID: "subscription-id",
wantResourceGroup: "resource-group",
wantScaleSet: "scale-set-name",
wantInstanceID: "instance-id",
},
"providerID for individual instance must fail": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
expectErr: true,
wantErr: true,
},
"providerID is malformed": {
providerID: "malformed-provider-id",
expectErr: true,
wantErr: true,
},
}
@ -195,15 +195,15 @@ func TestSplitScaleSetProviderID(t *testing.T) {
subscriptionID, resourceGroup, scaleSet, instanceID, err := splitScaleSetProviderID(tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSubscriptionID, subscriptionID)
assert.Equal(tc.expectedResourceGroup, resourceGroup)
assert.Equal(tc.expectedScaleSet, scaleSet)
assert.Equal(tc.expectedInstanceID, instanceID)
assert.Equal(tc.wantSubscriptionID, subscriptionID)
assert.Equal(tc.wantResourceGroup, resourceGroup)
assert.Equal(tc.wantScaleSet, scaleSet)
assert.Equal(tc.wantInstanceID, instanceID)
})
}
}
@ -212,8 +212,8 @@ func TestConvertScaleSetVMToCoreInstance(t *testing.T) {
testCases := map[string]struct {
inVM armcompute.VirtualMachineScaleSetVM
inInterfaceIPConfigs []*armnetwork.InterfaceIPConfiguration
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"conversion works": {
inVM: armcompute.VirtualMachineScaleSetVM{
@ -233,7 +233,7 @@ func TestConvertScaleSetVMToCoreInstance(t *testing.T) {
},
},
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "scale-set-name-instance-id",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
IPs: []string{"192.0.2.0"},
@ -242,7 +242,7 @@ func TestConvertScaleSetVMToCoreInstance(t *testing.T) {
},
"invalid instance": {
inVM: armcompute.VirtualMachineScaleSetVM{},
expectErr: true,
wantErr: true,
},
}
@ -253,12 +253,12 @@ func TestConvertScaleSetVMToCoreInstance(t *testing.T) {
instance, err := convertScaleSetVMToCoreInstance("scale-set", tc.inVM, tc.inInterfaceIPConfigs)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
@ -266,19 +266,19 @@ func TestConvertScaleSetVMToCoreInstance(t *testing.T) {
func TestExtractScaleSetVMRole(t *testing.T) {
testCases := map[string]struct {
scaleSet string
expectedRole role.Role
wantRole role.Role
}{
"coordinator role": {
scaleSet: "constellation-scale-set-coordinators-abcd123",
expectedRole: role.Coordinator,
wantRole: role.Coordinator,
},
"node role": {
scaleSet: "constellation-scale-set-nodes-abcd123",
expectedRole: role.Node,
wantRole: role.Node,
},
"unknown role": {
scaleSet: "unknown",
expectedRole: role.Unknown,
wantRole: role.Unknown,
},
}
@ -288,7 +288,7 @@ func TestExtractScaleSetVMRole(t *testing.T) {
role := extractScaleSetVMRole(tc.scaleSet)
assert.Equal(tc.expectedRole, role)
assert.Equal(tc.wantRole, role)
})
}
}

View File

@ -17,24 +17,24 @@ func TestGetApplicationCredentials(t *testing.T) {
}
testCases := map[string]struct {
cloudServiceAccountURI string
expectedCreds client.ApplicationCredentials
expectErr bool
wantCreds client.ApplicationCredentials
wantErr bool
}{
"getApplicationCredentials works": {
cloudServiceAccountURI: "serviceaccount://azure?tenant_id=tenant-id&client_id=client-id&client_secret=client-secret&location=location",
expectedCreds: creds,
wantCreds: creds,
},
"invalid URI fails": {
cloudServiceAccountURI: "\x00",
expectErr: true,
wantErr: true,
},
"incorrect URI scheme fails": {
cloudServiceAccountURI: "invalid",
expectErr: true,
wantErr: true,
},
"incorrect URI host fails": {
cloudServiceAccountURI: "serviceaccount://incorrect",
expectErr: true,
wantErr: true,
},
}
@ -44,12 +44,12 @@ func TestGetApplicationCredentials(t *testing.T) {
require := require.New(t)
creds, err := getApplicationCredentials(tc.cloudServiceAccountURI)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedCreds, creds)
assert.Equal(tc.wantCreds, creds)
})
}
}

View File

@ -14,7 +14,7 @@ import (
)
func TestGetVM(t *testing.T) {
expectedInstance := core.Instance{
wantInstance := core.Instance{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
IPs: []string{"192.0.2.0"},
@ -24,35 +24,35 @@ func TestGetVM(t *testing.T) {
providerID string
networkInterfacesAPI networkInterfacesAPI
virtualMachinesAPI virtualMachinesAPI
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"getVM for individual instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newVirtualMachinesStub(),
expectedInstance: expectedInstance,
wantInstance: wantInstance,
},
"getVM for scale set instance must fail": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
expectErr: true,
wantErr: true,
},
"Get fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
virtualMachinesAPI: newFailingGetVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
"retrieving interfaces fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
virtualMachinesAPI: newVirtualMachinesStub(),
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
"conversion fails": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
virtualMachinesAPI: newGetInvalidVirtualMachinesStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
expectErr: true,
wantErr: true,
},
}
@ -67,18 +67,18 @@ func TestGetVM(t *testing.T) {
}
instance, err := metadata.getVM(context.Background(), tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
func TestListVMs(t *testing.T) {
expectedInstances := []core.Instance{
wantInstances := []core.Instance{
{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
@ -90,38 +90,38 @@ func TestListVMs(t *testing.T) {
imdsAPI imdsAPI
networkInterfacesAPI networkInterfacesAPI
virtualMachinesAPI virtualMachinesAPI
expectErr bool
expectedInstances []core.Instance
wantErr bool
wantInstances []core.Instance
}{
"listVMs works": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newVirtualMachinesStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"listVMs can return 0 VMs": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: &stubVirtualMachinesAPI{},
expectedInstances: []core.Instance{},
wantInstances: []core.Instance{},
},
"can skip nil in VM list": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newListContainingNilVirtualMachinesStub(),
expectedInstances: expectedInstances,
wantInstances: wantInstances,
},
"retrieving network interfaces fails": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newFailingNetworkInterfacesStub(),
virtualMachinesAPI: newVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
"converting instance fails": {
imdsAPI: newIMDSStub(),
networkInterfacesAPI: newNetworkInterfacesStub(),
virtualMachinesAPI: newListContainingInvalidVirtualMachinesStub(),
expectErr: true,
wantErr: true,
},
}
@ -137,12 +137,12 @@ func TestListVMs(t *testing.T) {
}
instances, err := metadata.listVMs(context.Background(), "resource-group")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedInstances, instances)
assert.ElementsMatch(tc.wantInstances, instances)
})
}
}
@ -151,7 +151,7 @@ func TestSetTag(t *testing.T) {
testCases := map[string]struct {
imdsAPI imdsAPI
tagsAPI tagsAPI
expectErr bool
wantErr bool
}{
"setTag works": {
imdsAPI: newIMDSStub(),
@ -160,12 +160,12 @@ func TestSetTag(t *testing.T) {
"retrieving resource ID fails": {
imdsAPI: newFailingIMDSStub(),
tagsAPI: newTagsStub(),
expectErr: true,
wantErr: true,
},
"updating tags fails": {
imdsAPI: newIMDSStub(),
tagsAPI: newFailingTagsStub(),
expectErr: true,
wantErr: true,
},
}
@ -180,7 +180,7 @@ func TestSetTag(t *testing.T) {
}
err := metadata.setTag(context.Background(), "key", "value")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -192,24 +192,24 @@ func TestSetTag(t *testing.T) {
func TestSplitVMProviderID(t *testing.T) {
testCases := map[string]struct {
providerID string
expectErr bool
expectedSubscriptionID string
expectedResourceGroup string
expectedInstanceName string
wantErr bool
wantSubscriptionID string
wantResourceGroup string
wantInstanceName string
}{
"providerID for individual instance works": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
expectedSubscriptionID: "subscription-id",
expectedResourceGroup: "resource-group",
expectedInstanceName: "instance-name",
wantSubscriptionID: "subscription-id",
wantResourceGroup: "resource-group",
wantInstanceName: "instance-name",
},
"providerID for scale set instance must fail": {
providerID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachineScaleSets/scale-set-name/virtualMachines/instance-id",
expectErr: true,
wantErr: true,
},
"providerID is malformed": {
providerID: "malformed-provider-id",
expectErr: true,
wantErr: true,
},
}
@ -220,14 +220,14 @@ func TestSplitVMProviderID(t *testing.T) {
subscriptionID, resourceGroup, instanceName, err := splitVMProviderID(tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSubscriptionID, subscriptionID)
assert.Equal(tc.expectedResourceGroup, resourceGroup)
assert.Equal(tc.expectedInstanceName, instanceName)
assert.Equal(tc.wantSubscriptionID, subscriptionID)
assert.Equal(tc.wantResourceGroup, resourceGroup)
assert.Equal(tc.wantInstanceName, instanceName)
})
}
}
@ -236,8 +236,8 @@ func TestConvertVMToCoreInstance(t *testing.T) {
testCases := map[string]struct {
inVM armcompute.VirtualMachine
inInterfaceIPConfigs []*armnetwork.InterfaceIPConfiguration
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"conversion works": {
inVM: armcompute.VirtualMachine{
@ -266,7 +266,7 @@ func TestConvertVMToCoreInstance(t *testing.T) {
},
},
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
IPs: []string{"192.0.2.0"},
@ -286,7 +286,7 @@ func TestConvertVMToCoreInstance(t *testing.T) {
},
},
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "instance-name",
ProviderID: "azure:///subscriptions/subscription-id/resourceGroups/resource-group/providers/Microsoft.Compute/virtualMachines/instance-name",
IPs: []string{"192.0.2.0"},
@ -295,7 +295,7 @@ func TestConvertVMToCoreInstance(t *testing.T) {
},
"invalid instance": {
inVM: armcompute.VirtualMachine{},
expectErr: true,
wantErr: true,
},
}
@ -306,12 +306,12 @@ func TestConvertVMToCoreInstance(t *testing.T) {
instance, err := convertVMToCoreInstance(tc.inVM, tc.inInterfaceIPConfigs)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}

View File

@ -16,12 +16,12 @@ import (
func TestConfigMaps(t *testing.T) {
testCases := map[string]struct {
instance core.Instance
expectedConfigMaps resources.ConfigMaps
expectErr bool
wantConfigMaps resources.ConfigMaps
wantErr bool
}{
"ConfigMaps works": {
instance: core.Instance{ProviderID: "gce://project-id/zone/instance-name"},
expectedConfigMaps: resources.ConfigMaps{
wantConfigMaps: resources.ConfigMaps{
&k8s.ConfigMap{
TypeMeta: v1.TypeMeta{
Kind: "ConfigMap",
@ -42,7 +42,7 @@ use-metadata-server = false
},
"invalid providerID fails": {
instance: core.Instance{ProviderID: "invalid"},
expectErr: true,
wantErr: true,
},
}
@ -54,12 +54,12 @@ use-metadata-server = false
cloud := CloudControllerManager{}
configMaps, err := cloud.ConfigMaps(tc.instance)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedConfigMaps, configMaps)
assert.Equal(tc.wantConfigMaps, configMaps)
})
}
}
@ -82,12 +82,12 @@ func TestSecrets(t *testing.T) {
testCases := map[string]struct {
instance core.Instance
cloudServiceAccountURI string
expectedSecrets resources.Secrets
expectErr bool
wantSecrets resources.Secrets
wantErr bool
}{
"Secrets works": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectedSecrets: resources.Secrets{
wantSecrets: resources.Secrets{
&k8s.Secret{
TypeMeta: v1.TypeMeta{
Kind: "Secret",
@ -105,7 +105,7 @@ func TestSecrets(t *testing.T) {
},
"invalid serviceAccountKey fails": {
cloudServiceAccountURI: "invalid",
expectErr: true,
wantErr: true,
},
}
@ -116,12 +116,12 @@ func TestSecrets(t *testing.T) {
cloud := CloudControllerManager{}
secrets, err := cloud.Secrets(tc.instance, tc.cloudServiceAccountURI)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedSecrets, secrets)
assert.Equal(tc.wantSecrets, secrets)
})
}
}

View File

@ -67,14 +67,14 @@ func TestRetrieveInstances(t *testing.T) {
metadata stubMetadataClient
instanceIter *stubInstanceIterator
instanceIterMutator func(*stubInstanceIterator)
expectedInstances []core.Instance
expectErr bool
wantInstances []core.Instance
wantErr bool
}{
"retrieve works": {
client: stubInstancesClient{},
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
expectedInstances: []core.Instance{
wantInstances: []core.Instance{
{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
@ -89,14 +89,14 @@ func TestRetrieveInstances(t *testing.T) {
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
instanceIterMutator: func(sii *stubInstanceIterator) { sii.instances[0].Name = nil },
expectErr: true,
wantErr: true,
},
"no instance with network ip": {
client: stubInstancesClient{},
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
instanceIterMutator: func(sii *stubInstanceIterator) { sii.instances[0].NetworkInterfaces = nil },
expectedInstances: []core.Instance{
wantInstances: []core.Instance{
{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
@ -111,7 +111,7 @@ func TestRetrieveInstances(t *testing.T) {
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
instanceIterMutator: func(sii *stubInstanceIterator) { sii.instances[0].NetworkInterfaces[0].NetworkIP = nil },
expectedInstances: []core.Instance{
wantInstances: []core.Instance{
{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
@ -126,20 +126,20 @@ func TestRetrieveInstances(t *testing.T) {
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
instanceIterMutator: func(sii *stubInstanceIterator) { sii.instances[0].Metadata.Items[2].Key = proto.String("") },
expectedInstances: []core.Instance{},
wantInstances: []core.Instance{},
},
"constellation retrieval fails": {
client: stubInstancesClient{},
metadata: stubMetadataClient{InstanceErr: someErr},
instanceIter: newTestIter(),
expectErr: true,
wantErr: true,
},
"role is not set": {
client: stubInstancesClient{},
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: newTestIter(),
instanceIterMutator: func(sii *stubInstanceIterator) { sii.instances[0].Metadata.Items[3].Key = proto.String("") },
expectedInstances: []core.Instance{
wantInstances: []core.Instance{
{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
@ -153,7 +153,7 @@ func TestRetrieveInstances(t *testing.T) {
client: stubInstancesClient{},
metadata: stubMetadataClient{InstanceValue: uid},
instanceIter: &stubInstanceIterator{nextErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -173,12 +173,12 @@ func TestRetrieveInstances(t *testing.T) {
instances, err := client.RetrieveInstances(context.Background(), "someProject", "someZone")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstances, instances)
assert.Equal(tc.wantInstances, instances)
})
}
}
@ -209,13 +209,13 @@ func TestRetrieveInstance(t *testing.T) {
client stubInstancesClient
clientInstance *computepb.Instance
clientInstanceMutator func(*computepb.Instance)
expectedInstance core.Instance
expectErr bool
wantInstance core.Instance
wantErr bool
}{
"retrieve works": {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -229,7 +229,7 @@ func TestRetrieveInstance(t *testing.T) {
i.Metadata.Items[0].Key = proto.String("ssh-keys")
i.Metadata.Items[0].Value = proto.String("bob:ssh-rsa bobskey")
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -243,7 +243,7 @@ func TestRetrieveInstance(t *testing.T) {
i.Metadata.Items[0].Key = proto.String(core.RoleMetadataKey)
i.Metadata.Items[0].Value = proto.String(role.Coordinator.String())
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
Role: role.Coordinator,
@ -256,13 +256,13 @@ func TestRetrieveInstance(t *testing.T) {
GetErr: errors.New("retrieve error"),
},
clientInstance: nil,
expectErr: true,
wantErr: true,
},
"metadata item is null": {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
clientInstanceMutator: func(i *computepb.Instance) { i.Metadata.Items[0] = nil },
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -273,7 +273,7 @@ func TestRetrieveInstance(t *testing.T) {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
clientInstanceMutator: func(i *computepb.Instance) { i.Metadata.Items[0].Key = nil },
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -284,7 +284,7 @@ func TestRetrieveInstance(t *testing.T) {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
clientInstanceMutator: func(i *computepb.Instance) { i.Metadata.Items[0].Value = nil },
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -295,7 +295,7 @@ func TestRetrieveInstance(t *testing.T) {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
clientInstanceMutator: func(i *computepb.Instance) { i.NetworkInterfaces[0] = nil },
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{},
@ -306,7 +306,7 @@ func TestRetrieveInstance(t *testing.T) {
client: stubInstancesClient{},
clientInstance: newTestInstance(),
clientInstanceMutator: func(i *computepb.Instance) { i.NetworkInterfaces[0].NetworkIP = nil },
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{},
@ -328,12 +328,12 @@ func TestRetrieveInstance(t *testing.T) {
instance, err := client.RetrieveInstance(context.Background(), "someProject", "someZone", "someInstance")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
@ -343,16 +343,16 @@ func TestRetrieveProjectID(t *testing.T) {
testCases := map[string]struct {
client stubMetadataClient
expectedValue string
expectErr bool
wantValue string
wantErr bool
}{
"retrieve works": {
client: stubMetadataClient{ProjectIDValue: "someProjectID"},
expectedValue: "someProjectID",
wantValue: "someProjectID",
},
"retrieve fails": {
client: stubMetadataClient{ProjectIDErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -364,12 +364,12 @@ func TestRetrieveProjectID(t *testing.T) {
client := Client{metadataAPI: tc.client}
value, err := client.RetrieveProjectID()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedValue, value)
assert.Equal(tc.wantValue, value)
})
}
}
@ -379,16 +379,16 @@ func TestRetrieveZone(t *testing.T) {
testCases := map[string]struct {
client stubMetadataClient
expectedValue string
expectErr bool
wantValue string
wantErr bool
}{
"retrieve works": {
client: stubMetadataClient{ZoneValue: "someZone"},
expectedValue: "someZone",
wantValue: "someZone",
},
"retrieve fails": {
client: stubMetadataClient{ZoneErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -400,12 +400,12 @@ func TestRetrieveZone(t *testing.T) {
client := Client{metadataAPI: tc.client}
value, err := client.RetrieveZone()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedValue, value)
assert.Equal(tc.wantValue, value)
})
}
}
@ -415,16 +415,16 @@ func TestRetrieveInstanceName(t *testing.T) {
testCases := map[string]struct {
client stubMetadataClient
expectedValue string
expectErr bool
wantValue string
wantErr bool
}{
"retrieve works": {
client: stubMetadataClient{InstanceNameValue: "someInstanceName"},
expectedValue: "someInstanceName",
wantValue: "someInstanceName",
},
"retrieve fails": {
client: stubMetadataClient{InstanceNameErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -436,12 +436,12 @@ func TestRetrieveInstanceName(t *testing.T) {
client := Client{metadataAPI: tc.client}
value, err := client.RetrieveInstanceName()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedValue, value)
assert.Equal(tc.wantValue, value)
})
}
}
@ -453,22 +453,22 @@ func TestRetrieveInstanceMetadata(t *testing.T) {
testCases := map[string]struct {
client stubMetadataClient
attr string
expectedValue string
expectErr bool
wantValue string
wantErr bool
}{
"retrieve works": {
client: stubMetadataClient{
InstanceValue: "someValue",
InstanceErr: nil,
},
expectedValue: "someValue",
wantValue: "someValue",
},
"retrieve fails": {
client: stubMetadataClient{
InstanceValue: "",
InstanceErr: someErr,
},
expectErr: true,
wantErr: true,
},
}
@ -480,12 +480,12 @@ func TestRetrieveInstanceMetadata(t *testing.T) {
client := Client{metadataAPI: tc.client}
value, err := client.RetrieveInstanceMetadata(attr)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedValue, value)
assert.Equal(tc.wantValue, value)
})
}
}
@ -495,7 +495,7 @@ func TestSetInstanceMetadata(t *testing.T) {
testCases := map[string]struct {
client stubInstancesClient
expectErr bool
wantErr bool
}{
"set works": {
client: stubInstancesClient{
@ -512,10 +512,10 @@ func TestSetInstanceMetadata(t *testing.T) {
client: stubInstancesClient{
GetErr: someErr,
},
expectErr: true,
wantErr: true,
},
"retrieve returns nil": {
expectErr: true,
wantErr: true,
},
"setting fails": {
client: stubInstancesClient{
@ -528,7 +528,7 @@ func TestSetInstanceMetadata(t *testing.T) {
},
SetMetadataErr: someErr,
},
expectErr: true,
wantErr: true,
},
}
@ -540,7 +540,7 @@ func TestSetInstanceMetadata(t *testing.T) {
client := Client{instanceAPI: tc.client}
err := client.SetInstanceMetadata(context.Background(), "project", "zone", "instanceName", "key", "value")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -554,7 +554,7 @@ func TestUnsetInstanceMetadata(t *testing.T) {
testCases := map[string]struct {
client stubInstancesClient
expectErr bool
wantErr bool
}{
"unset works": {
client: stubInstancesClient{
@ -585,10 +585,10 @@ func TestUnsetInstanceMetadata(t *testing.T) {
},
"retrieve fails": {
client: stubInstancesClient{GetErr: someErr},
expectErr: true,
wantErr: true,
},
"retrieve returns nil": {
expectErr: true,
wantErr: true,
},
"setting fails": {
client: stubInstancesClient{
@ -601,7 +601,7 @@ func TestUnsetInstanceMetadata(t *testing.T) {
},
SetMetadataErr: someErr,
},
expectErr: true,
wantErr: true,
},
}
@ -613,7 +613,7 @@ func TestUnsetInstanceMetadata(t *testing.T) {
client := Client{instanceAPI: tc.client}
err := client.UnsetInstanceMetadata(context.Background(), "project", "zone", "instanceName", "key")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -637,35 +637,35 @@ func TestClose(t *testing.T) {
func TestFetchSSHKeys(t *testing.T) {
testCases := map[string]struct {
metadata map[string]string
expectedKeys map[string][]string
wantKeys map[string][]string
}{
"fetch works": {
metadata: map[string]string{"ssh-keys": "bob:ssh-rsa bobskey"},
expectedKeys: map[string][]string{"bob": {"ssh-rsa bobskey"}},
wantKeys: map[string][]string{"bob": {"ssh-rsa bobskey"}},
},
"google ssh key metadata is ignored": {
metadata: map[string]string{"ssh-keys": "bob:ssh-rsa bobskey google-ssh {\"userName\":\"bob\",\"expireOn\":\"2021-06-14T16:59:03+0000\"}"},
expectedKeys: map[string][]string{"bob": {"ssh-rsa bobskey"}},
wantKeys: map[string][]string{"bob": {"ssh-rsa bobskey"}},
},
"ssh key format error is ignored": {
metadata: map[string]string{"ssh-keys": "incorrect-format"},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"ssh key format space error is ignored": {
metadata: map[string]string{"ssh-keys": "user:incorrect-key-format"},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"metadata field empty": {
metadata: map[string]string{"ssh-keys": ""},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"metadata field missing": {
metadata: map[string]string{},
expectedKeys: map[string][]string{},
wantKeys: map[string][]string{},
},
"multiple keys": {
metadata: map[string]string{"ssh-keys": "bob:ssh-rsa bobskey\nalice:ssh-rsa alicekey"},
expectedKeys: map[string][]string{
wantKeys: map[string][]string{
"bob": {"ssh-rsa bobskey"},
"alice": {"ssh-rsa alicekey"},
},
@ -677,7 +677,7 @@ func TestFetchSSHKeys(t *testing.T) {
assert := assert.New(t)
keys := extractSSHKeys(tc.metadata)
assert.Equal(tc.expectedKeys, keys)
assert.Equal(tc.wantKeys, keys)
})
}
}

View File

@ -28,8 +28,8 @@ func TestList(t *testing.T) {
client stubGCPClient
instancesGenerator func() *[]core.Instance
instancesMutator func(*[]core.Instance)
expectErr bool
expectedInstances []core.Instance
wantErr bool
wantInstances []core.Instance
}{
"retrieve works": {
client: stubGCPClient{
@ -40,7 +40,7 @@ func TestList(t *testing.T) {
},
},
instancesGenerator: instancesGenerator,
expectedInstances: []core.Instance{
wantInstances: []core.Instance{
{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
@ -58,21 +58,21 @@ func TestList(t *testing.T) {
retrieveInstancesErr: err,
},
instancesGenerator: instancesGenerator,
expectErr: true,
wantErr: true,
},
"project metadata retrieval error is detected": {
client: stubGCPClient{
retrieveProjectIDErr: err,
},
instancesGenerator: instancesGenerator,
expectErr: true,
wantErr: true,
},
"zone retrieval error is detected": {
client: stubGCPClient{
retrieveZoneErr: err,
},
instancesGenerator: instancesGenerator,
expectErr: true,
wantErr: true,
},
}
@ -88,12 +88,12 @@ func TestList(t *testing.T) {
metadata := New(&tc.client)
instances, err := metadata.List(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedInstances, instances)
assert.ElementsMatch(tc.wantInstances, instances)
})
}
}
@ -104,8 +104,8 @@ func TestSelf(t *testing.T) {
testCases := map[string]struct {
client stubGCPClient
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"retrieve works": {
client: stubGCPClient{
@ -117,7 +117,7 @@ func TestSelf(t *testing.T) {
IPs: []string{"192.0.2.0"},
},
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -132,25 +132,25 @@ func TestSelf(t *testing.T) {
},
retrieveInstanceErr: err,
},
expectErr: true,
wantErr: true,
},
"project id retrieval error is detected": {
client: stubGCPClient{
retrieveProjectIDErr: err,
},
expectErr: true,
wantErr: true,
},
"zone retrieval error is detected": {
client: stubGCPClient{
retrieveZoneErr: err,
},
expectErr: true,
wantErr: true,
},
"instance name retrieval error is detected": {
client: stubGCPClient{
retrieveInstanceNameErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -162,12 +162,12 @@ func TestSelf(t *testing.T) {
cloud := New(&tc.client)
instance, err := cloud.Self(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
@ -178,8 +178,8 @@ func TestGetInstance(t *testing.T) {
testCases := map[string]struct {
providerID string
client stubGCPClient
expectErr bool
expectedInstance core.Instance
wantErr bool
wantInstance core.Instance
}{
"retrieve works": {
providerID: "gce://someProject/someZone/someInstance",
@ -190,7 +190,7 @@ func TestGetInstance(t *testing.T) {
IPs: []string{"192.0.2.0"},
},
},
expectedInstance: core.Instance{
wantInstance: core.Instance{
Name: "someInstance",
ProviderID: "gce://someProject/someZone/someInstance",
IPs: []string{"192.0.2.0"},
@ -201,15 +201,15 @@ func TestGetInstance(t *testing.T) {
client: stubGCPClient{
retrieveInstanceErr: err,
},
expectErr: true,
wantErr: true,
},
"malformed providerID with too many fields is detected": {
providerID: "gce://someProject/someZone/someInstance/tooMany/fields",
expectErr: true,
wantErr: true,
},
"malformed providerID with too few fields is detected": {
providerID: "gce://someProject",
expectErr: true,
wantErr: true,
},
}
@ -221,12 +221,12 @@ func TestGetInstance(t *testing.T) {
cloud := New(&tc.client)
instance, err := cloud.GetInstance(context.Background(), tc.providerID)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedInstance, instance)
assert.Equal(tc.wantInstance, instance)
})
}
}
@ -236,8 +236,8 @@ func TestSignalRole(t *testing.T) {
testCases := map[string]struct {
client stubGCPClient
expectErr bool
expectedRole role.Role
wantErr bool
wantRole role.Role
}{
"signaling role works": {
client: stubGCPClient{
@ -245,25 +245,25 @@ func TestSignalRole(t *testing.T) {
zone: "someZone",
instanceName: "someName",
},
expectedRole: role.Coordinator,
wantRole: role.Coordinator,
},
"project metadata retrieval error is detected": {
client: stubGCPClient{
retrieveProjectIDErr: err,
},
expectErr: true,
wantErr: true,
},
"instance zone retrieval error is detected": {
client: stubGCPClient{
retrieveZoneErr: err,
},
expectErr: true,
wantErr: true,
},
"instance name retrieval error is detected": {
client: stubGCPClient{
retrieveInstanceNameErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -273,9 +273,9 @@ func TestSignalRole(t *testing.T) {
require := require.New(t)
cloud := New(&tc.client)
err := cloud.SignalRole(context.Background(), tc.expectedRole)
err := cloud.SignalRole(context.Background(), tc.wantRole)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -285,7 +285,7 @@ func TestSignalRole(t *testing.T) {
assert.ElementsMatch([]string{"someZone"}, tc.client.instanceMetadataZones)
assert.ElementsMatch([]string{"someName"}, tc.client.instanceMetadataInstanceNames)
assert.ElementsMatch([]string{core.RoleMetadataKey}, tc.client.instanceMetadataKeys)
assert.ElementsMatch([]string{tc.expectedRole.String()}, tc.client.instanceMetadataValues)
assert.ElementsMatch([]string{tc.wantRole.String()}, tc.client.instanceMetadataValues)
})
}
}
@ -295,8 +295,8 @@ func TestSetVPNIP(t *testing.T) {
testCases := map[string]struct {
client stubGCPClient
expectErr bool
expectedVPNIP string
wantErr bool
wantVPNIP string
}{
"signaling role works": {
client: stubGCPClient{
@ -304,25 +304,25 @@ func TestSetVPNIP(t *testing.T) {
zone: "someZone",
instanceName: "someName",
},
expectedVPNIP: "192.0.2.0",
wantVPNIP: "192.0.2.0",
},
"project metadata retrieval error is detected": {
client: stubGCPClient{
retrieveProjectIDErr: err,
},
expectErr: true,
wantErr: true,
},
"instance zone retrieval error is detected": {
client: stubGCPClient{
retrieveZoneErr: err,
},
expectErr: true,
wantErr: true,
},
"instance name retrieval error is detected": {
client: stubGCPClient{
retrieveInstanceNameErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -332,9 +332,9 @@ func TestSetVPNIP(t *testing.T) {
require := require.New(t)
cloud := New(&tc.client)
err := cloud.SetVPNIP(context.Background(), tc.expectedVPNIP)
err := cloud.SetVPNIP(context.Background(), tc.wantVPNIP)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -344,7 +344,7 @@ func TestSetVPNIP(t *testing.T) {
assert.ElementsMatch([]string{"someZone"}, tc.client.instanceMetadataZones)
assert.ElementsMatch([]string{"someName"}, tc.client.instanceMetadataInstanceNames)
assert.ElementsMatch([]string{core.VPNIPMetadataKey}, tc.client.instanceMetadataKeys)
assert.ElementsMatch([]string{tc.expectedVPNIP}, tc.client.instanceMetadataValues)
assert.ElementsMatch([]string{tc.wantVPNIP}, tc.client.instanceMetadataValues)
})
}
}

View File

@ -23,60 +23,60 @@ func TestGetServiceAccountKey(t *testing.T) {
}
testCases := map[string]struct {
cloudServiceAccountURI string
expectedKey client.ServiceAccountKey
expectErr bool
wantKey client.ServiceAccountKey
wantErr bool
}{
"getServiceAccountKey works": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectedKey: serviceAccountKey,
wantKey: serviceAccountKey,
},
"missing type": {
cloudServiceAccountURI: "serviceaccount://gcp?project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing project_id": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing private_key_id": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing private_key": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing client_email": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing client_id": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing token_uri": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing auth_provider_x509_cert_url": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&client_x509_cert_url=client-x509-cert-url",
expectErr: true,
wantErr: true,
},
"missing client_x509_cert_url": {
cloudServiceAccountURI: "serviceaccount://gcp?type=type&project_id=project-id&private_key_id=private-key-id&private_key=private-key&client_email=client-email&client_id=client-id&auth_uri=auth-uri&token_uri=token-uri&auth_provider_x509_cert_url=auth-provider-x509-cert-url",
expectErr: true,
wantErr: true,
},
"invalid URI fails": {
cloudServiceAccountURI: "\x00",
expectErr: true,
wantErr: true,
},
"incorrect URI scheme fails": {
cloudServiceAccountURI: "invalid",
expectErr: true,
wantErr: true,
},
"incorrect URI host fails": {
cloudServiceAccountURI: "serviceaccount://incorrect",
expectErr: true,
wantErr: true,
},
}
@ -86,12 +86,12 @@ func TestGetServiceAccountKey(t *testing.T) {
require := require.New(t)
key, err := getServiceAccountKey(tc.cloudServiceAccountURI)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedKey, key)
assert.Equal(tc.wantKey, key)
})
}
}

View File

@ -13,21 +13,21 @@ func TestWriteGCEConf(t *testing.T) {
testCases := map[string]struct {
fs afero.Afero
expectedValue string
expectErr bool
wantValue string
wantErr bool
}{
"write works": {
fs: afero.Afero{
Fs: afero.NewMemMapFs(),
},
expectedValue: config,
expectErr: false,
wantValue: config,
wantErr: false,
},
"write fails": {
fs: afero.Afero{
Fs: afero.NewReadOnlyFs(afero.NewMemMapFs()),
},
expectErr: true,
wantErr: true,
},
}
@ -41,14 +41,14 @@ func TestWriteGCEConf(t *testing.T) {
}
err := writer.WriteGCEConf(config)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
value, err := tc.fs.ReadFile("/etc/gce.conf")
assert.NoError(err)
assert.Equal(tc.expectedValue, string(value))
assert.Equal(tc.wantValue, string(value))
})
}
}

View File

@ -11,28 +11,28 @@ import (
func TestExtractRole(t *testing.T) {
testCases := map[string]struct {
metadata map[string]string
expectedRole role.Role
wantRole role.Role
}{
"coordinator role": {
metadata: map[string]string{
core.RoleMetadataKey: role.Coordinator.String(),
},
expectedRole: role.Coordinator,
wantRole: role.Coordinator,
},
"node role": {
metadata: map[string]string{
core.RoleMetadataKey: role.Node.String(),
},
expectedRole: role.Node,
wantRole: role.Node,
},
"unknown role": {
metadata: map[string]string{
core.RoleMetadataKey: "some-unknown-role",
},
expectedRole: role.Unknown,
wantRole: role.Unknown,
},
"no role": {
expectedRole: role.Unknown,
wantRole: role.Unknown,
},
}
@ -42,7 +42,7 @@ func TestExtractRole(t *testing.T) {
role := ExtractRole(tc.metadata)
assert.Equal(tc.expectedRole, role)
assert.Equal(tc.wantRole, role)
})
}
}

View File

@ -15,8 +15,8 @@ func TestCoordinatorEndpoints(t *testing.T) {
testCases := map[string]struct {
metadata stubMetadata
expectErr bool
expectedEndpoints []string
wantErr bool
wantEndpoints []string
}{
"getting coordinator endpoints works and role is checked": {
metadata: stubMetadata{
@ -36,19 +36,19 @@ func TestCoordinatorEndpoints(t *testing.T) {
},
supportedRes: true,
},
expectErr: false,
expectedEndpoints: []string{"192.0.2.1:9000"},
wantErr: false,
wantEndpoints: []string{"192.0.2.1:9000"},
},
"List fails": {
metadata: stubMetadata{
listErr: err,
supportedRes: true,
},
expectErr: true,
wantErr: true,
},
"metadata API unsupported": {
metadata: stubMetadata{},
expectErr: true,
wantErr: true,
},
}
@ -59,13 +59,13 @@ func TestCoordinatorEndpoints(t *testing.T) {
endpoints, err := CoordinatorEndpoints(context.Background(), &tc.metadata)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedEndpoints, endpoints)
assert.ElementsMatch(tc.wantEndpoints, endpoints)
})
}
}
@ -76,18 +76,18 @@ func TestPrepareInstanceForCCM(t *testing.T) {
testCases := map[string]struct {
metadata stubMetadata
vpnIP string
expectErr bool
wantErr bool
}{
"updating role works": {
metadata: stubMetadata{},
vpnIP: "192.0.2.1",
expectErr: false,
wantErr: false,
},
"setting VPN IP fails": {
metadata: stubMetadata{
setVPNIPErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -98,7 +98,7 @@ func TestPrepareInstanceForCCM(t *testing.T) {
err := PrepareInstanceForCCM(context.Background(), &tc.metadata, &CloudControllerManagerFake{}, tc.vpnIP)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -28,15 +28,15 @@ func TestInitCluster(t *testing.T) {
cloudNodeManager stubCloudNodeManager
clusterAutoscaler stubClusterAutoscaler
autoscalingNodeGroups []string
expectErr bool
expectedInitClusterInput kubernetes.InitClusterInput
wantErr bool
wantInitClusterInput kubernetes.InitClusterInput
}{
"InitCluster works": {
cluster: clusterStub{
kubeconfig: []byte("kubeconfig"),
},
autoscalingNodeGroups: []string{"someNodeGroup"},
expectedInitClusterInput: kubernetes.InitClusterInput{
wantInitClusterInput: kubernetes.InitClusterInput{
APIServerAdvertiseIP: "10.118.0.1",
NodeIP: "10.118.0.1",
NodeName: "10.118.0.1",
@ -44,7 +44,7 @@ func TestInitCluster(t *testing.T) {
SupportClusterAutoscaler: false,
AutoscalingNodeGroups: []string{"someNodeGroup"},
},
expectErr: false,
wantErr: false,
},
"Instance metadata is retrieved": {
cluster: clusterStub{
@ -57,7 +57,7 @@ func TestInitCluster(t *testing.T) {
},
supportedRes: true,
},
expectedInitClusterInput: kubernetes.InitClusterInput{
wantInitClusterInput: kubernetes.InitClusterInput{
APIServerAdvertiseIP: "10.118.0.1",
NodeIP: "10.118.0.1",
NodeName: "some-name",
@ -65,7 +65,7 @@ func TestInitCluster(t *testing.T) {
SupportsCloudControllerManager: false,
SupportClusterAutoscaler: false,
},
expectErr: false,
wantErr: false,
},
"metadata of self retrieval error is checked": {
cluster: clusterStub{
@ -75,7 +75,7 @@ func TestInitCluster(t *testing.T) {
supportedRes: true,
selfErr: errors.New("metadata retrieval error"),
},
expectErr: true,
wantErr: true,
},
"Autoscaler is prepared when supported": {
cluster: clusterStub{
@ -86,7 +86,7 @@ func TestInitCluster(t *testing.T) {
supportedRes: true,
},
autoscalingNodeGroups: []string{"someNodeGroup"},
expectedInitClusterInput: kubernetes.InitClusterInput{
wantInitClusterInput: kubernetes.InitClusterInput{
APIServerAdvertiseIP: "10.118.0.1",
NodeIP: "10.118.0.1",
NodeName: "10.118.0.1",
@ -95,7 +95,7 @@ func TestInitCluster(t *testing.T) {
AutoscalingCloudprovider: "some-name",
AutoscalingNodeGroups: []string{"someNodeGroup"},
},
expectErr: false,
wantErr: false,
},
"Node is prepared for CCM if supported": {
cluster: clusterStub{
@ -107,7 +107,7 @@ func TestInitCluster(t *testing.T) {
imageRes: "someImage",
pathRes: "/some/path",
},
expectedInitClusterInput: kubernetes.InitClusterInput{
wantInitClusterInput: kubernetes.InitClusterInput{
APIServerAdvertiseIP: "10.118.0.1",
NodeIP: "10.118.0.1",
NodeName: "10.118.0.1",
@ -117,7 +117,7 @@ func TestInitCluster(t *testing.T) {
CloudControllerManagerImage: "someImage",
CloudControllerManagerPath: "/some/path",
},
expectErr: false,
wantErr: false,
},
"Node preparation for CCM can fail": {
cluster: clusterStub{
@ -133,7 +133,7 @@ func TestInitCluster(t *testing.T) {
pathRes: "/some/path",
prepareInstanceRes: errors.New("preparing node for CCM failed"),
},
expectErr: true,
wantErr: true,
},
"updating role fails without error": {
cluster: clusterStub{
@ -143,8 +143,8 @@ func TestInitCluster(t *testing.T) {
signalRoleErr: errors.New("updating role fails"),
supportedRes: true,
},
expectErr: false,
expectedInitClusterInput: kubernetes.InitClusterInput{
wantErr: false,
wantInitClusterInput: kubernetes.InitClusterInput{
APIServerAdvertiseIP: "10.118.0.1",
NodeIP: "10.118.0.1",
},
@ -153,13 +153,13 @@ func TestInitCluster(t *testing.T) {
cluster: clusterStub{
getKubeconfigErr: errors.New("getting kubeconfig fails"),
},
expectErr: true,
wantErr: true,
},
"InitCluster fail detected": {
cluster: clusterStub{
initErr: someErr,
},
expectErr: true,
wantErr: true,
},
}
@ -175,13 +175,13 @@ func TestInitCluster(t *testing.T) {
kubeconfig, err := core.InitCluster(tc.autoscalingNodeGroups, "cloud-service-account-uri")
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.Len(tc.cluster.initInputs, 1)
assert.Equal(tc.expectedInitClusterInput, tc.cluster.initInputs[0])
assert.Equal(tc.wantInitClusterInput, tc.cluster.initInputs[0])
assert.Equal(tc.cluster.kubeconfig, kubeconfig)
})
}
@ -197,14 +197,14 @@ func TestJoinCluster(t *testing.T) {
cloudNodeManager stubCloudNodeManager
clusterAutoscaler stubClusterAutoscaler
vpn stubVPN
expectErr bool
expectedJoinClusterArgs joinClusterArgs
wantErr bool
wantJoinClusterArgs joinClusterArgs
}{
"JoinCluster works": {
vpn: stubVPN{
interfaceIP: "192.0.2.0",
},
expectedJoinClusterArgs: joinClusterArgs{
wantJoinClusterArgs: joinClusterArgs{
args: &kubeadm.BootstrapTokenDiscovery{
APIServerEndpoint: "192.0.2.0:6443",
Token: "someToken",
@ -218,13 +218,13 @@ func TestJoinCluster(t *testing.T) {
cluster: clusterStub{
joinErr: someErr,
},
expectErr: true,
wantErr: true,
},
"retrieving vpn ip failure detected": {
vpn: stubVPN{
getInterfaceIPErr: errors.New("retrieving interface ip error"),
},
expectErr: true,
wantErr: true,
},
"Instance metadata is retrieved": {
metadata: stubMetadata{
@ -234,7 +234,7 @@ func TestJoinCluster(t *testing.T) {
},
supportedRes: true,
},
expectedJoinClusterArgs: joinClusterArgs{
wantJoinClusterArgs: joinClusterArgs{
args: &kubeadm.BootstrapTokenDiscovery{
APIServerEndpoint: "192.0.2.0:6443",
Token: "someToken",
@ -243,14 +243,14 @@ func TestJoinCluster(t *testing.T) {
nodeName: "some-name",
providerID: "fake://providerid",
},
expectErr: false,
wantErr: false,
},
"Instance metadata retrieval can fail": {
metadata: stubMetadata{
supportedRes: true,
selfErr: errors.New("metadata retrieval error"),
},
expectErr: true,
wantErr: true,
},
"CCM preparation failure is detected": {
metadata: stubMetadata{
@ -260,15 +260,15 @@ func TestJoinCluster(t *testing.T) {
supportedRes: true,
prepareInstanceRes: errors.New("ccm prepare fails"),
},
expectErr: true,
wantErr: true,
},
"updating role fails without error": {
metadata: stubMetadata{
signalRoleErr: errors.New("updating role fails"),
supportedRes: true,
},
expectErr: false,
expectedJoinClusterArgs: joinClusterArgs{
wantErr: false,
wantJoinClusterArgs: joinClusterArgs{
args: &kubeadm.BootstrapTokenDiscovery{
APIServerEndpoint: "192.0.2.0:6443",
Token: "someToken",
@ -295,13 +295,13 @@ func TestJoinCluster(t *testing.T) {
}
err = core.JoinCluster(joinReq, "", role.Node)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.Len(tc.cluster.joinClusterArgs, 1)
assert.Equal(tc.expectedJoinClusterArgs, tc.cluster.joinClusterArgs[0])
assert.Equal(tc.wantJoinClusterArgs, tc.cluster.joinClusterArgs[0])
})
}
}
@ -310,19 +310,19 @@ func TestK8sCompliantHostname(t *testing.T) {
compliantHostname := regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`)
testCases := map[string]struct {
hostname string
expectedHostname string
wantHostname string
}{
"azure scale set names work": {
hostname: "constellation-scale-set-coordinators-name_0",
expectedHostname: "constellation-scale-set-coordinators-name-0",
wantHostname: "constellation-scale-set-coordinators-name-0",
},
"compliant hostname is not modified": {
hostname: "abcd-123",
expectedHostname: "abcd-123",
wantHostname: "abcd-123",
},
"uppercase hostnames are lowercased": {
hostname: "ABCD",
expectedHostname: "abcd",
wantHostname: "abcd",
},
}
@ -332,7 +332,7 @@ func TestK8sCompliantHostname(t *testing.T) {
hostname := k8sCompliantHostname(tc.hostname)
assert.Equal(tc.expectedHostname, hostname)
assert.Equal(tc.wantHostname, hostname)
assert.Regexp(compliantHostname, hostname)
})
}

View File

@ -159,34 +159,34 @@ func TestInitialize(t *testing.T) {
initializePCRs bool
writeNodeState bool
role role.Role
expectActivated bool
expectedState state.State
expectPanic bool
expectErr bool
wantActivated bool
wantState state.State
wantPanic bool
wantErr bool
}{
"fresh node": {
expectedState: state.AcceptingInit,
wantState: state.AcceptingInit,
},
"activated coordinator": {
initializePCRs: true,
writeNodeState: true,
role: role.Coordinator,
expectPanic: true, // TODO: adapt test case once restart is implemented
expectActivated: true,
expectedState: state.ActivatingNodes,
wantPanic: true, // TODO: adapt test case once restart is implemented
wantActivated: true,
wantState: state.ActivatingNodes,
},
"activated node": {
initializePCRs: true,
writeNodeState: true,
role: role.Node,
expectPanic: true, // TODO: adapt test case once restart is implemented
expectActivated: true,
expectedState: state.IsNode,
wantPanic: true, // TODO: adapt test case once restart is implemented
wantActivated: true,
wantState: state.IsNode,
},
"activated node with no node state": {
initializePCRs: true,
writeNodeState: false,
expectErr: true,
wantErr: true,
},
}
@ -211,19 +211,19 @@ func TestInitialize(t *testing.T) {
core, err := NewCore(&stubVPN{}, nil, nil, nil, nil, nil, nil, zaptest.NewLogger(t), openTPM, nil, fileHandler)
require.NoError(err)
if tc.expectPanic {
if tc.wantPanic {
assert.Panics(func() { _, _ = core.Initialize() })
return
}
nodeActivated, err := core.Initialize()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectActivated, nodeActivated)
assert.Equal(tc.expectedState, core.state)
assert.Equal(tc.wantActivated, nodeActivated)
assert.Equal(tc.wantState, core.state)
})
}
}
@ -232,7 +232,7 @@ func TestPersistNodeState(t *testing.T) {
testCases := map[string]struct {
vpn VPN
touchStateFile bool
errExpected bool
wantErr bool
}{
"persisting works": {
vpn: &stubVPN{
@ -243,14 +243,14 @@ func TestPersistNodeState(t *testing.T) {
vpn: &stubVPN{
getPrivateKeyErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
"writing node state over existing file fails": {
vpn: &stubVPN{
privateKey: []byte("private-key"),
},
touchStateFile: true,
errExpected: true,
wantErr: true,
},
}
@ -269,7 +269,7 @@ func TestPersistNodeState(t *testing.T) {
core, err := NewCore(tc.vpn, nil, nil, nil, nil, nil, nil, zaptest.NewLogger(t), nil, nil, fileHandler)
require.NoError(err)
err = core.PersistNodeState(role.Coordinator, []byte("owner-id"), []byte("cluster-id"))
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -13,21 +13,21 @@ import (
func TestGetDiskUUID(t *testing.T) {
testCases := map[string]struct {
expectedUUID string
wantUUID string
openErr error
uuidErr error
errExpected bool
wantErr bool
}{
"getting uuid works": {
expectedUUID: "uuid",
wantUUID: "uuid",
},
"open can fail": {
openErr: errors.New("open-error"),
errExpected: true,
wantErr: true,
},
"getting disk uuid can fail": {
uuidErr: errors.New("uuid-err"),
errExpected: true,
wantErr: true,
},
}
@ -41,18 +41,18 @@ func TestGetDiskUUID(t *testing.T) {
diskStub := encryptedDiskStub{
openErr: tc.openErr,
uuidErr: tc.uuidErr,
uuid: tc.expectedUUID,
uuid: tc.wantUUID,
}
core, err := NewCore(&stubVPN{}, nil, nil, nil, nil, nil, &diskStub, zapLogger, nil, nil, file.NewHandler(afero.NewMemMapFs()))
require.NoError(err)
uuid, err := core.GetDiskUUID()
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedUUID, uuid)
assert.Equal(tc.wantUUID, uuid)
})
}
}
@ -61,16 +61,16 @@ func TestUpdateDiskPassphrase(t *testing.T) {
testCases := map[string]struct {
openErr error
updatePassphraseErr error
errExpected bool
wantErr bool
}{
"updating passphrase works": {},
"open can fail": {
openErr: errors.New("open-error"),
errExpected: true,
wantErr: true,
},
"updating disk passphrase can fail": {
updatePassphraseErr: errors.New("update-err"),
errExpected: true,
wantErr: true,
},
}
@ -88,7 +88,7 @@ func TestUpdateDiskPassphrase(t *testing.T) {
core, err := NewCore(&stubVPN{}, nil, nil, nil, nil, nil, &diskStub, zapLogger, nil, nil, file.NewHandler(afero.NewMemMapFs()))
require.NoError(err)
err = core.UpdateDiskPassphrase("passphrase")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -19,32 +19,32 @@ func TestGetPeers(t *testing.T) {
testCases := map[string]struct {
storePeers []peer.Peer
resourceVersion int
expectedPeers []peer.Peer
wantPeers []peer.Peer
}{
"request version 0": { // store has version 2
storePeers: []peer.Peer{peer1, peer2},
resourceVersion: 0,
expectedPeers: []peer.Peer{peer1, peer2},
wantPeers: []peer.Peer{peer1, peer2},
},
"request version 1": {
storePeers: []peer.Peer{peer1, peer2},
resourceVersion: 1,
expectedPeers: []peer.Peer{peer1, peer2},
wantPeers: []peer.Peer{peer1, peer2},
},
"request version 2": {
storePeers: []peer.Peer{peer1, peer2},
resourceVersion: 2,
expectedPeers: nil,
wantPeers: nil,
},
"request version 3": {
storePeers: []peer.Peer{peer1, peer2},
resourceVersion: 3,
expectedPeers: []peer.Peer{peer1, peer2},
wantPeers: []peer.Peer{peer1, peer2},
},
"request version 4": {
storePeers: []peer.Peer{peer1, peer2},
resourceVersion: 4,
expectedPeers: []peer.Peer{peer1, peer2},
wantPeers: []peer.Peer{peer1, peer2},
},
}
@ -66,7 +66,7 @@ func TestGetPeers(t *testing.T) {
require.NoError(err)
assert.Equal(2, resourceVersion)
assert.ElementsMatch(tc.expectedPeers, peers)
assert.ElementsMatch(tc.wantPeers, peers)
})
}
}
@ -78,7 +78,7 @@ func TestAddPeer(t *testing.T) {
VPNIP: "192.0.2.21",
VPNPubKey: []byte{2, 3, 4},
}
expectedVPNPeers := []stubVPNPeer{{
wantVPNPeers := []stubVPNPeer{{
pubKey: testPeer.VPNPubKey,
publicIP: "192.0.2.11",
vpnIP: testPeer.VPNIP,
@ -87,24 +87,24 @@ func TestAddPeer(t *testing.T) {
testCases := map[string]struct {
peer peer.Peer
vpn stubVPN
expectErr bool
expectedVPNPeers []stubVPNPeer
expectedStorePeers []peer.Peer
wantErr bool
wantVPNPeers []stubVPNPeer
wantStorePeers []peer.Peer
}{
"add peer": {
peer: testPeer,
expectedVPNPeers: expectedVPNPeers,
expectedStorePeers: []peer.Peer{testPeer},
wantVPNPeers: wantVPNPeers,
wantStorePeers: []peer.Peer{testPeer},
},
"don't add self to vpn": {
peer: testPeer,
vpn: stubVPN{interfaceIP: testPeer.VPNIP},
expectedStorePeers: []peer.Peer{testPeer},
wantStorePeers: []peer.Peer{testPeer},
},
"vpn add peer error": {
peer: testPeer,
vpn: stubVPN{addPeerErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -118,17 +118,17 @@ func TestAddPeer(t *testing.T) {
err = core.AddPeer(tc.peer)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedVPNPeers, tc.vpn.peers)
assert.Equal(tc.wantVPNPeers, tc.vpn.peers)
actualStorePeers, err := core.data().GetPeers()
require.NoError(err)
assert.Equal(tc.expectedStorePeers, actualStorePeers)
assert.Equal(tc.wantStorePeers, actualStorePeers)
})
}
}

View File

@ -21,18 +21,18 @@ func TestAdvanceState(t *testing.T) {
initialState state.State
newState state.State
openTPMErr error
expectErr bool
expectOpenTPMCalled bool
wantErr bool
wantOpenTPMCalled bool
}{
"init -> coordinator": {
initialState: state.AcceptingInit,
newState: state.ActivatingNodes,
expectOpenTPMCalled: true,
wantOpenTPMCalled: true,
},
"init -> node": {
initialState: state.AcceptingInit,
newState: state.IsNode,
expectOpenTPMCalled: true,
wantOpenTPMCalled: true,
},
"init -> failed": {
initialState: state.AcceptingInit,
@ -46,8 +46,8 @@ func TestAdvanceState(t *testing.T) {
initialState: state.AcceptingInit,
newState: state.ActivatingNodes,
openTPMErr: someErr,
expectErr: true,
expectOpenTPMCalled: true,
wantErr: true,
wantOpenTPMCalled: true,
},
}
@ -71,9 +71,9 @@ func TestAdvanceState(t *testing.T) {
core.state = tc.initialState
err = core.AdvanceState(tc.newState, []byte("secret"), []byte("cluster"))
assert.Equal(tc.expectOpenTPMCalled, openTPMCalled)
assert.Equal(tc.wantOpenTPMCalled, openTPMCalled)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
assert.Equal(tc.initialState, core.GetState())
return

View File

@ -14,23 +14,23 @@ func TestOpenClose(t *testing.T) {
testCases := map[string]struct {
initByNameErr error
operations []string
errExpected bool
wantErr bool
}{
"open and close work": {
operations: []string{"open", "close"},
},
"opening twice fails": {
operations: []string{"open", "open"},
errExpected: true,
wantErr: true,
},
"closing first fails": {
operations: []string{"close"},
errExpected: true,
wantErr: true,
},
"initByName failure detected": {
initByNameErr: errors.New("initByNameErr"),
operations: []string{"open"},
errExpected: true,
wantErr: true,
},
}
@ -47,7 +47,7 @@ func TestOpenClose(t *testing.T) {
}
err := executeOperations(&crypt, tc.operations)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -59,19 +59,19 @@ func TestOpenClose(t *testing.T) {
func TestUUID(t *testing.T) {
testCases := map[string]struct {
open bool
expectedUUID string
errExpected bool
wantUUID string
wantErr bool
}{
"getting uuid works": {
open: true,
expectedUUID: "uuid",
wantUUID: "uuid",
},
"getting uuid on closed device fails": {
errExpected: true,
wantErr: true,
},
"empty uuid is detected": {
open: true,
errExpected: true,
wantErr: true,
},
}
@ -83,7 +83,7 @@ func TestUUID(t *testing.T) {
crypt := Cryptsetup{
fs: afero.NewMemMapFs(),
initByName: func(name string) (cryptdevice, error) {
return &stubCryptdevice{uuid: tc.expectedUUID}, nil
return &stubCryptdevice{uuid: tc.wantUUID}, nil
},
}
@ -92,12 +92,12 @@ func TestUUID(t *testing.T) {
defer crypt.Close()
}
uuid, err := crypt.UUID()
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedUUID, uuid)
assert.Equal(tc.wantUUID, uuid)
})
}
}
@ -107,24 +107,24 @@ func TestUpdatePassphrase(t *testing.T) {
writePassphrase bool
open bool
keyslotChangeByPassphraseErr error
errExpected bool
wantErr bool
}{
"updating passphrase works": {
writePassphrase: true,
open: true,
},
"updating passphrase on closed device fails": {
errExpected: true,
wantErr: true,
},
"reading initial passphrase can fail": {
open: true,
errExpected: true,
wantErr: true,
},
"changing keyslot passphrase can fail": {
open: true,
writePassphrase: true,
keyslotChangeByPassphraseErr: errors.New("keyslotChangeByPassphraseErr"),
errExpected: true,
wantErr: true,
},
}
@ -151,7 +151,7 @@ func TestUpdatePassphrase(t *testing.T) {
defer crypt.Close()
}
err := crypt.UpdatePassphrase("new-key")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -13,35 +13,35 @@ import (
func TestGetStore(t *testing.T) {
testCases := map[string]struct {
uri string
errExpected bool
wantErr bool
}{
"no store": {
uri: NoStoreURI,
errExpected: false,
wantErr: false,
},
"aws s3": {
uri: fmt.Sprintf(AWSS3URI, ""),
errExpected: true,
wantErr: true,
},
"azure blob": {
uri: fmt.Sprintf(AzureBlobURI, "", ""),
errExpected: true,
wantErr: true,
},
"gcp storage": {
uri: fmt.Sprintf(GCPStorageURI, "", ""),
errExpected: true,
wantErr: true,
},
"unknown store": {
uri: "storage://unknown",
errExpected: true,
wantErr: true,
},
"invalid scheme": {
uri: ClusterKMSURI,
errExpected: true,
wantErr: true,
},
"not a url": {
uri: ":/123",
errExpected: true,
wantErr: true,
},
}
@ -50,7 +50,7 @@ func TestGetStore(t *testing.T) {
assert := assert.New(t)
_, err := getStore(context.Background(), tc.uri)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -62,39 +62,39 @@ func TestGetStore(t *testing.T) {
func TestGetKMS(t *testing.T) {
testCases := map[string]struct {
uri string
errExpected bool
wantErr bool
}{
"cluster kms": {
uri: ClusterKMSURI,
errExpected: false,
wantErr: false,
},
"aws kms": {
uri: fmt.Sprintf(AWSKMSURI, ""),
errExpected: true,
wantErr: true,
},
"azure kms": {
uri: fmt.Sprintf(AzureKMSURI, "", ""),
errExpected: true,
wantErr: true,
},
"azure hsm": {
uri: fmt.Sprintf(AzureHSMURI, ""),
errExpected: true,
wantErr: true,
},
"gcp kms": {
uri: fmt.Sprintf(GCPKMSURI, "", "", "", ""),
errExpected: true,
wantErr: true,
},
"unknown kms": {
uri: "kms://unknown",
errExpected: true,
wantErr: true,
},
"invalid scheme": {
uri: NoStoreURI,
errExpected: true,
wantErr: true,
},
"not a url": {
uri: ":/123",
errExpected: true,
wantErr: true,
},
}
@ -103,7 +103,7 @@ func TestGetKMS(t *testing.T) {
assert := assert.New(t)
kms, err := getKMS(context.Background(), tc.uri, nil)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -184,32 +184,32 @@ func TestGetConfig(t *testing.T) {
testCases := map[string]struct {
uri string
keys []string
errExpected bool
wantErr bool
}{
"success": {
uri: testUri,
keys: []string{"name", "data", "value"},
errExpected: false,
wantErr: false,
},
"less keys than capture groups": {
uri: testUri,
keys: []string{"name", "data"},
errExpected: false,
wantErr: false,
},
"invalid regex": {
uri: testUri,
keys: []string{"name", "data", "test-value"},
errExpected: true,
wantErr: true,
},
"missing value": {
uri: "test://config?name=test-name&data=test-data&value",
keys: []string{"name", "data", "value"},
errExpected: true,
wantErr: true,
},
"more keys than expected": {
uri: testUri,
keys: []string{"name", "data", "value", "anotherValue"},
errExpected: true,
wantErr: true,
},
}
@ -222,7 +222,7 @@ func TestGetConfig(t *testing.T) {
require.NoError(err)
res, err := getConfig(uri.Query(), tc.keys)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
assert.Len(res, len(tc.keys))
} else {

View File

@ -11,42 +11,42 @@ import (
func TestParseJoinCommand(t *testing.T) {
testCases := map[string]struct {
joinCommand string
expectedJoinArgs kubeadm.BootstrapTokenDiscovery
expectErr bool
wantJoinArgs kubeadm.BootstrapTokenDiscovery
wantErr bool
}{
"join command can be parsed": {
joinCommand: "kubeadm join 192.0.2.0:8443 --token dummy-token --discovery-token-ca-cert-hash sha512:dummy-hash --control-plane",
expectedJoinArgs: kubeadm.BootstrapTokenDiscovery{
wantJoinArgs: kubeadm.BootstrapTokenDiscovery{
APIServerEndpoint: "192.0.2.0:8443",
Token: "dummy-token",
CACertHashes: []string{"sha512:dummy-hash"},
},
expectErr: false,
wantErr: false,
},
"incorrect join command returns error": {
joinCommand: "some string",
expectErr: true,
wantErr: true,
},
"missing api server endpoint is checked": {
joinCommand: "kubeadm join --token dummy-token --discovery-token-ca-cert-hash sha512:dummy-hash --control-plane",
expectErr: true,
wantErr: true,
},
"missing token is checked": {
joinCommand: "kubeadm join 192.0.2.0:8443 --discovery-token-ca-cert-hash sha512:dummy-hash --control-plane",
expectErr: true,
wantErr: true,
},
"missing discovery-token-ca-cert-hash is checked": {
joinCommand: "kubeadm join 192.0.2.0:8443 --token dummy-token --control-plane",
expectErr: true,
wantErr: true,
},
"missing control-plane": {
joinCommand: "kubeadm join 192.0.2.0:8443 --token dummy-token --discovery-token-ca-cert-hash sha512:dummy-hash",
expectedJoinArgs: kubeadm.BootstrapTokenDiscovery{
wantJoinArgs: kubeadm.BootstrapTokenDiscovery{
APIServerEndpoint: "192.0.2.0:8443",
Token: "dummy-token",
CACertHashes: []string{"sha512:dummy-hash"},
},
expectErr: false,
wantErr: false,
},
}
@ -57,13 +57,13 @@ func TestParseJoinCommand(t *testing.T) {
joinArgs, err := ParseJoinCommand(tc.joinCommand)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(&tc.expectedJoinArgs, joinArgs)
assert.Equal(&tc.wantJoinArgs, joinArgs)
})
}
}

View File

@ -176,25 +176,25 @@ func marshalYAML(obj runtime.Object) ([]byte, error) {
func TestApplyOneObject(t *testing.T) {
testCases := map[string]struct {
httpResponseData map[string]string
expectedObj runtime.Object
wantObj runtime.Object
resourcesYAML string
failingClient bool
expectErr bool
wantErr bool
}{
"apply works": {
httpResponseData: map[string]string{
"/deployments/my-nginx?fieldManager=constellation-coordinator&force=true": string(nginxDeplJSON),
},
expectedObj: nginxDeployment,
wantObj: nginxDeployment,
resourcesYAML: string(nginxDeplYAML),
expectErr: false,
wantErr: false,
},
"apply fails": {
httpResponseData: map[string]string{},
expectedObj: nginxDeployment,
wantObj: nginxDeployment,
resourcesYAML: string(nginxDeplYAML),
failingClient: true,
expectErr: true,
wantErr: true,
},
}
@ -205,9 +205,9 @@ func TestApplyOneObject(t *testing.T) {
var client Client
if tc.failingClient {
client = newFailingClient(tc.expectedObj)
client = newFailingClient(tc.wantObj)
} else {
client = newClientWithFakes(t, tc.httpResponseData, tc.expectedObj)
client = newClientWithFakes(t, tc.httpResponseData, tc.wantObj)
}
reader := bytes.NewReader([]byte(tc.resourcesYAML))
@ -223,7 +223,7 @@ func TestApplyOneObject(t *testing.T) {
err = client.ApplyOneObject(infos[0], true)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -234,30 +234,30 @@ func TestApplyOneObject(t *testing.T) {
func TestGetObjects(t *testing.T) {
testCases := map[string]struct {
expectedResources resources.Marshaler
wantResources resources.Marshaler
httpResponseData map[string]string
resourcesYAML string
expectErr bool
wantErr bool
}{
"GetObjects works on flannel deployment": {
expectedResources: resources.NewDefaultFlannelDeployment(),
wantResources: resources.NewDefaultFlannelDeployment(),
resourcesYAML: string(nginxDeplYAML),
expectErr: false,
wantErr: false,
},
"GetObjects works on cluster-autoscaler deployment": {
expectedResources: resources.NewDefaultFlannelDeployment(),
wantResources: resources.NewDefaultFlannelDeployment(),
resourcesYAML: string(nginxDeplYAML),
expectErr: false,
wantErr: false,
},
"GetObjects works on cloud-controller-manager deployment": {
expectedResources: resources.NewDefaultCloudControllerManagerDeployment("someProvider", "someImage", "somePath", nil, nil, nil, nil),
wantResources: resources.NewDefaultCloudControllerManagerDeployment("someProvider", "someImage", "somePath", nil, nil, nil, nil),
resourcesYAML: string(nginxDeplYAML),
expectErr: false,
wantErr: false,
},
"GetObjects Marshal failure detected": {
expectedResources: &unmarshableResource{},
wantResources: &unmarshableResource{},
resourcesYAML: string(nginxDeplYAML),
expectErr: true,
wantErr: true,
},
}
@ -267,9 +267,9 @@ func TestGetObjects(t *testing.T) {
require := require.New(t)
client := newClientWithFakes(t, tc.httpResponseData)
infos, err := client.GetObjects(tc.expectedResources)
infos, err := client.GetObjects(tc.wantResources)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -14,8 +14,8 @@ import (
func TestMarshalK8SResources(t *testing.T) {
testCases := map[string]struct {
resources interface{}
expectErr bool
expectedYAML string
wantErr bool
wantYAML string
}{
"ConfigMap as only field can be marshaled": {
resources: &struct {
@ -31,7 +31,7 @@ func TestMarshalK8SResources(t *testing.T) {
},
},
},
expectedYAML: `apiVersion: v1
wantYAML: `apiVersion: v1
data:
key: value
kind: ConfigMap
@ -63,7 +63,7 @@ metadata:
},
},
},
expectedYAML: `apiVersion: v1
wantYAML: `apiVersion: v1
data:
key: value
kind: ConfigMap
@ -80,11 +80,11 @@ metadata:
},
"Non-pointer is detected": {
resources: "non-pointer",
expectErr: true,
wantErr: true,
},
"Nil resource pointer is detected": {
resources: nil,
expectErr: true,
wantErr: true,
},
"Non-pointer field is ignored": {
resources: &struct{ String string }{String: "somestring"},
@ -105,13 +105,13 @@ metadata:
yaml, err := MarshalK8SResources(tc.resources)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedYAML, string(yaml))
assert.Equal(tc.wantYAML, string(yaml))
})
}
}
@ -120,8 +120,8 @@ func TestUnmarshalK8SResources(t *testing.T) {
testCases := map[string]struct {
data string
into interface{}
expectedObj interface{}
expectErr bool
wantObj interface{}
wantErr bool
}{
"ConfigMap as only field can be unmarshaled": {
data: `apiVersion: v1
@ -134,7 +134,7 @@ metadata:
into: &struct {
ConfigMap k8s.ConfigMap
}{},
expectedObj: &struct {
wantObj: &struct {
ConfigMap k8s.ConfigMap
}{
ConfigMap: k8s.ConfigMap{
@ -167,7 +167,7 @@ metadata:
ConfigMap k8s.ConfigMap
Secret k8s.Secret
}{},
expectedObj: &struct {
wantObj: &struct {
ConfigMap k8s.ConfigMap
Secret k8s.Secret
}{
@ -209,15 +209,15 @@ metadata:
into: &struct {
ConfigMap k8s.ConfigMap
}{},
expectErr: true,
wantErr: true,
},
"Non-struct pointer is detected": {
into: proto.String("test"),
expectErr: true,
wantErr: true,
},
"Nil into is detected": {
into: nil,
expectErr: true,
wantErr: true,
},
"Invalid yaml is detected": {
data: `duplicateKey: value
@ -225,7 +225,7 @@ metadata:
into: &struct {
ConfigMap k8s.ConfigMap
}{},
expectErr: true,
wantErr: true,
},
"Struct field cannot interface with runtime.Object": {
data: `apiVersion: v1
@ -238,7 +238,7 @@ metadata:
into: &struct {
String string
}{},
expectErr: true,
wantErr: true,
},
"Struct field mismatch": {
data: `apiVersion: v1
@ -251,7 +251,7 @@ metadata:
into: &struct {
Secret k8s.Secret
}{},
expectErr: true,
wantErr: true,
},
}
@ -262,13 +262,13 @@ metadata:
err := UnmarshalK8SResources([]byte(tc.data), tc.into)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedObj, tc.into)
assert.Equal(tc.wantObj, tc.into)
})
}
}
@ -276,8 +276,8 @@ metadata:
func TestMarshalK8SResourcesList(t *testing.T) {
testCases := map[string]struct {
resources []runtime.Object
expectErr bool
expectedYAML string
wantErr bool
wantYAML string
}{
"ConfigMap as only element be marshaled": {
resources: []runtime.Object{
@ -291,7 +291,7 @@ func TestMarshalK8SResourcesList(t *testing.T) {
},
},
},
expectedYAML: `apiVersion: v1
wantYAML: `apiVersion: v1
data:
key: value
kind: ConfigMap
@ -320,7 +320,7 @@ metadata:
},
},
},
expectedYAML: `apiVersion: v1
wantYAML: `apiVersion: v1
data:
key: value
kind: ConfigMap
@ -337,7 +337,7 @@ metadata:
},
"Nil resource pointer is encodes": {
resources: []runtime.Object{nil},
expectedYAML: "null\n",
wantYAML: "null\n",
},
}
@ -348,13 +348,13 @@ metadata:
yaml, err := MarshalK8SResourcesList(tc.resources)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedYAML, string(yaml))
assert.Equal(tc.wantYAML, string(yaml))
})
}
}

View File

@ -131,7 +131,7 @@ func TestInitCluster(t *testing.T) {
kubeconfigReader stubKubeconfigReader
initConfig k8sapi.KubeadmInitYAML
joinConfig k8sapi.KubeadmJoinYAML
expectErr bool
wantErr bool
}{
"kubeadm init works": {
clusterUtil: stubClusterUtil{
@ -144,7 +144,7 @@ func TestInitCluster(t *testing.T) {
kubeconfigReader: stubKubeconfigReader{
Kubeconfig: []byte("someKubeconfig"),
},
expectErr: false,
wantErr: false,
},
"kubeadm init errors": {
clusterUtil: stubClusterUtil{
@ -154,7 +154,7 @@ func TestInitCluster(t *testing.T) {
kubeconfigReader: stubKubeconfigReader{
Kubeconfig: []byte("someKubeconfig"),
},
expectErr: true,
wantErr: true,
},
"pod network setup errors": {
clusterUtil: stubClusterUtil{
@ -164,7 +164,7 @@ func TestInitCluster(t *testing.T) {
kubeconfigReader: stubKubeconfigReader{
Kubeconfig: []byte("someKubeconfig"),
},
expectErr: true,
wantErr: true,
},
}
@ -193,7 +193,7 @@ func TestInitCluster(t *testing.T) {
},
)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -223,15 +223,15 @@ func TestJoinCluster(t *testing.T) {
testCases := map[string]struct {
clusterUtil stubClusterUtil
expectErr bool
wantErr bool
}{
"kubeadm join works": {
clusterUtil: stubClusterUtil{},
expectErr: false,
wantErr: false,
},
"kubeadm join errors": {
clusterUtil: stubClusterUtil{joinClusterErr: someErr},
expectErr: true,
wantErr: true,
},
}
@ -242,7 +242,7 @@ func TestJoinCluster(t *testing.T) {
kube := New(&tc.clusterUtil, &stubConfigProvider{}, &client)
err := kube.JoinCluster(joinCommand, instanceName, nodeVPNIP, nodeVPNIP, coordinatorProviderID, "", role.Node)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -262,7 +262,7 @@ func TestJoinCluster(t *testing.T) {
func TestGetKubeconfig(t *testing.T) {
testCases := map[string]struct {
Kubewrapper KubeWrapper
expectErr bool
wantErr bool
}{
"check single replacement": {
Kubewrapper: KubeWrapper{kubeconfigReader: &stubKubeconfigReader{

View File

@ -14,12 +14,12 @@ import (
func TestFromFile(t *testing.T) {
testCases := map[string]struct {
fileContents string
expectedState *NodeState
errExpected bool
wantState *NodeState
wantErr bool
}{
"nodestate exists": {
fileContents: `{ "Role": "Coordinator", "VPNPrivKey": "dGVzdA==", "OwnerID": "T3duZXJJRA==", "ClusterID": "Q2x1c3RlcklE" }`,
expectedState: &NodeState{
wantState: &NodeState{
Role: role.Coordinator,
VPNPrivKey: []byte("test"),
OwnerID: []byte("OwnerID"),
@ -27,7 +27,7 @@ func TestFromFile(t *testing.T) {
},
},
"nodestate file does not exist": {
errExpected: true,
wantErr: true,
},
}
@ -43,12 +43,12 @@ func TestFromFile(t *testing.T) {
}
fileHandler := file.NewHandler(fs)
state, err := FromFile(fileHandler)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedState, state)
assert.Equal(tc.wantState, state)
})
}
}
@ -57,8 +57,8 @@ func TestToFile(t *testing.T) {
testCases := map[string]struct {
precreateFile bool
state *NodeState
expectedFile string
errExpected bool
wantFile string
wantErr bool
}{
"writing works": {
state: &NodeState{
@ -67,7 +67,7 @@ func TestToFile(t *testing.T) {
OwnerID: []byte("OwnerID"),
ClusterID: []byte("ClusterID"),
},
expectedFile: `{
wantFile: `{
"Role": "Coordinator",
"VPNPrivKey": "dGVzdA==",
"OwnerID": "T3duZXJJRA==",
@ -76,7 +76,7 @@ func TestToFile(t *testing.T) {
},
"file exists already": {
precreateFile: true,
errExpected: true,
wantErr: true,
},
}
@ -92,7 +92,7 @@ func TestToFile(t *testing.T) {
}
fileHandler := file.NewHandler(fs)
err := tc.state.ToFile(fileHandler)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
@ -100,7 +100,7 @@ func TestToFile(t *testing.T) {
fileContents, err := afero.ReadFile(fs, nodeStatePath)
require.NoError(err)
assert.Equal(tc.expectedFile, string(fileContents))
assert.Equal(tc.wantFile, string(fileContents))
})
}
}

View File

@ -34,78 +34,78 @@ func TestActivateAsCoordinator(t *testing.T) {
testNode1 := newStubPeer("192.0.2.11", []byte{1, 2, 3})
testNode2 := newStubPeer("192.0.2.12", []byte{2, 3, 4})
testNode3 := newStubPeer("192.0.2.13", []byte{3, 4, 5})
expectedNode1 := peer.Peer{PublicIP: "192.0.2.11", VPNIP: "10.118.0.11", VPNPubKey: []byte{1, 2, 3}, Role: role.Node}
expectedNode2 := peer.Peer{PublicIP: "192.0.2.12", VPNIP: "10.118.0.12", VPNPubKey: []byte{2, 3, 4}, Role: role.Node}
expectedNode3 := peer.Peer{PublicIP: "192.0.2.13", VPNIP: "10.118.0.13", VPNPubKey: []byte{3, 4, 5}, Role: role.Node}
expectedCoord := peer.Peer{PublicIP: "192.0.2.1", VPNIP: "10.118.0.1", VPNPubKey: coordinatorPubKey, Role: role.Coordinator}
wantNode1 := peer.Peer{PublicIP: "192.0.2.11", VPNIP: "10.118.0.11", VPNPubKey: []byte{1, 2, 3}, Role: role.Node}
wantNode2 := peer.Peer{PublicIP: "192.0.2.12", VPNIP: "10.118.0.12", VPNPubKey: []byte{2, 3, 4}, Role: role.Node}
wantNode3 := peer.Peer{PublicIP: "192.0.2.13", VPNIP: "10.118.0.13", VPNPubKey: []byte{3, 4, 5}, Role: role.Node}
wantCoord := peer.Peer{PublicIP: "192.0.2.1", VPNIP: "10.118.0.1", VPNPubKey: coordinatorPubKey, Role: role.Coordinator}
adminPeer := peer.Peer{VPNPubKey: []byte{7, 8, 9}, Role: role.Admin}
testCases := map[string]struct {
nodes []*stubPeer
state state.State
switchToPersistentStoreErr error
expectErr bool
expectedPeers []peer.Peer
expectedState state.State
wantErr bool
wantPeers []peer.Peer
wantState state.State
adminVPNIP string
}{
"0 nodes": {
state: state.AcceptingInit,
expectedPeers: []peer.Peer{expectedCoord},
expectedState: state.ActivatingNodes,
wantPeers: []peer.Peer{wantCoord},
wantState: state.ActivatingNodes,
adminVPNIP: "10.118.0.11",
},
"1 node": {
nodes: []*stubPeer{testNode1},
state: state.AcceptingInit,
expectedPeers: []peer.Peer{expectedCoord, expectedNode1},
expectedState: state.ActivatingNodes,
wantPeers: []peer.Peer{wantCoord, wantNode1},
wantState: state.ActivatingNodes,
adminVPNIP: "10.118.0.12",
},
"2 nodes": {
nodes: []*stubPeer{testNode1, testNode2},
state: state.AcceptingInit,
expectedPeers: []peer.Peer{expectedCoord, expectedNode1, expectedNode2},
expectedState: state.ActivatingNodes,
wantPeers: []peer.Peer{wantCoord, wantNode1, wantNode2},
wantState: state.ActivatingNodes,
adminVPNIP: "10.118.0.13",
},
"3 nodes": {
nodes: []*stubPeer{testNode1, testNode2, testNode3},
state: state.AcceptingInit,
expectedPeers: []peer.Peer{expectedCoord, expectedNode1, expectedNode2, expectedNode3},
expectedState: state.ActivatingNodes,
wantPeers: []peer.Peer{wantCoord, wantNode1, wantNode2, wantNode3},
wantState: state.ActivatingNodes,
adminVPNIP: "10.118.0.14",
},
"already activated": {
nodes: []*stubPeer{testNode1},
state: state.ActivatingNodes,
expectErr: true,
expectedState: state.ActivatingNodes,
wantErr: true,
wantState: state.ActivatingNodes,
},
"wrong peer kind": {
nodes: []*stubPeer{testNode1},
state: state.IsNode,
expectErr: true,
expectedState: state.IsNode,
wantErr: true,
wantState: state.IsNode,
},
"node activation error": {
nodes: []*stubPeer{testNode1, {activateErr: someErr}, testNode3},
state: state.AcceptingInit,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
"node join error": {
nodes: []*stubPeer{testNode1, {joinErr: someErr}, testNode3},
state: state.AcceptingInit,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
"SwitchToPersistentStore error": {
nodes: []*stubPeer{testNode1},
state: state.AcceptingInit,
switchToPersistentStoreErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
}
@ -162,9 +162,9 @@ func TestActivateAsCoordinator(t *testing.T) {
StorageUri: kms.NoStoreURI,
}, stream)
assert.Equal(tc.expectedState, core.state)
assert.Equal(tc.wantState, core.state)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -188,7 +188,7 @@ func TestActivateAsCoordinator(t *testing.T) {
assert.Equal(vpnIP, core.vpnIP)
// construct full list of expected peers
adminPeer.VPNIP = tc.adminVPNIP
assert.Equal(append(tc.expectedPeers, adminPeer), core.peers)
assert.Equal(append(tc.wantPeers, adminPeer), core.peers)
assert.Equal(autoscalingNodeGroups, core.autoscalingNodeGroups)
assert.Equal(keyEncryptionKeyID, core.kekID)
assert.Equal([]role.Role{role.Coordinator}, core.persistNodeStateRoles)
@ -201,15 +201,15 @@ func TestActivateAdditionalNodes(t *testing.T) {
testNode1 := newStubPeer("192.0.2.11", []byte{1, 2, 3})
testNode2 := newStubPeer("192.0.2.12", []byte{2, 3, 4})
testNode3 := newStubPeer("192.0.2.13", []byte{3, 4, 5})
expectedNode1 := peer.Peer{PublicIP: "192.0.2.11", VPNIP: "10.118.0.11", VPNPubKey: []byte{1, 2, 3}, Role: role.Node}
expectedNode2 := peer.Peer{PublicIP: "192.0.2.12", VPNIP: "10.118.0.12", VPNPubKey: []byte{2, 3, 4}, Role: role.Node}
expectedNode3 := peer.Peer{PublicIP: "192.0.2.13", VPNIP: "10.118.0.13", VPNPubKey: []byte{3, 4, 5}, Role: role.Node}
wantNode1 := peer.Peer{PublicIP: "192.0.2.11", VPNIP: "10.118.0.11", VPNPubKey: []byte{1, 2, 3}, Role: role.Node}
wantNode2 := peer.Peer{PublicIP: "192.0.2.12", VPNIP: "10.118.0.12", VPNPubKey: []byte{2, 3, 4}, Role: role.Node}
wantNode3 := peer.Peer{PublicIP: "192.0.2.13", VPNIP: "10.118.0.13", VPNPubKey: []byte{3, 4, 5}, Role: role.Node}
testCases := map[string]struct {
nodes []*stubPeer
state state.State
expectErr bool
expectedPeers []peer.Peer
wantErr bool
wantPeers []peer.Peer
}{
"0 nodes": {
state: state.ActivatingNodes,
@ -217,36 +217,36 @@ func TestActivateAdditionalNodes(t *testing.T) {
"1 node": {
nodes: []*stubPeer{testNode1},
state: state.ActivatingNodes,
expectedPeers: []peer.Peer{expectedNode1},
wantPeers: []peer.Peer{wantNode1},
},
"2 nodes": {
nodes: []*stubPeer{testNode1, testNode2},
state: state.ActivatingNodes,
expectedPeers: []peer.Peer{expectedNode1, expectedNode2},
wantPeers: []peer.Peer{wantNode1, wantNode2},
},
"3 nodes": {
nodes: []*stubPeer{testNode1, testNode2, testNode3},
state: state.ActivatingNodes,
expectedPeers: []peer.Peer{expectedNode1, expectedNode2, expectedNode3},
wantPeers: []peer.Peer{wantNode1, wantNode2, wantNode3},
},
"uninitialized": {
nodes: []*stubPeer{testNode1},
expectErr: true,
wantErr: true,
},
"wrong peer kind": {
nodes: []*stubPeer{testNode1},
state: state.IsNode,
expectErr: true,
wantErr: true,
},
"node activation error": {
nodes: []*stubPeer{testNode1, {activateErr: someErr}, testNode3},
state: state.ActivatingNodes,
expectErr: true,
wantErr: true,
},
"node join error": {
nodes: []*stubPeer{testNode1, {joinErr: someErr}, testNode3},
state: state.ActivatingNodes,
expectErr: true,
wantErr: true,
},
}
@ -283,7 +283,7 @@ func TestActivateAdditionalNodes(t *testing.T) {
require.NoError(core.InitializeStoreIPs())
stream := &stubActivateAdditionalNodesServer{}
err := api.ActivateAdditionalNodes(&pubproto.ActivateAdditionalNodesRequest{NodePublicIps: nodePublicIPs}, stream)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -296,7 +296,7 @@ func TestActivateAdditionalNodes(t *testing.T) {
}
// Core is updated
assert.Equal(tc.expectedPeers, core.peers)
assert.Equal(tc.wantPeers, core.peers)
})
}
}
@ -316,7 +316,7 @@ func TestAssemblePeerStruct(t *testing.T) {
vpnIP, err := core.GetVPNIP()
require.NoError(err)
expected := peer.Peer{
want := peer.Peer{
PublicIP: "192.0.2.1",
VPNIP: vpnIP,
VPNPubKey: vpnPubKey,
@ -325,7 +325,7 @@ func TestAssemblePeerStruct(t *testing.T) {
actual, err := api.assemblePeerStruct(vpnIP, role.Coordinator)
require.NoError(err)
assert.Equal(expected, actual)
assert.Equal(want, actual)
}
type stubPeer struct {
@ -452,7 +452,7 @@ func TestRequestStateDiskKey(t *testing.T) {
dataKey []byte
getDataKeyErr error
pushKeyErr error
errExpected bool
wantErr bool
}{
"success": {
state: state.ActivatingNodes,
@ -461,19 +461,19 @@ func TestRequestStateDiskKey(t *testing.T) {
"Coordinator in wrong state": {
state: state.IsNode,
dataKey: defaultKey,
errExpected: true,
wantErr: true,
},
"GetDataKey fails": {
state: state.ActivatingNodes,
dataKey: defaultKey,
getDataKeyErr: someErr,
errExpected: true,
wantErr: true,
},
"key pushing fails": {
state: state.ActivatingNodes,
dataKey: defaultKey,
pushKeyErr: someErr,
errExpected: true,
wantErr: true,
},
}
@ -515,7 +515,7 @@ func TestRequestStateDiskKey(t *testing.T) {
api := New(zaptest.NewLogger(t), core, &net.Dialer{}, nil, dummyValidator{}, nil, getPeerFromContext)
_, err = api.RequestStateDiskKey(ctx, &pubproto.RequestStateDiskKeyRequest{})
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -30,9 +30,9 @@ func TestActivateAsAdditionalCoordinator(t *testing.T) {
testCases := map[string]struct {
coordinators stubPeer
state state.State
expectedState state.State
wantState state.State
vpnapi stubVPNAPI
expectErr bool
wantErr bool
switchToPersistentStoreErr error
k8sJoinargsErr error
k8sCertKeyErr error
@ -40,29 +40,29 @@ func TestActivateAsAdditionalCoordinator(t *testing.T) {
"basic": {
coordinators: testCoord1,
state: state.AcceptingInit,
expectedState: state.ActivatingNodes,
wantState: state.ActivatingNodes,
vpnapi: stubVPN,
},
"already activated": {
state: state.ActivatingNodes,
expectErr: true,
expectedState: state.ActivatingNodes,
wantErr: true,
wantState: state.ActivatingNodes,
vpnapi: stubVPN,
},
"SwitchToPersistentStore error": {
coordinators: testCoord1,
state: state.AcceptingInit,
switchToPersistentStoreErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
vpnapi: stubVPN,
},
"GetK8SJoinArgs error": {
coordinators: testCoord1,
state: state.AcceptingInit,
switchToPersistentStoreErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
vpnapi: stubVPN,
k8sJoinargsErr: someErr,
},
@ -70,8 +70,8 @@ func TestActivateAsAdditionalCoordinator(t *testing.T) {
coordinators: testCoord1,
state: state.AcceptingInit,
switchToPersistentStoreErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
vpnapi: stubVPN,
k8sCertKeyErr: someErr,
},
@ -113,9 +113,9 @@ func TestActivateAsAdditionalCoordinator(t *testing.T) {
ClusterId: core.clusterID,
})
assert.Equal(tc.expectedState, core.state)
assert.Equal(tc.wantState, core.state)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -135,7 +135,7 @@ func TestTriggerCoordinatorUpdate(t *testing.T) {
peers []peer.Peer
state state.State
getUpdateErr error
expectErr bool
wantErr bool
}{
"basic": {
peers: peers,
@ -144,12 +144,12 @@ func TestTriggerCoordinatorUpdate(t *testing.T) {
"not activated": {
peers: peers,
state: state.AcceptingInit,
expectErr: true,
wantErr: true,
},
"wrong peer kind": {
peers: peers,
state: state.IsNode,
expectErr: true,
wantErr: true,
},
}
@ -168,7 +168,7 @@ func TestTriggerCoordinatorUpdate(t *testing.T) {
api := New(logger, core, dialer, nil, nil, nil, nil)
_, err := api.TriggerCoordinatorUpdate(context.Background(), &pubproto.TriggerCoordinatorUpdateRequest{})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -194,33 +194,33 @@ func TestActivateAdditionalCoordinators(t *testing.T) {
state state.State
activateErr error
getPublicKeyErr error
expectErr bool
expectedState state.State
wantErr bool
wantState state.State
}{
"basic": {
coordinators: testCoord1,
state: state.ActivatingNodes,
expectedState: state.ActivatingNodes,
wantState: state.ActivatingNodes,
},
"Activation Err": {
coordinators: testCoord1,
state: state.ActivatingNodes,
expectedState: state.ActivatingNodes,
wantState: state.ActivatingNodes,
activateErr: someErr,
expectErr: true,
wantErr: true,
},
"Not in exprected state": {
coordinators: testCoord1,
state: state.AcceptingInit,
expectedState: state.AcceptingInit,
expectErr: true,
wantState: state.AcceptingInit,
wantErr: true,
},
"getPeerPublicKey error": {
coordinators: testCoord1,
state: state.ActivatingNodes,
expectedState: state.ActivatingNodes,
wantState: state.ActivatingNodes,
getPublicKeyErr: someErr,
expectErr: true,
wantErr: true,
},
}
@ -254,9 +254,9 @@ func TestActivateAdditionalCoordinators(t *testing.T) {
_, err := api.ActivateAdditionalCoordinator(context.Background(), &pubproto.ActivateAdditionalCoordinatorRequest{CoordinatorPublicIp: tc.coordinators.peer.PublicIP})
assert.Equal(tc.expectedState, core.state)
assert.Equal(tc.wantState, core.state)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -272,7 +272,7 @@ func TestGetPeerVPNPublicKey(t *testing.T) {
testCases := map[string]struct {
coordinator stubPeer
getVPNPubKeyErr error
expectErr bool
wantErr bool
}{
"basic": {
coordinator: testCoord,
@ -280,7 +280,7 @@ func TestGetPeerVPNPublicKey(t *testing.T) {
"Activation Err": {
coordinator: testCoord,
getVPNPubKeyErr: someErr,
expectErr: true,
wantErr: true,
},
}
@ -304,7 +304,7 @@ func TestGetPeerVPNPublicKey(t *testing.T) {
resp, err := api.GetPeerVPNPublicKey(context.Background(), &pubproto.GetPeerVPNPublicKeyRequest{})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -35,75 +35,75 @@ func TestActivateAsNode(t *testing.T) {
getUpdateErr error
setVPNIPErr error
messageSequenceOverride []string
expectErr bool
expectedState state.State
wantErr bool
wantState state.State
}{
"basic": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
expectedState: state.NodeWaitingForClusterJoin,
wantState: state.NodeWaitingForClusterJoin,
},
"already activated": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.IsNode,
expectErr: true,
expectedState: state.IsNode,
wantErr: true,
wantState: state.IsNode,
},
"wrong peer kind": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.ActivatingNodes,
expectErr: true,
expectedState: state.ActivatingNodes,
wantErr: true,
wantState: state.ActivatingNodes,
},
"GetUpdate error": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
getUpdateErr: someErr,
expectedState: state.NodeWaitingForClusterJoin,
wantState: state.NodeWaitingForClusterJoin,
},
"SetVPNIP error": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
setVPNIPErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
"no messages sent to node": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
messageSequenceOverride: []string{},
expectErr: true,
expectedState: state.AcceptingInit,
wantErr: true,
wantState: state.AcceptingInit,
},
"only initial message sent to node": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
messageSequenceOverride: []string{"initialRequest"},
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
"wrong initial message sent to node": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
messageSequenceOverride: []string{"stateDiskKey"},
expectErr: true,
expectedState: state.AcceptingInit,
wantErr: true,
wantState: state.AcceptingInit,
},
"initial message sent twice to node": {
initialPeers: []peer.Peer{peer1},
updatedPeers: []peer.Peer{peer2},
state: state.AcceptingInit,
messageSequenceOverride: []string{"initialRequest", "initialRequest"},
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
}
@ -146,9 +146,9 @@ func TestActivateAsNode(t *testing.T) {
defer pubserver.GracefulStop()
_, nodeVPNPubKey, err := activateNode(require, dialer, messageSequence, nodeIP, "9000", nodeVPNIP, peer.ToPubProto(tc.initialPeers), ownerID, clusterID, stateDiskKey)
assert.Equal(tc.expectedState, cor.state)
assert.Equal(tc.wantState, cor.state)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -184,7 +184,7 @@ func TestTriggerNodeUpdate(t *testing.T) {
peers []peer.Peer
state state.State
getUpdateErr error
expectErr bool
wantErr bool
}{
"basic": {
peers: peers,
@ -193,18 +193,18 @@ func TestTriggerNodeUpdate(t *testing.T) {
"not activated": {
peers: peers,
state: state.AcceptingInit,
expectErr: true,
wantErr: true,
},
"wrong peer kind": {
peers: peers,
state: state.ActivatingNodes,
expectErr: true,
wantErr: true,
},
"GetUpdate error": {
peers: peers,
state: state.IsNode,
getUpdateErr: someErr,
expectErr: true,
wantErr: true,
},
}
@ -229,7 +229,7 @@ func TestTriggerNodeUpdate(t *testing.T) {
defer vserver.GracefulStop()
_, err := api.TriggerNodeUpdate(context.Background(), &pubproto.TriggerNodeUpdateRequest{})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -252,34 +252,34 @@ func TestJoinCluster(t *testing.T) {
state state.State
getJoinArgsErr error
joinClusterErr error
expectErr bool
expectedState state.State
wantErr bool
wantState state.State
}{
"basic": {
state: state.NodeWaitingForClusterJoin,
expectedState: state.IsNode,
wantState: state.IsNode,
},
"not activated": {
state: state.AcceptingInit,
expectErr: true,
expectedState: state.AcceptingInit,
wantErr: true,
wantState: state.AcceptingInit,
},
"wrong peer kind": {
state: state.ActivatingNodes,
expectErr: true,
expectedState: state.ActivatingNodes,
wantErr: true,
wantState: state.ActivatingNodes,
},
"GetK8sJoinArgs error": {
state: state.NodeWaitingForClusterJoin,
getJoinArgsErr: someErr,
expectErr: true,
expectedState: state.NodeWaitingForClusterJoin,
wantErr: true,
wantState: state.NodeWaitingForClusterJoin,
},
"JoinCluster error": {
state: state.NodeWaitingForClusterJoin,
joinClusterErr: someErr,
expectErr: true,
expectedState: state.Failed,
wantErr: true,
wantState: state.Failed,
},
}
@ -309,9 +309,9 @@ func TestJoinCluster(t *testing.T) {
_, err := api.JoinCluster(context.Background(), &pubproto.JoinClusterRequest{CoordinatorVpnIp: "192.0.2.1"})
assert.Equal(tc.expectedState, core.state)
assert.Equal(tc.wantState, core.state)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -23,14 +23,14 @@ func TestGetRecoveryPeerFromContext(t *testing.T) {
assert := assert.New(t)
testIP := "192.0.2.1"
testPort := 1234
expectedPeer := net.JoinHostPort(testIP, "9000")
wantPeer := net.JoinHostPort(testIP, "9000")
addr := &net.TCPAddr{IP: net.ParseIP(testIP), Port: testPort}
ctx := grpcpeer.NewContext(context.Background(), &grpcpeer.Peer{Addr: addr})
peer, err := GetRecoveryPeerFromContext(ctx)
assert.NoError(err)
assert.Equal(expectedPeer, peer)
assert.Equal(wantPeer, peer)
_, err = GetRecoveryPeerFromContext(context.Background())
assert.Error(err)

View File

@ -10,24 +10,24 @@ import (
func TestMarshal(t *testing.T) {
testCases := map[string]struct {
role Role
jsonExpected string
errExpected bool
wantJson string
wantErr bool
}{
"coordinator role": {
role: Coordinator,
jsonExpected: `"Coordinator"`,
wantJson: `"Coordinator"`,
},
"node role": {
role: Node,
jsonExpected: `"Node"`,
wantJson: `"Node"`,
},
"admin role": {
role: Admin,
jsonExpected: `"Admin"`,
wantJson: `"Admin"`,
},
"unknown role": {
role: Unknown,
jsonExpected: `"Unknown"`,
wantJson: `"Unknown"`,
},
}
@ -37,13 +37,13 @@ func TestMarshal(t *testing.T) {
require := require.New(t)
jsonRole, err := tc.role.MarshalJSON()
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.jsonExpected, string(jsonRole))
assert.Equal(tc.wantJson, string(jsonRole))
})
}
}
@ -51,40 +51,40 @@ func TestMarshal(t *testing.T) {
func TestUnmarshal(t *testing.T) {
testCases := map[string]struct {
json string
expectedRole Role
errExpected bool
wantRole Role
wantErr bool
}{
"Coordinator can be unmarshaled": {
json: `"Coordinator"`,
expectedRole: Coordinator,
wantRole: Coordinator,
},
"lowercase coordinator can be unmarshaled": {
json: `"coordinator"`,
expectedRole: Coordinator,
wantRole: Coordinator,
},
"Node can be unmarshaled": {
json: `"Node"`,
expectedRole: Node,
wantRole: Node,
},
"lowercase node can be unmarshaled": {
json: `"node"`,
expectedRole: Node,
wantRole: Node,
},
"Admin can be unmarshaled": {
json: `"Admin"`,
expectedRole: Admin,
wantRole: Admin,
},
"lowercase admin can be unmarshaled": {
json: `"admin"`,
expectedRole: Admin,
wantRole: Admin,
},
"other strings unmarshal to the unknown role": {
json: `"anything"`,
expectedRole: Unknown,
wantRole: Unknown,
},
"invalid json fails": {
json: `"unterminated string literal`,
errExpected: true,
wantErr: true,
},
}
@ -96,13 +96,13 @@ func TestUnmarshal(t *testing.T) {
var role Role
err := role.UnmarshalJSON([]byte(tc.json))
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedRole, role)
assert.Equal(tc.wantRole, role)
})
}
}

View File

@ -34,7 +34,7 @@ func TestGetUpdate(t *testing.T) {
clientAddr net.Addr
peers []peer.Peer
getPeersErr error
expectErr bool
wantErr bool
}{
"0 peers": {
clientAddr: clientIP,
@ -59,7 +59,7 @@ func TestGetUpdate(t *testing.T) {
"getPeers error": {
clientAddr: clientIP,
getPeersErr: someErr,
expectErr: true,
wantErr: true,
},
"missing client addr": {
peers: []peer.Peer{peer1},
@ -83,7 +83,7 @@ func TestGetUpdate(t *testing.T) {
}
resp, err := api.GetUpdate(ctx, &vpnproto.GetUpdateRequest{ResourceVersion: clientResourceVersion})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -94,10 +94,10 @@ func TestGetUpdate(t *testing.T) {
require.Len(resp.Peers, len(tc.peers))
for i, actual := range resp.Peers {
expected := tc.peers[i]
assert.EqualValues(expected.PublicIP, actual.PublicIp)
assert.EqualValues(expected.VPNIP, actual.VpnIp)
assert.Equal(expected.VPNPubKey, actual.VpnPubKey)
want := tc.peers[i]
assert.EqualValues(want.PublicIP, actual.PublicIp)
assert.EqualValues(want.VPNIP, actual.VpnIp)
assert.Equal(want.VPNPubKey, actual.VpnPubKey)
}
if tc.clientAddr == nil {
@ -150,14 +150,14 @@ func TestGetK8SCertificateKey(t *testing.T) {
testCases := map[string]struct {
certKey string
getCertKeyErr error
expectErr bool
wantErr bool
}{
"basic": {
certKey: certKey,
},
"error": {
getCertKeyErr: someErr,
expectErr: true,
wantErr: true,
},
}
for name, tc := range testCases {
@ -173,7 +173,7 @@ func TestGetK8SCertificateKey(t *testing.T) {
api := New(zaptest.NewLogger(t), core)
resp, err := api.GetK8SCertificateKey(context.Background(), &vpnproto.GetK8SCertificateKeyRequest{})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}

View File

@ -39,32 +39,32 @@ func TestUpdatePeer(t *testing.T) {
storePeers []peer.Peer
vpnPeers []wgtypes.Peer
excludedIP map[string]struct{}
expectErr bool
expectedVPNPeers []wgtypes.Peer
wantErr bool
wantVPNPeers []wgtypes.Peer
}{
"basic": {
storePeers: []peer.Peer{peer1, peer3},
vpnPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
expectedVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer3})),
wantVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer3})),
},
"previously empty": {
storePeers: []peer.Peer{peer1, peer2},
expectedVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
wantVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
},
"no changes": {
storePeers: []peer.Peer{peer1, peer2},
vpnPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
expectedVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
wantVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
},
"key update": {
storePeers: []peer.Peer{peer1KeyUpd, peer3},
vpnPeers: checkError(transformToWgpeer([]peer.Peer{peer1, peer2})),
expectedVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1KeyUpd, peer3})),
wantVPNPeers: checkError(transformToWgpeer([]peer.Peer{peer1KeyUpd, peer3})),
},
"not update Endpoint changes": {
storePeers: []peer.Peer{peerAdminNoEndp, peer3},
vpnPeers: checkError(transformToWgpeer([]peer.Peer{peerAdmin, peer3})),
expectedVPNPeers: checkError(transformToWgpeer([]peer.Peer{peerAdmin, peer3})),
wantVPNPeers: checkError(transformToWgpeer([]peer.Peer{peerAdmin, peer3})),
},
}
@ -81,13 +81,13 @@ func TestUpdatePeer(t *testing.T) {
updateErr := wg.UpdatePeers(tc.storePeers)
if tc.expectErr {
if tc.wantErr {
assert.Error(updateErr)
return
}
require.NoError(updateErr)
assert.ElementsMatch(tc.expectedVPNPeers, fakewg.devices[netInterface].Peers)
assert.ElementsMatch(tc.wantVPNPeers, fakewg.devices[netInterface].Peers)
})
}
}

View File

@ -18,8 +18,8 @@ func TestWriteStream(t *testing.T) {
readChunkStream fakeReadChunkStream
fs afero.Fs
showProgress bool
expectedFile []byte
expectErr bool
wantFile []byte
wantErr bool
}{
"stream works": {
readChunkStream: fakeReadChunkStream{
@ -28,8 +28,8 @@ func TestWriteStream(t *testing.T) {
},
},
fs: afero.NewMemMapFs(),
expectedFile: []byte("test"),
expectErr: false,
wantFile: []byte("test"),
wantErr: false,
},
"chunking works": {
readChunkStream: fakeReadChunkStream{
@ -39,8 +39,8 @@ func TestWriteStream(t *testing.T) {
},
},
fs: afero.NewMemMapFs(),
expectedFile: []byte("test"),
expectErr: false,
wantFile: []byte("test"),
wantErr: false,
},
"showProgress works": {
readChunkStream: fakeReadChunkStream{
@ -50,19 +50,19 @@ func TestWriteStream(t *testing.T) {
},
fs: afero.NewMemMapFs(),
showProgress: true,
expectedFile: []byte("test"),
expectErr: false,
wantFile: []byte("test"),
wantErr: false,
},
"Open fails": {
fs: afero.NewReadOnlyFs(afero.NewMemMapFs()),
expectErr: true,
wantErr: true,
},
"recv fails": {
readChunkStream: fakeReadChunkStream{
recvErr: errors.New("someErr"),
},
fs: afero.NewMemMapFs(),
expectErr: true,
wantErr: true,
},
}
@ -74,14 +74,14 @@ func TestWriteStream(t *testing.T) {
writer := NewFileStreamer(tc.fs)
err := writer.WriteStream(filename, &tc.readChunkStream, tc.showProgress)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
fileContents, err := afero.ReadFile(tc.fs, filename)
require.NoError(err)
assert.Equal(tc.expectedFile, fileContents)
assert.Equal(tc.wantFile, fileContents)
})
}
}
@ -94,48 +94,48 @@ func TestReadStream(t *testing.T) {
filename string
chunksize uint
showProgress bool
expectedChunks [][]byte
expectErr bool
wantChunks [][]byte
wantErr bool
}{
"stream works": {
writeChunkStream: stubWriteChunkStream{},
filename: correctFilename,
chunksize: 4,
expectedChunks: [][]byte{
wantChunks: [][]byte{
[]byte("test"),
},
expectErr: false,
wantErr: false,
},
"chunking works": {
writeChunkStream: stubWriteChunkStream{},
filename: correctFilename,
chunksize: 2,
expectedChunks: [][]byte{
wantChunks: [][]byte{
[]byte("te"),
[]byte("st"),
},
expectErr: false,
wantErr: false,
},
"chunksize of 0 detected": {
writeChunkStream: stubWriteChunkStream{},
filename: correctFilename,
chunksize: 0,
expectErr: true,
wantErr: true,
},
"showProgress works": {
writeChunkStream: stubWriteChunkStream{},
filename: correctFilename,
chunksize: 4,
showProgress: true,
expectedChunks: [][]byte{
wantChunks: [][]byte{
[]byte("test"),
},
expectErr: false,
wantErr: false,
},
"Open fails": {
filename: "incorrect-filename",
chunksize: 4,
expectErr: true,
wantErr: true,
},
"send fails": {
writeChunkStream: stubWriteChunkStream{
@ -143,7 +143,7 @@ func TestReadStream(t *testing.T) {
},
filename: correctFilename,
chunksize: 4,
expectErr: true,
wantErr: true,
},
}
@ -157,12 +157,12 @@ func TestReadStream(t *testing.T) {
reader := NewFileStreamer(fs)
err := reader.ReadStream(tc.filename, &tc.writeChunkStream, tc.chunksize, tc.showProgress)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedChunks, tc.writeChunkStream.chunks)
assert.Equal(tc.wantChunks, tc.writeChunkStream.chunks)
})
}
}

View File

@ -26,24 +26,24 @@ func TestDownloadCoordinator(t *testing.T) {
downloadClient stubDownloadClient
serviceManager stubServiceManager
attemptedDownloads map[string]time.Time
expectedChunks [][]byte
expectDownloadErr bool
expectFile bool
expectSystemdAction bool
expectDeployed bool
wantChunks [][]byte
wantDownloadErr bool
wantFile bool
wantSystemdAction bool
wantDeployed bool
}{
"download works": {
server: fakeOnlyDownloadServer{
chunks: [][]byte{[]byte("test")},
},
attemptedDownloads: map[string]time.Time{},
expectedChunks: [][]byte{
wantChunks: [][]byte{
[]byte("test"),
},
expectDownloadErr: false,
expectFile: true,
expectSystemdAction: true,
expectDeployed: true,
wantDownloadErr: false,
wantFile: true,
wantSystemdAction: true,
wantDeployed: true,
},
"second download is not attempted twice": {
server: fakeOnlyDownloadServer{
@ -52,14 +52,14 @@ func TestDownloadCoordinator(t *testing.T) {
attemptedDownloads: map[string]time.Time{
"192.0.2.0:4000": time.Now(),
},
expectDownloadErr: true,
wantDownloadErr: true,
},
"download rpc call error is detected": {
server: fakeOnlyDownloadServer{
downladErr: errors.New("download rpc error"),
},
attemptedDownloads: map[string]time.Time{},
expectDownloadErr: true,
wantDownloadErr: true,
},
"service restart error is detected": {
server: fakeOnlyDownloadServer{
@ -69,13 +69,13 @@ func TestDownloadCoordinator(t *testing.T) {
systemdActionErr: errors.New("systemd error"),
},
attemptedDownloads: map[string]time.Time{},
expectedChunks: [][]byte{
wantChunks: [][]byte{
[]byte("test"),
},
expectDownloadErr: true,
expectFile: true,
expectDeployed: true,
expectSystemdAction: false,
wantDownloadErr: true,
wantFile: true,
wantDeployed: true,
wantSystemdAction: false,
},
}
@ -101,17 +101,17 @@ func TestDownloadCoordinator(t *testing.T) {
err := download.DownloadCoordinator(context.Background(), ip)
grpcServ.GracefulStop()
if tc.expectDownloadErr {
if tc.wantDownloadErr {
assert.Error(err)
} else {
assert.NoError(err)
}
if tc.expectFile {
assert.Equal(tc.expectedChunks, writer.chunks)
if tc.wantFile {
assert.Equal(tc.wantChunks, writer.chunks)
assert.Equal(filename, writer.filename)
}
if tc.expectSystemdAction {
if tc.wantSystemdAction {
assert.ElementsMatch(
[]ServiceManagerRequest{
{Unit: debugd.CoordinatorSystemdUnitName, Action: Restart},

View File

@ -17,14 +17,14 @@ func TestGetLinuxUser(t *testing.T) {
testCases := map[string]struct {
userCreator *stubUserCreator
passwdContents string
expectErr bool
expectedUser LinuxUser
wantErr bool
wantUser LinuxUser
}{
"get works": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: false,
expectedUser: LinuxUser{
wantErr: false,
wantUser: LinuxUser{
Username: "user",
Home: "/home/user",
Uid: 1000,
@ -34,22 +34,22 @@ func TestGetLinuxUser(t *testing.T) {
"user does not exist": {
userCreator: &stubUserCreator{},
passwdContents: "",
expectErr: true,
wantErr: true,
},
"parse fails": {
userCreator: &stubUserCreator{},
passwdContents: "invalid contents\n",
expectErr: true,
wantErr: true,
},
"invalid uid": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:invalid:1000:user:/home/user:/bin/bash\n",
expectErr: true,
wantErr: true,
},
"invalid gid": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:invalid:user:/home/user:/bin/bash\n",
expectErr: true,
wantErr: true,
},
}
@ -67,12 +67,12 @@ func TestGetLinuxUser(t *testing.T) {
}
user, err := manager.getLinuxUser(username)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedUser, user)
assert.Equal(tc.wantUser, user)
})
}
}
@ -83,14 +83,14 @@ func TestEnsureLinuxUserExists(t *testing.T) {
testCases := map[string]struct {
userCreator *stubUserCreator
passwdContents string
expectErr bool
expectedUser LinuxUser
wantErr bool
wantUser LinuxUser
}{
"create works": {
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: false,
expectedUser: LinuxUser{
wantErr: false,
wantUser: LinuxUser{
Username: "user",
Home: "/home/user",
Uid: 1000,
@ -102,7 +102,7 @@ func TestEnsureLinuxUserExists(t *testing.T) {
createUserErr: errors.New("create fails"),
},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: true,
wantErr: true,
},
}
@ -120,12 +120,12 @@ func TestEnsureLinuxUserExists(t *testing.T) {
}
user, err := manager.EnsureLinuxUserExists(context.Background(), username)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedUser, user)
assert.Equal(tc.wantUser, user)
assert.ElementsMatch([]string{username}, tc.userCreator.usernames)
})
}

View File

@ -14,13 +14,13 @@ func TestParse(t *testing.T) {
testCases := map[string]struct {
passwdContents string
createFile bool
expectedEntries Entries
expectErr bool
wantEntries Entries
wantErr bool
}{
"parse works": {
passwdContents: "root:x:0:0:root:/root:/bin/bash\n",
createFile: true,
expectedEntries: Entries{
wantEntries: Entries{
"root": {
Pass: "x",
Uid: "0",
@ -30,16 +30,16 @@ func TestParse(t *testing.T) {
Shell: "/bin/bash",
},
},
expectErr: false,
wantErr: false,
},
"passwd is corrupt": {
passwdContents: "too:few:fields\n",
createFile: true,
expectErr: true,
wantErr: true,
},
"file does not exist": {
createFile: false,
expectErr: true,
wantErr: true,
},
}
@ -55,12 +55,12 @@ func TestParse(t *testing.T) {
passwd := Passwd{}
entries, err := passwd.Parse(fs)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedEntries, entries)
assert.Equal(tc.wantEntries, entries)
})
}
}

View File

@ -18,7 +18,7 @@ func TestSystemdAction(t *testing.T) {
testCases := map[string]struct {
dbus stubDbus
action SystemdAction
expectErr bool
wantErr bool
}{
"start works": {
dbus: stubDbus{
@ -27,7 +27,7 @@ func TestSystemdAction(t *testing.T) {
},
},
action: Start,
expectErr: false,
wantErr: false,
},
"stop works": {
dbus: stubDbus{
@ -36,7 +36,7 @@ func TestSystemdAction(t *testing.T) {
},
},
action: Stop,
expectErr: false,
wantErr: false,
},
"restart works": {
dbus: stubDbus{
@ -45,21 +45,21 @@ func TestSystemdAction(t *testing.T) {
},
},
action: Restart,
expectErr: false,
wantErr: false,
},
"reload works": {
dbus: stubDbus{
conn: &fakeDbusConn{},
},
action: Reload,
expectErr: false,
wantErr: false,
},
"unknown action": {
dbus: stubDbus{
conn: &fakeDbusConn{},
},
action: Unknown,
expectErr: true,
wantErr: true,
},
"action fails": {
dbus: stubDbus{
@ -68,7 +68,7 @@ func TestSystemdAction(t *testing.T) {
},
},
action: Start,
expectErr: true,
wantErr: true,
},
"action result is failure": {
dbus: stubDbus{
@ -77,14 +77,14 @@ func TestSystemdAction(t *testing.T) {
},
},
action: Start,
expectErr: true,
wantErr: true,
},
"newConn fails": {
dbus: stubDbus{
connErr: errors.New("newConn fails"),
},
action: Start,
expectErr: true,
wantErr: true,
},
}
@ -104,7 +104,7 @@ func TestSystemdAction(t *testing.T) {
Action: tc.action,
})
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
@ -118,8 +118,8 @@ func TestWriteSystemdUnitFile(t *testing.T) {
dbus stubDbus
unit SystemdUnit
readonly bool
expectErr bool
expectedFileContents string
wantErr bool
wantFileContents string
}{
"start works": {
dbus: stubDbus{
@ -131,8 +131,8 @@ func TestWriteSystemdUnitFile(t *testing.T) {
Name: "test.service",
Contents: "testservicefilecontents",
},
expectErr: false,
expectedFileContents: "testservicefilecontents",
wantErr: false,
wantFileContents: "testservicefilecontents",
},
"write fails": {
dbus: stubDbus{
@ -145,7 +145,7 @@ func TestWriteSystemdUnitFile(t *testing.T) {
Contents: "testservicefilecontents",
},
readonly: true,
expectErr: true,
wantErr: true,
},
"systemd reload fails": {
dbus: stubDbus{
@ -158,7 +158,7 @@ func TestWriteSystemdUnitFile(t *testing.T) {
Contents: "testservicefilecontents",
},
readonly: false,
expectErr: true,
wantErr: true,
},
}
@ -179,14 +179,14 @@ func TestWriteSystemdUnitFile(t *testing.T) {
}
err := manager.WriteSystemdUnitFile(context.Background(), tc.unit)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
fileContents, err := afero.ReadFile(fs, fmt.Sprintf("%s/%s", systemdUnitFolder, tc.unit.Name))
assert.NoError(err)
assert.Equal(tc.expectedFileContents, string(fileContents))
assert.Equal(tc.wantFileContents, string(fileContents))
})
}
}

View File

@ -24,46 +24,46 @@ func TestDeploySSHAuthorizedKey(t *testing.T) {
passwdContents string
alreadyDeployed bool
readonly bool
expectErr bool
expectFile bool
expectedFileContents string
wantErr bool
wantFile bool
wantFileContents string
}{
"deploy works": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: false,
expectFile: true,
expectedFileContents: "ssh-rsa testkey user\n",
wantErr: false,
wantFile: true,
wantFileContents: "ssh-rsa testkey user\n",
},
"appending ssh key works": {
fs: memMapFsWithFile("/home/user/.ssh/authorized_keys.d/debugd", "ssh-rsa preexistingkey user\n"),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: false,
expectFile: true,
expectedFileContents: "ssh-rsa preexistingkey user\nssh-rsa testkey user\n",
wantErr: false,
wantFile: true,
wantFileContents: "ssh-rsa preexistingkey user\nssh-rsa testkey user\n",
},
"redeployment avoided": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
expectErr: false,
wantErr: false,
alreadyDeployed: true,
expectFile: false,
wantFile: false,
},
"user does not exist": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "",
expectErr: true,
wantErr: true,
},
"readonly fs": {
fs: afero.NewMemMapFs(),
userCreator: &stubUserCreator{},
passwdContents: "user:x:1000:1000:user:/home/user:/bin/bash\n",
readonly: true,
expectErr: true,
wantErr: true,
},
}
@ -92,15 +92,15 @@ func TestDeploySSHAuthorizedKey(t *testing.T) {
}
err := sshAccess.DeploySSHAuthorizedKey(context.Background(), authorizedKey)
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
if tc.expectFile {
if tc.wantFile {
fileContents, err := afero.ReadFile(tc.fs, "/home/user/.ssh/authorized_keys.d/debugd")
assert.NoError(err)
assert.Equal(tc.expectedFileContents, string(fileContents))
assert.Equal(tc.wantFileContents, string(fileContents))
} else {
exists, err := afero.Exists(tc.fs, "/home/user/.ssh/authorized_keys.d/debugd")
assert.NoError(err)

View File

@ -16,8 +16,8 @@ func TestDiscoverDebugIPs(t *testing.T) {
testCases := map[string]struct {
meta stubMetadata
expectedIPs []string
expectErr bool
wantIPs []string
wantErr bool
}{
"disovery works": {
meta: stubMetadata{
@ -33,7 +33,7 @@ func TestDiscoverDebugIPs(t *testing.T) {
},
},
},
expectedIPs: []string{
wantIPs: []string{
"192.0.2.1", "192.0.2.2",
},
},
@ -41,7 +41,7 @@ func TestDiscoverDebugIPs(t *testing.T) {
meta: stubMetadata{
listErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -55,12 +55,12 @@ func TestDiscoverDebugIPs(t *testing.T) {
}
ips, err := fetcher.DiscoverDebugdIPs(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedIPs, ips)
assert.ElementsMatch(tc.wantIPs, ips)
})
}
}
@ -70,8 +70,8 @@ func TestFetchSSHKeys(t *testing.T) {
testCases := map[string]struct {
meta stubMetadata
expectedKeys []ssh.SSHKey
expectErr bool
wantKeys []ssh.SSHKey
wantErr bool
}{
"fetch works": {
meta: stubMetadata{
@ -81,7 +81,7 @@ func TestFetchSSHKeys(t *testing.T) {
SSHKeys: map[string][]string{"bob": {"ssh-rsa bobskey"}},
},
},
expectedKeys: []ssh.SSHKey{
wantKeys: []ssh.SSHKey{
{
Username: "bob",
KeyValue: "ssh-rsa bobskey",
@ -92,7 +92,7 @@ func TestFetchSSHKeys(t *testing.T) {
meta: stubMetadata{
selfErr: err,
},
expectErr: true,
wantErr: true,
},
}
@ -106,12 +106,12 @@ func TestFetchSSHKeys(t *testing.T) {
}
keys, err := fetcher.FetchSSHKeys(context.Background())
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.ElementsMatch(tc.expectedKeys, keys)
assert.ElementsMatch(tc.wantKeys, keys)
})
}
}

View File

@ -17,8 +17,8 @@ func TestSchedulerStart(t *testing.T) {
ssh stubSSHDeployer
downloader stubDownloader
timeout time.Duration
expectedSSHKeys []ssh.SSHKey
expectedDebugdDownloads []string
wantSSHKeys []ssh.SSHKey
wantDebugdDownloads []string
}{
"scheduler works and calls fetcher functions at least once": {},
"ssh keys are fetched": {
@ -30,7 +30,7 @@ func TestSchedulerStart(t *testing.T) {
},
},
},
expectedSSHKeys: []ssh.SSHKey{
wantSSHKeys: []ssh.SSHKey{
{
Username: "test",
KeyValue: "testkey",
@ -45,14 +45,14 @@ func TestSchedulerStart(t *testing.T) {
err: errors.New("download fails"),
},
expectedDebugdDownloads: []string{"192.0.2.1", "192.0.2.2"},
wantDebugdDownloads: []string{"192.0.2.1", "192.0.2.2"},
},
"if download is successful, second download is not attempted": {
fetcher: stubFetcher{
ips: []string{"192.0.2.1", "192.0.2.2"},
},
expectedDebugdDownloads: []string{"192.0.2.1"},
wantDebugdDownloads: []string{"192.0.2.1"},
},
"endpoint discovery can fail": {
fetcher: stubFetcher{
@ -82,8 +82,8 @@ func TestSchedulerStart(t *testing.T) {
go scheduler.Start(ctx, wg)
wg.Wait()
assert.Equal(tc.expectedSSHKeys, tc.ssh.sshKeys)
assert.Equal(tc.expectedDebugdDownloads, tc.downloader.ips)
assert.Equal(tc.wantSSHKeys, tc.ssh.sshKeys)
assert.Equal(tc.wantDebugdDownloads, tc.downloader.ips)
assert.Greater(tc.fetcher.discoverCalls, 0)
assert.Greater(tc.fetcher.fetchSSHKeysCalls, 0)
})

View File

@ -26,9 +26,9 @@ func TestUploadAuthorizedKeys(t *testing.T) {
ssh stubSSHDeployer
serviceManager stubServiceManager
request *pb.UploadAuthorizedKeysRequest
expectErr bool
expectedResponseStatus pb.UploadAuthorizedKeysStatus
expectedKeys []ssh.SSHKey
wantErr bool
wantResponseStatus pb.UploadAuthorizedKeysStatus
wantKeys []ssh.SSHKey
}{
"upload authorized keys works": {
request: &pb.UploadAuthorizedKeysRequest{
@ -39,8 +39,8 @@ func TestUploadAuthorizedKeys(t *testing.T) {
},
},
},
expectedResponseStatus: pb.UploadAuthorizedKeysStatus_UPLOAD_AUTHORIZED_KEYS_SUCCESS,
expectedKeys: []ssh.SSHKey{
wantResponseStatus: pb.UploadAuthorizedKeysStatus_UPLOAD_AUTHORIZED_KEYS_SUCCESS,
wantKeys: []ssh.SSHKey{
{
Username: "testuser",
KeyValue: "teskey",
@ -57,8 +57,8 @@ func TestUploadAuthorizedKeys(t *testing.T) {
},
},
ssh: stubSSHDeployer{deployErr: errors.New("ssh key deployment error")},
expectedResponseStatus: pb.UploadAuthorizedKeysStatus_UPLOAD_AUTHORIZED_KEYS_FAILURE,
expectedKeys: []ssh.SSHKey{
wantResponseStatus: pb.UploadAuthorizedKeysStatus_UPLOAD_AUTHORIZED_KEYS_FAILURE,
wantKeys: []ssh.SSHKey{
{
Username: "testuser",
KeyValue: "teskey",
@ -86,13 +86,13 @@ func TestUploadAuthorizedKeys(t *testing.T) {
grpcServ.GracefulStop()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedResponseStatus, resp.Status)
assert.ElementsMatch(tc.ssh.sshKeys, tc.expectedKeys)
assert.Equal(tc.wantResponseStatus, resp.Status)
assert.ElementsMatch(tc.ssh.sshKeys, tc.wantKeys)
})
}
}
@ -105,27 +105,27 @@ func TestUploadCoordinator(t *testing.T) {
serviceManager stubServiceManager
streamer fakeStreamer
uploadChunks [][]byte
expectErr bool
expectedResponseStatus pb.UploadCoordinatorStatus
expectFile bool
expectedChunks [][]byte
wantErr bool
wantResponseStatus pb.UploadCoordinatorStatus
wantFile bool
wantChunks [][]byte
}{
"upload works": {
uploadChunks: [][]byte{
[]byte("test"),
},
expectFile: true,
expectedChunks: [][]byte{
wantFile: true,
wantChunks: [][]byte{
[]byte("test"),
},
expectedResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_SUCCESS,
wantResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_SUCCESS,
},
"recv fails": {
streamer: fakeStreamer{
writeStreamErr: errors.New("recv error"),
},
expectedResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_UPLOAD_FAILED,
expectErr: true,
wantResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_UPLOAD_FAILED,
wantErr: true,
},
"starting coordinator fails": {
uploadChunks: [][]byte{
@ -134,11 +134,11 @@ func TestUploadCoordinator(t *testing.T) {
serviceManager: stubServiceManager{
systemdActionErr: errors.New("starting coordinator error"),
},
expectFile: true,
expectedChunks: [][]byte{
wantFile: true,
wantChunks: [][]byte{
[]byte("test"),
},
expectedResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_START_FAILED,
wantResponseStatus: pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_START_FAILED,
},
}
@ -164,14 +164,14 @@ func TestUploadCoordinator(t *testing.T) {
grpcServ.GracefulStop()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedResponseStatus, resp.Status)
if tc.expectFile {
assert.Equal(tc.expectedChunks, tc.streamer.writeStreamChunks)
assert.Equal(tc.wantResponseStatus, resp.Status)
if tc.wantFile {
assert.Equal(tc.wantChunks, tc.streamer.writeStreamChunks)
assert.Equal("/opt/coordinator", tc.streamer.writeStreamFilename)
} else {
assert.Empty(tc.streamer.writeStreamChunks)
@ -188,8 +188,8 @@ func TestDownloadCoordinator(t *testing.T) {
serviceManager stubServiceManager
request *pb.DownloadCoordinatorRequest
streamer fakeStreamer
expectErr bool
expectedChunks [][]byte
wantErr bool
wantChunks [][]byte
}{
"download works": {
request: &pb.DownloadCoordinatorRequest{},
@ -198,8 +198,8 @@ func TestDownloadCoordinator(t *testing.T) {
[]byte("test"),
},
},
expectErr: false,
expectedChunks: [][]byte{
wantErr: false,
wantChunks: [][]byte{
[]byte("test"),
},
},
@ -208,7 +208,7 @@ func TestDownloadCoordinator(t *testing.T) {
streamer: fakeStreamer{
readStreamErr: errors.New("read coordinator fails"),
},
expectErr: true,
wantErr: true,
},
}
@ -232,12 +232,12 @@ func TestDownloadCoordinator(t *testing.T) {
chunks, err := fakeRead(stream)
grpcServ.GracefulStop()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
assert.Equal(tc.expectedChunks, chunks)
assert.Equal(tc.wantChunks, chunks)
assert.Equal("/opt/coordinator", tc.streamer.readStreamFilename)
})
}
@ -249,9 +249,9 @@ func TestUploadSystemServiceUnits(t *testing.T) {
ssh stubSSHDeployer
serviceManager stubServiceManager
request *pb.UploadSystemdServiceUnitsRequest
expectErr bool
expectedResponseStatus pb.UploadSystemdServiceUnitsStatus
expectedUnitFiles []deploy.SystemdUnit
wantErr bool
wantResponseStatus pb.UploadSystemdServiceUnitsStatus
wantUnitFiles []deploy.SystemdUnit
}{
"upload systemd service units": {
request: &pb.UploadSystemdServiceUnitsRequest{
@ -262,8 +262,8 @@ func TestUploadSystemServiceUnits(t *testing.T) {
},
},
},
expectedResponseStatus: pb.UploadSystemdServiceUnitsStatus_UPLOAD_SYSTEMD_SERVICE_UNITS_SUCCESS,
expectedUnitFiles: []deploy.SystemdUnit{
wantResponseStatus: pb.UploadSystemdServiceUnitsStatus_UPLOAD_SYSTEMD_SERVICE_UNITS_SUCCESS,
wantUnitFiles: []deploy.SystemdUnit{
{
Name: "test.service",
Contents: "testcontents",
@ -282,8 +282,8 @@ func TestUploadSystemServiceUnits(t *testing.T) {
serviceManager: stubServiceManager{
writeSystemdUnitFileErr: errors.New("write error"),
},
expectedResponseStatus: pb.UploadSystemdServiceUnitsStatus_UPLOAD_SYSTEMD_SERVICE_UNITS_FAILURE,
expectedUnitFiles: []deploy.SystemdUnit{
wantResponseStatus: pb.UploadSystemdServiceUnitsStatus_UPLOAD_SYSTEMD_SERVICE_UNITS_FAILURE,
wantUnitFiles: []deploy.SystemdUnit{
{
Name: "test.service",
Contents: "testcontents",
@ -310,14 +310,14 @@ func TestUploadSystemServiceUnits(t *testing.T) {
grpcServ.GracefulStop()
if tc.expectErr {
if tc.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.NotNil(resp.Status)
assert.Equal(tc.expectedResponseStatus, resp.Status)
assert.ElementsMatch(tc.expectedUnitFiles, tc.serviceManager.unitFiles)
assert.Equal(tc.wantResponseStatus, resp.Status)
assert.ElementsMatch(tc.wantUnitFiles, tc.serviceManager.unitFiles)
})
}
}

View File

@ -308,7 +308,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
policyProducer KeyPolicyProducer
importKey []byte
cleanupRequired bool
errExpected bool
wantErr bool
}{
"create new kek successful": {
client: &stubAWSClient{createKeyID: "key-id"},
@ -317,13 +317,13 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
"CreateKeyPolicy fails on existing": {
client: &stubAWSClient{},
policyProducer: &stubKeyPolicyProducer{createKeyPolicyErr: someErr},
errExpected: true,
wantErr: true,
},
"CreateKeyPolicy fails on new": {
client: &stubAWSClient{describeKeyErr: &types.NotFoundException{}},
policyProducer: &stubKeyPolicyProducer{createKeyPolicyErr: someErr},
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
"PutKeyPolicy fails on new": {
client: &stubAWSClient{
@ -333,7 +333,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
},
policyProducer: &stubKeyPolicyProducer{},
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
"CreateAlias fails on new": {
client: &stubAWSClient{
@ -343,17 +343,17 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
},
policyProducer: &stubKeyPolicyProducer{},
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
"CreateKey fails on new": {
client: &stubAWSClient{describeKeyErr: &types.NotFoundException{}, createKeyErr: someErr},
policyProducer: &stubKeyPolicyProducer{},
errExpected: true,
wantErr: true,
},
"DescribeKey fails": {
client: &stubAWSClient{describeKeyErr: someErr},
policyProducer: &stubKeyPolicyProducer{},
errExpected: true,
wantErr: true,
},
"DescribeKey fails with not found error": {
client: &stubAWSClient{describeKeyErr: &types.NotFoundException{}},
@ -373,7 +373,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
policyProducer: &stubKeyPolicyProducer{},
importKey: importKey,
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
"ImportKeyMaterial fails on new": {
client: &stubAWSClient{
@ -384,19 +384,19 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
policyProducer: &stubKeyPolicyProducer{},
importKey: importKey,
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
"GetParametersForImport fails on existing": {
client: &stubAWSClient{getParametersForImportErr: someErr},
policyProducer: &stubKeyPolicyProducer{},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"ImportKeyMaterial fails on existing": {
client: &stubAWSClient{importKeyMaterialErr: someErr},
policyProducer: &stubKeyPolicyProducer{},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"errors during cleanup don't stop execution": {
client: &stubAWSClient{
@ -406,7 +406,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
},
policyProducer: &stubKeyPolicyProducer{createKeyPolicyErr: someErr},
cleanupRequired: true,
errExpected: true,
wantErr: true,
},
}
@ -421,7 +421,7 @@ Y+t5OxL3kL15VzY1Ob0d5cMCAwEAAQ==
}
err := client.CreateKEK(context.Background(), "test-key", tc.importKey)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
if tc.cleanupRequired {
assert.True(tc.client.cleanUpCalled, "failed to clean up")

View File

@ -38,7 +38,7 @@ func TestKMSCreateKEK(t *testing.T) {
testCases := map[string]struct {
client *stubAzureClient
importKey []byte
errExpected bool
wantErr bool
}{
"create new kek successful": {
client: &stubAzureClient{},
@ -49,12 +49,12 @@ func TestKMSCreateKEK(t *testing.T) {
},
"SetSecret fails on new": {
client: &stubAzureClient{setSecretErr: someErr},
errExpected: true,
wantErr: true,
},
"SetSecret fails on import": {
client: &stubAzureClient{setSecretErr: someErr},
importKey: importKey,
errExpected: true,
wantErr: true,
},
}
@ -68,7 +68,7 @@ func TestKMSCreateKEK(t *testing.T) {
}
err := client.CreateKEK(context.Background(), "test-key", tc.importKey)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -85,7 +85,7 @@ func TestKMSGetDEK(t *testing.T) {
testCases := map[string]struct {
client kmsClientAPI
storage kms.Storage
errExpected bool
wantErr bool
}{
"successful for new key": {
client: &stubAzureClient{secret: wrapKey},
@ -99,7 +99,7 @@ func TestKMSGetDEK(t *testing.T) {
"Get from storage fails": {
client: &stubAzureClient{},
storage: &stubStorage{getErr: someErr},
errExpected: true,
wantErr: true,
},
"Put to storage fails": {
client: &stubAzureClient{secret: wrapKey},
@ -107,27 +107,27 @@ func TestKMSGetDEK(t *testing.T) {
getErr: storage.ErrDEKUnset,
putErr: someErr,
},
errExpected: true,
wantErr: true,
},
"GetSecret fails": {
client: &stubAzureClient{getSecretErr: someErr},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
"GetSecret fails with unknown kek": {
client: &stubAzureClient{getSecretErr: errors.New("SecretNotFound")},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
"key wrapping fails": {
client: &stubAzureClient{secret: []byte{0x1}},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
"key unwrapping fails": {
client: &stubAzureClient{secret: wrapKey},
storage: &stubStorage{key: []byte{0x1}},
errExpected: true,
wantErr: true,
},
}
@ -142,7 +142,7 @@ func TestKMSGetDEK(t *testing.T) {
}
dek, err := client.GetDEK(context.Background(), "test-key", "volume-01", 32)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.Len(dek, 32)

View File

@ -90,14 +90,14 @@ func TestHSMCreateKEK(t *testing.T) {
testCases := map[string]struct {
client *stubHSMClient
importKey []byte
errExpected bool
wantErr bool
}{
"create new kek successful": {
client: &stubHSMClient{},
},
"CreateOCTKey fails": {
client: &stubHSMClient{createOCTKeyErr: someErr},
errExpected: true,
wantErr: true,
},
"import key successful": {
client: &stubHSMClient{},
@ -106,7 +106,7 @@ func TestHSMCreateKEK(t *testing.T) {
"ImportKey fails": {
client: &stubHSMClient{importKeyErr: someErr},
importKey: importKey,
errExpected: true,
wantErr: true,
},
}
@ -120,7 +120,7 @@ func TestHSMCreateKEK(t *testing.T) {
}
err := client.CreateKEK(context.Background(), "test-key", tc.importKey)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -138,7 +138,7 @@ func TestHSMGetNewDEK(t *testing.T) {
client hsmClientAPI
storage kms.Storage
cryptoClient *stubCryptoClient
errExpected bool
wantErr bool
}{
"successful": {
client: &stubHSMClient{keyVersion: keyVersion},
@ -149,7 +149,7 @@ func TestHSMGetNewDEK(t *testing.T) {
client: &stubHSMClient{keyVersion: keyVersion},
cryptoClient: &stubCryptoClient{},
storage: &stubStorage{getErr: someErr},
errExpected: true,
wantErr: true,
},
"Put to storage fails": {
client: &stubHSMClient{keyVersion: keyVersion},
@ -158,25 +158,25 @@ func TestHSMGetNewDEK(t *testing.T) {
getErr: storage.ErrDEKUnset,
putErr: someErr,
},
errExpected: true,
wantErr: true,
},
"GetKey fails": {
client: &stubHSMClient{getKeyErr: someErr},
cryptoClient: &stubCryptoClient{},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
"WrapKey fails": {
client: &stubHSMClient{keyVersion: keyVersion},
cryptoClient: &stubCryptoClient{wrapKeyErr: someErr},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
"creating crypto client fails": {
client: &stubHSMClient{keyVersion: keyVersion},
cryptoClient: &stubCryptoClient{createErr: someErr},
storage: storage.NewMemMapStorage(),
errExpected: true,
wantErr: true,
},
}
@ -192,7 +192,7 @@ func TestHSMGetNewDEK(t *testing.T) {
}
dek, err := client.GetDEK(context.Background(), "test-key", "volume-01", 32)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.Len(dek, 32)
@ -210,7 +210,7 @@ func TestHSMGetExistingDEK(t *testing.T) {
testCases := map[string]struct {
client hsmClientAPI
cryptoClient *stubCryptoClient
errExpected bool
wantErr bool
}{
"successful": {
client: &stubHSMClient{keyVersion: keyVersion},
@ -222,17 +222,17 @@ func TestHSMGetExistingDEK(t *testing.T) {
getKeyErr: someErr,
},
cryptoClient: &stubCryptoClient{},
errExpected: true,
wantErr: true,
},
"UnwrapKey fails": {
client: &stubHSMClient{keyVersion: keyVersion},
cryptoClient: &stubCryptoClient{unwrapKeyErr: someErr},
errExpected: true,
wantErr: true,
},
"creating crypto client fails": {
client: &stubHSMClient{keyVersion: keyVersion},
cryptoClient: &stubCryptoClient{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -253,7 +253,7 @@ func TestHSMGetExistingDEK(t *testing.T) {
}
dek, err := client.GetDEK(context.Background(), "test-key", keyID, len(testKey))
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.Len(dek, len(testKey))
@ -267,22 +267,22 @@ func TestGetKeyVersion(t *testing.T) {
testVersion := "test-key-version"
testCases := map[string]struct {
client *stubHSMClient
errExpected bool
wantErr bool
}{
"valid key version": {
client: &stubHSMClient{keyVersion: fmt.Sprintf("https://test.managedhsm.azure.net/keys/test-key/%s", testVersion)},
},
"GetKey fails": {
client: &stubHSMClient{getKeyErr: errors.New("error")},
errExpected: true,
wantErr: true,
},
"key ID is not an URL": {
client: &stubHSMClient{keyVersion: string([]byte{0x0, 0x1, 0x2})},
errExpected: true,
wantErr: true,
},
"invalid key ID URL": {
client: &stubHSMClient{keyVersion: "https://test.managedhsm.azure.net/keys/test-key/test-key-version/another-version/and-another-one"},
errExpected: true,
wantErr: true,
},
}
@ -293,7 +293,7 @@ func TestGetKeyVersion(t *testing.T) {
client := HSMClient{client: tc.client}
keyVersion, err := client.getKeyVersion(context.Background(), "test")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -112,7 +112,7 @@ func TestCreateKEK(t *testing.T) {
testCases := map[string]struct {
client *stubGCPClient
importKey []byte
errExpected bool
wantErr bool
}{
"create new kek successful": {
client: &stubGCPClient{},
@ -130,7 +130,7 @@ func TestCreateKEK(t *testing.T) {
},
"CreateCryptoKey fails": {
client: &stubGCPClient{createCryptoKeyErr: someErr},
errExpected: true,
wantErr: true,
},
"CreatCryptoKey fails on import": {
client: &stubGCPClient{
@ -143,12 +143,12 @@ func TestCreateKEK(t *testing.T) {
},
},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"CreateImportJob fails": {
client: &stubGCPClient{createImportJobErr: someErr},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"ImportCryptoKeyVersion fails": {
client: &stubGCPClient{
@ -161,7 +161,7 @@ func TestCreateKEK(t *testing.T) {
importCryptoKeyVersionErr: someErr,
},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"UpdateCryptoKeyPrimaryVersion fails": {
client: &stubGCPClient{
@ -174,12 +174,12 @@ func TestCreateKEK(t *testing.T) {
updateCryptoKeyPrimaryVersionErr: someErr,
},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"GetImportJob fails during waitBackoff": {
client: &stubGCPClient{getImportJobErr: someErr},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"GetImportJob returns no key": {
client: &stubGCPClient{
@ -188,7 +188,7 @@ func TestCreateKEK(t *testing.T) {
},
},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"waitBackoff times out": {
client: &stubGCPClient{
@ -200,11 +200,11 @@ func TestCreateKEK(t *testing.T) {
},
},
importKey: importKey,
errExpected: true,
wantErr: true,
},
"creating client fails": {
client: &stubGCPClient{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -222,7 +222,7 @@ func TestCreateKEK(t *testing.T) {
}
err := client.CreateKEK(context.Background(), "test-key", tc.importKey)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -243,7 +243,7 @@ func TestGetDEK(t *testing.T) {
testCases := map[string]struct {
client *stubGCPClient
storage kmsInterface.Storage
errExpected bool
wantErr bool
}{
"GetDEK successful for new key": {
client: &stubGCPClient{},
@ -256,17 +256,17 @@ func TestGetDEK(t *testing.T) {
"Get from storage fails": {
client: &stubGCPClient{},
storage: &stubStorage{getErr: someErr},
errExpected: true,
wantErr: true,
},
"Encrypt fails": {
client: &stubGCPClient{encryptErr: someErr},
storage: &stubStorage{getErr: storage.ErrDEKUnset},
errExpected: true,
wantErr: true,
},
"Encrypt fails with notfound error": {
client: &stubGCPClient{encryptErr: status.Error(codes.NotFound, "error")},
storage: &stubStorage{getErr: storage.ErrDEKUnset},
errExpected: true,
wantErr: true,
},
"Put to storage fails": {
client: &stubGCPClient{},
@ -274,22 +274,22 @@ func TestGetDEK(t *testing.T) {
getErr: storage.ErrDEKUnset,
putErr: someErr,
},
errExpected: true,
wantErr: true,
},
"Decrypt fails": {
client: &stubGCPClient{decryptErr: someErr},
storage: &stubStorage{key: testKey},
errExpected: true,
wantErr: true,
},
"Decrypt fails with notfound error": {
client: &stubGCPClient{decryptErr: status.Error(codes.NotFound, "error")},
storage: &stubStorage{key: testKey},
errExpected: true,
wantErr: true,
},
"creating client fails": {
client: &stubGCPClient{createErr: someErr},
storage: &stubStorage{getErr: storage.ErrDEKUnset},
errExpected: true,
wantErr: true,
},
}
@ -308,7 +308,7 @@ func TestGetDEK(t *testing.T) {
}
dek, err := client.GetDEK(context.Background(), "test-key", "volume-01", 32)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -322,18 +322,18 @@ func TestConnection(t *testing.T) {
someErr := errors.New("error")
testCases := map[string]struct {
client *stubGCPClient
errExpected bool
wantErr bool
}{
"success": {
client: &stubGCPClient{},
},
"newClient fails": {
client: &stubGCPClient{createErr: someErr},
errExpected: true,
wantErr: true,
},
"GetKeyRing fails": {
client: &stubGCPClient{getKeyRingErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -351,7 +351,7 @@ func TestConnection(t *testing.T) {
}
err := client.testConnection(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -11,10 +11,10 @@ func TestWrapKeyAES(t *testing.T) {
testKEK := []byte{0xD6, 0x8A, 0xED, 0xF5, 0xDB, 0x89, 0x95, 0x66, 0xA9, 0xFF, 0xD9, 0x31, 0x27, 0x4E, 0x30, 0x2D, 0x21, 0xA9, 0x46, 0x21, 0x16, 0x6C, 0x16, 0x17, 0xD1, 0x96, 0x5D, 0xB2, 0xE9, 0x0E, 0x96, 0xD1}
testDEK := []byte{0xCB, 0x6E, 0x4B, 0x05, 0x92, 0x6C, 0xE7, 0x38, 0x0C, 0x46, 0x47, 0x06, 0x83, 0xDE, 0x20, 0xFB, 0x73, 0xAA, 0x87, 0xC1, 0x97, 0xE3, 0x7C, 0xE4, 0xF4, 0x0B, 0x96, 0x8D, 0xC5, 0x88, 0xB6, 0xDF}
expectedWrap := []byte{0x14, 0x48, 0xC4, 0xEA, 0x4B, 0x4B, 0xCA, 0xE4, 0x5A, 0xD4, 0xCC, 0xE3, 0xF7, 0xDD, 0xD5, 0x78, 0xA5, 0xA9, 0xEF, 0x9A, 0x93, 0x36, 0x09, 0xD6, 0x23, 0x01, 0xF5, 0x5F, 0xE1, 0x20, 0xDD, 0xFC, 0xBC, 0xF3, 0xA9, 0x67, 0x8B, 0x89, 0x54, 0x96}
wantWrap := []byte{0x14, 0x48, 0xC4, 0xEA, 0x4B, 0x4B, 0xCA, 0xE4, 0x5A, 0xD4, 0xCC, 0xE3, 0xF7, 0xDD, 0xD5, 0x78, 0xA5, 0xA9, 0xEF, 0x9A, 0x93, 0x36, 0x09, 0xD6, 0x23, 0x01, 0xF5, 0x5F, 0xE1, 0x20, 0xDD, 0xFC, 0xBC, 0xF3, 0xA9, 0x67, 0x8B, 0x89, 0x54, 0x96}
res, err := WrapAES(testDEK, testKEK)
assert.NoError(err)
assert.Equal(expectedWrap, res)
assert.Equal(wantWrap, res)
// Decrypt the Key
res, err = UnwrapAES(res, testKEK)

View File

@ -45,18 +45,18 @@ func TestAWSS3Get(t *testing.T) {
testCases := map[string]struct {
client *stubAWSS3StorageClient
unsetError bool
errExpected bool
wantErr bool
}{
"Get successful": {
client: &stubAWSS3StorageClient{getObjectOutputData: []byte("test-data")},
},
"GetObject fails": {
client: &stubAWSS3StorageClient{getObjectErr: errors.New("error")},
errExpected: true,
wantErr: true,
},
"GetObject fails with NoSuchKey": {
client: &stubAWSS3StorageClient{getObjectErr: &types.NoSuchKey{}},
errExpected: true,
wantErr: true,
unsetError: true,
},
}
@ -70,7 +70,7 @@ func TestAWSS3Get(t *testing.T) {
}
out, err := store.Get(context.Background(), "test-key")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
if tc.unsetError {
@ -90,14 +90,14 @@ func TestAWSS3Get(t *testing.T) {
func TestAWSS3Put(t *testing.T) {
testCases := map[string]struct {
client *stubAWSS3StorageClient
errExpected bool
wantErr bool
}{
"Put successful": {
client: &stubAWSS3StorageClient{},
},
"PutObject fails": {
client: &stubAWSS3StorageClient{putObjectErr: errors.New("error")},
errExpected: true,
wantErr: true,
},
}
@ -112,7 +112,7 @@ func TestAWSS3Put(t *testing.T) {
testData := []byte{0x1, 0x2, 0x3}
err := store.Put(context.Background(), "test-key", testData)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -125,22 +125,22 @@ func TestAWSS3Put(t *testing.T) {
func TestAWSS3CreateBucket(t *testing.T) {
testCases := map[string]struct {
client *stubAWSS3StorageClient
errExpected bool
wantErr bool
}{
"CreateBucket successful": {
client: &stubAWSS3StorageClient{},
},
"CreateBucket fails": {
client: &stubAWSS3StorageClient{createBucketErr: errors.New("error")},
errExpected: true,
wantErr: true,
},
"CreateBucket fails with BucketAlreadyExists": {
client: &stubAWSS3StorageClient{createBucketErr: &types.BucketAlreadyExists{}},
errExpected: false,
wantErr: false,
},
"CreateBucket fails with BucketAlreadyOwnedByYou": {
client: &stubAWSS3StorageClient{createBucketErr: &types.BucketAlreadyOwnedByYou{}},
errExpected: false,
wantErr: false,
},
}
@ -153,7 +153,7 @@ func TestAWSS3CreateBucket(t *testing.T) {
}
err := store.createBucket(context.Background(), "test-bucket", "test-region")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -61,7 +61,7 @@ func TestAzureGet(t *testing.T) {
testCases := map[string]struct {
client stubAzureContainerAPI
unsetError bool
errExpected bool
wantErr bool
}{
"success": {
client: stubAzureContainerAPI{
@ -70,13 +70,13 @@ func TestAzureGet(t *testing.T) {
},
"creating client fails": {
client: stubAzureContainerAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"DownloadBlobToBuffer fails": {
client: stubAzureContainerAPI{
blockBlobAPI: stubAzureBlockBlobAPI{downloadBlobToWriterAtErr: someErr},
},
errExpected: true,
wantErr: true,
},
"BlobNotFound error": {
client: stubAzureContainerAPI{
@ -87,7 +87,7 @@ func TestAzureGet(t *testing.T) {
},
},
unsetError: true,
errExpected: true,
wantErr: true,
},
}
@ -103,7 +103,7 @@ func TestAzureGet(t *testing.T) {
}
out, err := client.Get(context.Background(), "test-key")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
if tc.unsetError {
@ -125,20 +125,20 @@ func TestAzurePut(t *testing.T) {
testCases := map[string]struct {
client stubAzureContainerAPI
errExpected bool
wantErr bool
}{
"success": {
client: stubAzureContainerAPI{},
},
"creating client fails": {
client: stubAzureContainerAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"Upload fails": {
client: stubAzureContainerAPI{
blockBlobAPI: stubAzureBlockBlobAPI{uploadErr: someErr},
},
errExpected: true,
wantErr: true,
},
}
@ -157,7 +157,7 @@ func TestAzurePut(t *testing.T) {
}
err := client.Put(context.Background(), "test-key", testData)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -171,7 +171,7 @@ func TestCreateContainerOrContinue(t *testing.T) {
someErr := errors.New("error")
testCases := map[string]struct {
client stubAzureContainerAPI
errExpected bool
wantErr bool
}{
"success": {
client: stubAzureContainerAPI{},
@ -181,11 +181,11 @@ func TestCreateContainerOrContinue(t *testing.T) {
},
"creating client fails": {
client: stubAzureContainerAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"Create fails": {
client: stubAzureContainerAPI{createErr: someErr},
errExpected: true,
wantErr: true,
},
}
@ -202,7 +202,7 @@ func TestCreateContainerOrContinue(t *testing.T) {
}
err := client.createContainerOrContinue(context.Background())
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -68,23 +68,23 @@ func TestGCPGet(t *testing.T) {
testCases := map[string]struct {
client *stubGCPStorageAPI
unsetError bool
errExpected bool
wantErr bool
}{
"success": {
client: &stubGCPStorageAPI{newReaderOutput: []byte("test-data")},
},
"creating client fails": {
client: &stubGCPStorageAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"NewReader fails": {
client: &stubGCPStorageAPI{newReaderErr: someErr},
errExpected: true,
wantErr: true,
},
"ErrObjectNotExist error": {
client: &stubGCPStorageAPI{newReaderErr: storage.ErrObjectNotExist},
unsetError: true,
errExpected: true,
wantErr: true,
},
}
@ -99,7 +99,7 @@ func TestGCPGet(t *testing.T) {
}
out, err := client.Get(context.Background(), "test-key")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
if tc.unsetError {
@ -121,7 +121,7 @@ func TestGCPPut(t *testing.T) {
testCases := map[string]struct {
client *stubGCPStorageAPI
unsetError bool
errExpected bool
wantErr bool
}{
"success": {
client: &stubGCPStorageAPI{
@ -132,7 +132,7 @@ func TestGCPPut(t *testing.T) {
},
"creating client fails": {
client: &stubGCPStorageAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"NewWriter fails": {
client: &stubGCPStorageAPI{
@ -141,7 +141,7 @@ func TestGCPPut(t *testing.T) {
writeErr: someErr,
},
},
errExpected: true,
wantErr: true,
},
}
@ -157,7 +157,7 @@ func TestGCPPut(t *testing.T) {
testData := []byte{0x1, 0x2, 0x3}
err := client.Put(context.Background(), "test-key", testData)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -172,7 +172,7 @@ func TestGCPCreateContainerOrContinue(t *testing.T) {
testCases := map[string]struct {
client *stubGCPStorageAPI
createNewBucket bool
errExpected bool
wantErr bool
}{
"success": {
client: &stubGCPStorageAPI{},
@ -183,18 +183,18 @@ func TestGCPCreateContainerOrContinue(t *testing.T) {
},
"creating client fails": {
client: &stubGCPStorageAPI{newClientErr: someErr},
errExpected: true,
wantErr: true,
},
"Attrs fails": {
client: &stubGCPStorageAPI{attrsErr: someErr},
errExpected: true,
wantErr: true,
},
"CreateBucket fails": {
client: &stubGCPStorageAPI{
attrsErr: storage.ErrBucketNotExist,
createBucketErr: someErr,
},
errExpected: true,
wantErr: true,
},
}
@ -209,7 +209,7 @@ func TestGCPCreateContainerOrContinue(t *testing.T) {
}
err := client.createContainerOrContinue(context.Background(), nil)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -61,23 +61,23 @@ func (c *stubCryptDevice) Wipe(devicePath string, pattern int, offset, length ui
func TestCloseCryptDevice(t *testing.T) {
testCases := map[string]struct {
mapper *stubCryptDevice
errExpected bool
wantErr bool
}{
"success": {
mapper: &stubCryptDevice{},
errExpected: false,
wantErr: false,
},
"error on Init": {
mapper: &stubCryptDevice{
initErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
"error on Deactivate": {
mapper: &stubCryptDevice{
deactivateErr: errors.New("error"),
},
errExpected: true,
wantErr: true,
},
}
@ -86,7 +86,7 @@ func TestCloseCryptDevice(t *testing.T) {
assert := assert.New(t)
err := closeCryptDevice(tc.mapper, "/dev/some-device", "volume0", "test")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -109,7 +109,7 @@ func TestOpenCryptDevice(t *testing.T) {
integrity bool
mapper *stubCryptDevice
diskInfo func(disk string) (string, error)
errExpected bool
wantErr bool
}{
"success with Load": {
source: "/dev/some-device",
@ -117,7 +117,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: false,
wantErr: false,
},
"success with error on Load": {
source: "/dev/some-device",
@ -125,7 +125,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{loadErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: false,
wantErr: false,
},
"success with integrity": {
source: "/dev/some-device",
@ -134,7 +134,7 @@ func TestOpenCryptDevice(t *testing.T) {
integrity: true,
mapper: &stubCryptDevice{loadErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: false,
wantErr: false,
},
"incorrect key size": {
source: "/dev/some-device",
@ -142,7 +142,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: "short",
mapper: &stubCryptDevice{},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error on Init": {
source: "/dev/some-device",
@ -150,7 +150,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{initErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error on Format": {
source: "/dev/some-device",
@ -158,7 +158,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{loadErr: someErr, formatErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error on Activate": {
source: "/dev/some-device",
@ -166,7 +166,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{activateErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error on diskInfo": {
source: "/dev/some-device",
@ -174,7 +174,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{loadErr: someErr},
diskInfo: func(disk string) (string, error) { return "", someErr },
errExpected: true,
wantErr: true,
},
"disk is already formatted": {
source: "/dev/some-device",
@ -182,7 +182,7 @@ func TestOpenCryptDevice(t *testing.T) {
dek: string(testDEK),
mapper: &stubCryptDevice{loadErr: someErr},
diskInfo: func(disk string) (string, error) { return "ext4", nil },
errExpected: true,
wantErr: true,
},
"error with integrity on wipe": {
source: "/dev/some-device",
@ -191,7 +191,7 @@ func TestOpenCryptDevice(t *testing.T) {
integrity: true,
mapper: &stubCryptDevice{loadErr: someErr, wipeErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error with integrity on activate": {
source: "/dev/some-device",
@ -200,7 +200,7 @@ func TestOpenCryptDevice(t *testing.T) {
integrity: true,
mapper: &stubCryptDevice{loadErr: someErr, activateErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
"error with integrity on deactivate": {
source: "/dev/some-device",
@ -209,7 +209,7 @@ func TestOpenCryptDevice(t *testing.T) {
integrity: true,
mapper: &stubCryptDevice{loadErr: someErr, deactivateErr: someErr},
diskInfo: func(disk string) (string, error) { return "", nil },
errExpected: true,
wantErr: true,
},
}
@ -218,7 +218,7 @@ func TestOpenCryptDevice(t *testing.T) {
assert := assert.New(t)
out, err := openCryptDevice(tc.mapper, tc.source, tc.volumeID, tc.dek, tc.integrity, tc.diskInfo)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -23,15 +23,15 @@ func (c *stubVPNClient) GetDataKey(context.Context, *vpnproto.GetDataKeyRequest,
func TestConstellationKMS(t *testing.T) {
testCases := map[string]struct {
vpn *stubVPNClient
errExpected bool
wantErr bool
}{
"GetDataKey success": {
vpn: &stubVPNClient{dataKey: []byte{0x1, 0x2, 0x3}},
errExpected: false,
wantErr: false,
},
"GetDataKey error": {
vpn: &stubVPNClient{getDataKeyErr: errors.New("error")},
errExpected: true,
wantErr: true,
},
}
@ -48,7 +48,7 @@ func TestConstellationKMS(t *testing.T) {
}
res, err := kms.GetDEK(context.Background(), "data-key", 64)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
assert.Nil(res)
} else {

View File

@ -29,7 +29,7 @@ func TestRequestKeyLoop(t *testing.T) {
testCases := map[string]struct {
server *stubAPIServer
expectedCalls int
wantCalls int
listResponse []core.Instance
dontStartServer bool
}{
@ -113,7 +113,7 @@ func TestPushStateDiskKey(t *testing.T) {
testCases := map[string]struct {
testAPI *KeyAPI
request *keyproto.PushStateDiskKeyRequest
errExpected bool
wantErr bool
}{
"success": {
testAPI: &KeyAPI{keyReceived: make(chan struct{}, 1)},
@ -125,12 +125,12 @@ func TestPushStateDiskKey(t *testing.T) {
key: []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
},
request: &keyproto.PushStateDiskKeyRequest{StateDiskKey: []byte("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")},
errExpected: true,
wantErr: true,
},
"incorrect size of pushed key": {
testAPI: &KeyAPI{keyReceived: make(chan struct{}, 1)},
request: &keyproto.PushStateDiskKeyRequest{StateDiskKey: []byte("AAAAAAAAAAAAAAAA")},
errExpected: true,
wantErr: true,
},
}
@ -139,7 +139,7 @@ func TestPushStateDiskKey(t *testing.T) {
assert := assert.New(t)
_, err := tc.testAPI.PushStateDiskKey(context.Background(), tc.request)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -26,7 +26,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mounter *stubMounter
openTPM vtpm.TPMOpenFunc
missingState bool
errExpected bool
wantErr bool
}{
"success": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -41,7 +41,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mapper: &stubMapper{uuid: "test"},
mounter: &stubMounter{},
openTPM: vtpm.OpenNOPTPM,
errExpected: true,
wantErr: true,
},
"MapDisk fails causes a repeat": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -53,7 +53,7 @@ func TestPrepareExistingDisk(t *testing.T) {
},
mounter: &stubMounter{},
openTPM: vtpm.OpenNOPTPM,
errExpected: false,
wantErr: false,
},
"MkdirAll fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -61,7 +61,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mapper: &stubMapper{uuid: "test"},
mounter: &stubMounter{mkdirAllErr: someErr},
openTPM: vtpm.OpenNOPTPM,
errExpected: true,
wantErr: true,
},
"Mount fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -69,7 +69,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mapper: &stubMapper{uuid: "test"},
mounter: &stubMounter{mountErr: someErr},
openTPM: vtpm.OpenNOPTPM,
errExpected: true,
wantErr: true,
},
"Unmount fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -77,7 +77,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mapper: &stubMapper{uuid: "test"},
mounter: &stubMounter{unmountErr: someErr},
openTPM: vtpm.OpenNOPTPM,
errExpected: true,
wantErr: true,
},
"MarkNodeAsInitialized fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -85,7 +85,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mapper: &stubMapper{uuid: "test"},
mounter: &stubMounter{unmountErr: someErr},
openTPM: failOpener,
errExpected: true,
wantErr: true,
},
"no state file": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -94,7 +94,7 @@ func TestPrepareExistingDisk(t *testing.T) {
mounter: &stubMounter{},
openTPM: vtpm.OpenNOPTPM,
missingState: true,
errExpected: true,
wantErr: true,
},
}
@ -110,7 +110,7 @@ func TestPrepareExistingDisk(t *testing.T) {
setupManager := New("test", tc.fs, tc.keyWaiter, tc.mapper, tc.mounter, tc.openTPM)
err := setupManager.PrepareExistingDisk()
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -133,7 +133,7 @@ func TestPrepareNewDisk(t *testing.T) {
testCases := map[string]struct {
fs afero.Afero
mapper *stubMapper
errExpected bool
wantErr bool
}{
"success": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -142,7 +142,7 @@ func TestPrepareNewDisk(t *testing.T) {
"creating directory fails": {
fs: afero.Afero{Fs: afero.NewReadOnlyFs(afero.NewMemMapFs())},
mapper: &stubMapper{},
errExpected: true,
wantErr: true,
},
"FormatDisk fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -150,7 +150,7 @@ func TestPrepareNewDisk(t *testing.T) {
uuid: "test",
formatDiskErr: someErr,
},
errExpected: true,
wantErr: true,
},
"MapDisk fails": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -159,7 +159,7 @@ func TestPrepareNewDisk(t *testing.T) {
mapDiskErr: someErr,
mapDiskRepeatedCalls: 1,
},
errExpected: true,
wantErr: true,
},
}
@ -170,7 +170,7 @@ func TestPrepareNewDisk(t *testing.T) {
setupManager := New("test", tc.fs, nil, tc.mapper, nil, nil)
err := setupManager.PrepareNewDisk()
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -191,7 +191,7 @@ func TestReadInitSecrets(t *testing.T) {
ownerID string
clusterID string
writeFile bool
errExpected bool
wantErr bool
}{
"success": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
@ -201,24 +201,24 @@ func TestReadInitSecrets(t *testing.T) {
},
"no state file": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
errExpected: true,
wantErr: true,
},
"missing ownerID": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
clusterID: "clusterID",
writeFile: true,
errExpected: true,
wantErr: true,
},
"missing clusterID": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
ownerID: "ownerID",
writeFile: true,
errExpected: true,
wantErr: true,
},
"no IDs": {
fs: afero.Afero{Fs: afero.NewMemMapFs()},
writeFile: true,
errExpected: true,
wantErr: true,
},
}
@ -236,7 +236,7 @@ func TestReadInitSecrets(t *testing.T) {
setupManager := New("test", tc.fs, nil, nil, nil, nil)
ownerID, clusterID, err := setupManager.readInitSecrets("/tmp/test-state.json")
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)

View File

@ -25,17 +25,17 @@ import (
func TestGetVerifyPeerCertificateFunc(t *testing.T) {
testCases := map[string]struct {
rawCerts [][]byte
errExpected bool
wantErr bool
}{
"no certificates": {
rawCerts: nil,
errExpected: true,
wantErr: true,
},
"invalid certificate": {
rawCerts: [][]byte{
{0x1, 0x2, 0x3},
},
errExpected: true,
wantErr: true,
},
"no extension": {
rawCerts: [][]byte{
@ -43,7 +43,7 @@ func TestGetVerifyPeerCertificateFunc(t *testing.T) {
SerialNumber: big.NewInt(123),
}),
},
errExpected: true,
wantErr: true,
},
"certificate with attestation": {
rawCerts: [][]byte{
@ -58,7 +58,7 @@ func TestGetVerifyPeerCertificateFunc(t *testing.T) {
},
}),
},
errExpected: false,
wantErr: false,
},
}
@ -71,7 +71,7 @@ func TestGetVerifyPeerCertificateFunc(t *testing.T) {
verify := getVerifyPeerCertificateFunc(attDoc)
err := verify(tc.rawCerts, nil)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
require.NoError(err)
@ -98,7 +98,7 @@ func TestExportToFile(t *testing.T) {
testCases := map[string]struct {
pcrs map[uint32][]byte
fs *afero.Afero
errExpected bool
wantErr bool
}{
"file not writeable": {
pcrs: map[uint32][]byte{
@ -107,7 +107,7 @@ func TestExportToFile(t *testing.T) {
2: {0x1, 0x2, 0x3},
},
fs: &afero.Afero{Fs: afero.NewReadOnlyFs(afero.NewMemMapFs())},
errExpected: true,
wantErr: true,
},
"file writeable": {
pcrs: map[uint32][]byte{
@ -116,7 +116,7 @@ func TestExportToFile(t *testing.T) {
2: {0x1, 0x2, 0x3},
},
fs: &afero.Afero{Fs: afero.NewMemMapFs()},
errExpected: false,
wantErr: false,
},
}
@ -127,7 +127,7 @@ func TestExportToFile(t *testing.T) {
path := "test-file"
err := exportToFile(path, tc.pcrs, tc.fs)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
assert.NoError(err)
@ -147,21 +147,21 @@ func TestExportToFile(t *testing.T) {
func TestValidatePCRAttDoc(t *testing.T) {
testCases := map[string]struct {
attDocRaw []byte
errExpected bool
wantErr bool
}{
"invalid attestation document": {
attDocRaw: []byte{0x1, 0x2, 0x3},
errExpected: true,
wantErr: true,
},
"nil attestation": {
attDocRaw: mustMarshalAttDoc(t, vtpm.AttestationDocument{}),
errExpected: true,
wantErr: true,
},
"nil quotes": {
attDocRaw: mustMarshalAttDoc(t, vtpm.AttestationDocument{
Attestation: &attest.Attestation{},
}),
errExpected: true,
wantErr: true,
},
"invalid PCRs": {
attDocRaw: mustMarshalAttDoc(t, vtpm.AttestationDocument{
@ -178,7 +178,7 @@ func TestValidatePCRAttDoc(t *testing.T) {
},
},
}),
errExpected: true,
wantErr: true,
},
"valid PCRs": {
attDocRaw: mustMarshalAttDoc(t, vtpm.AttestationDocument{
@ -195,7 +195,7 @@ func TestValidatePCRAttDoc(t *testing.T) {
},
},
}),
errExpected: false,
wantErr: false,
},
}
@ -205,7 +205,7 @@ func TestValidatePCRAttDoc(t *testing.T) {
require := require.New(t)
pcrs, err := validatePCRAttDoc(tc.attDocRaw)
if tc.errExpected {
if tc.wantErr {
assert.Error(err)
} else {
require.NoError(err)