github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/compute/v2/servers/testing/requests_test.go (about)

     1  package testing
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/json"
     6  	"net/http"
     7  	"testing"
     8  
     9  	"github.com/huaweicloud/golangsdk/openstack/compute/v2/extensions/availabilityzones"
    10  	"github.com/huaweicloud/golangsdk/openstack/compute/v2/extensions/diskconfig"
    11  	"github.com/huaweicloud/golangsdk/openstack/compute/v2/extensions/extendedstatus"
    12  	"github.com/huaweicloud/golangsdk/openstack/compute/v2/servers"
    13  	"github.com/huaweicloud/golangsdk/pagination"
    14  	th "github.com/huaweicloud/golangsdk/testhelper"
    15  	"github.com/huaweicloud/golangsdk/testhelper/client"
    16  )
    17  
    18  func TestListServers(t *testing.T) {
    19  	th.SetupHTTP()
    20  	defer th.TeardownHTTP()
    21  	HandleServerListSuccessfully(t)
    22  
    23  	pages := 0
    24  	err := servers.List(client.ServiceClient(), servers.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
    25  		pages++
    26  
    27  		actual, err := servers.ExtractServers(page)
    28  		if err != nil {
    29  			return false, err
    30  		}
    31  
    32  		if len(actual) != 3 {
    33  			t.Fatalf("Expected 3 servers, got %d", len(actual))
    34  		}
    35  		th.CheckDeepEquals(t, ServerHerp, actual[0])
    36  		th.CheckDeepEquals(t, ServerDerp, actual[1])
    37  		th.CheckDeepEquals(t, ServerMerp, actual[2])
    38  
    39  		return true, nil
    40  	})
    41  
    42  	th.AssertNoErr(t, err)
    43  
    44  	if pages != 1 {
    45  		t.Errorf("Expected 1 page, saw %d", pages)
    46  	}
    47  }
    48  
    49  func TestListAllServers(t *testing.T) {
    50  	th.SetupHTTP()
    51  	defer th.TeardownHTTP()
    52  	HandleServerListSuccessfully(t)
    53  
    54  	allPages, err := servers.List(client.ServiceClient(), servers.ListOpts{}).AllPages()
    55  	th.AssertNoErr(t, err)
    56  	actual, err := servers.ExtractServers(allPages)
    57  	th.AssertNoErr(t, err)
    58  	th.CheckDeepEquals(t, ServerHerp, actual[0])
    59  	th.CheckDeepEquals(t, ServerDerp, actual[1])
    60  }
    61  
    62  func TestListAllServersWithExtensions(t *testing.T) {
    63  	th.SetupHTTP()
    64  	defer th.TeardownHTTP()
    65  	HandleServerListSuccessfully(t)
    66  
    67  	type ServerWithExt struct {
    68  		servers.Server
    69  		availabilityzones.ServerAvailabilityZoneExt
    70  		extendedstatus.ServerExtendedStatusExt
    71  		diskconfig.ServerDiskConfigExt
    72  	}
    73  
    74  	allPages, err := servers.List(client.ServiceClient(), servers.ListOpts{}).AllPages()
    75  	th.AssertNoErr(t, err)
    76  
    77  	var actual []ServerWithExt
    78  	err = servers.ExtractServersInto(allPages, &actual)
    79  	th.AssertNoErr(t, err)
    80  	th.AssertEquals(t, 3, len(actual))
    81  	th.AssertEquals(t, "nova", actual[0].AvailabilityZone)
    82  	th.AssertEquals(t, "RUNNING", actual[0].PowerState.String())
    83  	th.AssertEquals(t, "", actual[0].TaskState)
    84  	th.AssertEquals(t, "active", actual[0].VmState)
    85  	th.AssertEquals(t, diskconfig.Manual, actual[0].DiskConfig)
    86  }
    87  
    88  func TestCreateServer(t *testing.T) {
    89  	th.SetupHTTP()
    90  	defer th.TeardownHTTP()
    91  	HandleServerCreationSuccessfully(t, SingleServerBody)
    92  
    93  	actual, err := servers.Create(client.ServiceClient(), servers.CreateOpts{
    94  		Name:      "derp",
    95  		ImageRef:  "f90f6034-2570-4974-8351-6b49732ef2eb",
    96  		FlavorRef: "1",
    97  	}).Extract()
    98  	th.AssertNoErr(t, err)
    99  
   100  	th.CheckDeepEquals(t, ServerDerp, *actual)
   101  }
   102  
   103  func TestCreateServerWithCustomField(t *testing.T) {
   104  	th.SetupHTTP()
   105  	defer th.TeardownHTTP()
   106  	HandleServerCreationWithCustomFieldSuccessfully(t, SingleServerBody)
   107  
   108  	actual, err := servers.Create(client.ServiceClient(), CreateOptsWithCustomField{
   109  		CreateOpts: servers.CreateOpts{
   110  			Name:      "derp",
   111  			ImageRef:  "f90f6034-2570-4974-8351-6b49732ef2eb",
   112  			FlavorRef: "1",
   113  		},
   114  		Foo: "bar",
   115  	}).Extract()
   116  	th.AssertNoErr(t, err)
   117  
   118  	th.CheckDeepEquals(t, ServerDerp, *actual)
   119  }
   120  
   121  func TestCreateServerWithMetadata(t *testing.T) {
   122  	th.SetupHTTP()
   123  	defer th.TeardownHTTP()
   124  	HandleServerCreationWithMetadata(t, SingleServerBody)
   125  
   126  	actual, err := servers.Create(client.ServiceClient(), servers.CreateOpts{
   127  		Name:      "derp",
   128  		ImageRef:  "f90f6034-2570-4974-8351-6b49732ef2eb",
   129  		FlavorRef: "1",
   130  		Metadata: map[string]string{
   131  			"abc": "def",
   132  		},
   133  	}).Extract()
   134  	th.AssertNoErr(t, err)
   135  
   136  	th.CheckDeepEquals(t, ServerDerp, *actual)
   137  }
   138  
   139  func TestCreateServerWithUserdataString(t *testing.T) {
   140  	th.SetupHTTP()
   141  	defer th.TeardownHTTP()
   142  	HandleServerCreationWithUserdata(t, SingleServerBody)
   143  
   144  	actual, err := servers.Create(client.ServiceClient(), servers.CreateOpts{
   145  		Name:      "derp",
   146  		ImageRef:  "f90f6034-2570-4974-8351-6b49732ef2eb",
   147  		FlavorRef: "1",
   148  		UserData:  []byte("userdata string"),
   149  	}).Extract()
   150  	th.AssertNoErr(t, err)
   151  
   152  	th.CheckDeepEquals(t, ServerDerp, *actual)
   153  }
   154  
   155  func TestCreateServerWithUserdataEncoded(t *testing.T) {
   156  	th.SetupHTTP()
   157  	defer th.TeardownHTTP()
   158  	HandleServerCreationWithUserdata(t, SingleServerBody)
   159  
   160  	encoded := base64.StdEncoding.EncodeToString([]byte("userdata string"))
   161  
   162  	actual, err := servers.Create(client.ServiceClient(), servers.CreateOpts{
   163  		Name:      "derp",
   164  		ImageRef:  "f90f6034-2570-4974-8351-6b49732ef2eb",
   165  		FlavorRef: "1",
   166  		UserData:  []byte(encoded),
   167  	}).Extract()
   168  	th.AssertNoErr(t, err)
   169  
   170  	th.CheckDeepEquals(t, ServerDerp, *actual)
   171  }
   172  
   173  func TestCreateServerWithImageNameAndFlavorName(t *testing.T) {
   174  	th.SetupHTTP()
   175  	defer th.TeardownHTTP()
   176  	HandleServerCreationSuccessfully(t, SingleServerBody)
   177  
   178  	actual, err := servers.Create(client.ServiceClient(), servers.CreateOpts{
   179  		Name:          "derp",
   180  		ImageName:     "cirros-0.3.2-x86_64-disk",
   181  		FlavorName:    "m1.tiny",
   182  		ServiceClient: client.ServiceClient(),
   183  	}).Extract()
   184  	th.AssertNoErr(t, err)
   185  
   186  	th.CheckDeepEquals(t, ServerDerp, *actual)
   187  }
   188  
   189  func TestDeleteServer(t *testing.T) {
   190  	th.SetupHTTP()
   191  	defer th.TeardownHTTP()
   192  	HandleServerDeletionSuccessfully(t)
   193  
   194  	res := servers.Delete(client.ServiceClient(), "asdfasdfasdf")
   195  	th.AssertNoErr(t, res.Err)
   196  }
   197  
   198  func TestForceDeleteServer(t *testing.T) {
   199  	th.SetupHTTP()
   200  	defer th.TeardownHTTP()
   201  	HandleServerForceDeletionSuccessfully(t)
   202  
   203  	res := servers.ForceDelete(client.ServiceClient(), "asdfasdfasdf")
   204  	th.AssertNoErr(t, res.Err)
   205  }
   206  
   207  func TestGetServer(t *testing.T) {
   208  	th.SetupHTTP()
   209  	defer th.TeardownHTTP()
   210  	HandleServerGetSuccessfully(t)
   211  
   212  	client := client.ServiceClient()
   213  	actual, err := servers.Get(client, "1234asdf").Extract()
   214  	if err != nil {
   215  		t.Fatalf("Unexpected Get error: %v", err)
   216  	}
   217  
   218  	th.CheckDeepEquals(t, ServerDerp, *actual)
   219  }
   220  
   221  func TestGetFaultyServer(t *testing.T) {
   222  	th.SetupHTTP()
   223  	defer th.TeardownHTTP()
   224  	HandleServerGetFaultSuccessfully(t)
   225  
   226  	client := client.ServiceClient()
   227  	actual, err := servers.Get(client, "1234asdf").Extract()
   228  	if err != nil {
   229  		t.Fatalf("Unexpected Get error: %v", err)
   230  	}
   231  
   232  	FaultyServer := ServerDerp
   233  	FaultyServer.Fault = DerpFault
   234  	th.CheckDeepEquals(t, FaultyServer, *actual)
   235  }
   236  
   237  func TestGetServerWithExtensions(t *testing.T) {
   238  	th.SetupHTTP()
   239  	defer th.TeardownHTTP()
   240  	HandleServerGetSuccessfully(t)
   241  
   242  	var s struct {
   243  		servers.Server
   244  		availabilityzones.ServerAvailabilityZoneExt
   245  		extendedstatus.ServerExtendedStatusExt
   246  		diskconfig.ServerDiskConfigExt
   247  	}
   248  
   249  	err := servers.Get(client.ServiceClient(), "1234asdf").ExtractInto(&s)
   250  	th.AssertNoErr(t, err)
   251  	th.AssertEquals(t, "nova", s.AvailabilityZone)
   252  	th.AssertEquals(t, "RUNNING", s.PowerState.String())
   253  	th.AssertEquals(t, "", s.TaskState)
   254  	th.AssertEquals(t, "active", s.VmState)
   255  	th.AssertEquals(t, diskconfig.Manual, s.DiskConfig)
   256  
   257  	err = servers.Get(client.ServiceClient(), "1234asdf").ExtractInto(s)
   258  	if err == nil {
   259  		t.Errorf("Expected error when providing non-pointer struct")
   260  	}
   261  }
   262  
   263  func TestUpdateServer(t *testing.T) {
   264  	th.SetupHTTP()
   265  	defer th.TeardownHTTP()
   266  	HandleServerUpdateSuccessfully(t)
   267  
   268  	client := client.ServiceClient()
   269  	actual, err := servers.Update(client, "1234asdf", servers.UpdateOpts{Name: "new-name"}).Extract()
   270  	if err != nil {
   271  		t.Fatalf("Unexpected Update error: %v", err)
   272  	}
   273  
   274  	th.CheckDeepEquals(t, ServerDerp, *actual)
   275  }
   276  
   277  func TestChangeServerAdminPassword(t *testing.T) {
   278  	th.SetupHTTP()
   279  	defer th.TeardownHTTP()
   280  	HandleAdminPasswordChangeSuccessfully(t)
   281  
   282  	res := servers.ChangeAdminPassword(client.ServiceClient(), "1234asdf", "new-password")
   283  	th.AssertNoErr(t, res.Err)
   284  }
   285  
   286  func TestShowConsoleOutput(t *testing.T) {
   287  	th.SetupHTTP()
   288  	defer th.TeardownHTTP()
   289  	HandleShowConsoleOutputSuccessfully(t, ConsoleOutputBody)
   290  
   291  	outputOpts := &servers.ShowConsoleOutputOpts{
   292  		Length: 50,
   293  	}
   294  	actual, err := servers.ShowConsoleOutput(client.ServiceClient(), "1234asdf", outputOpts).Extract()
   295  
   296  	th.AssertNoErr(t, err)
   297  	th.AssertByteArrayEquals(t, []byte(ConsoleOutput), []byte(actual))
   298  }
   299  
   300  func TestGetPassword(t *testing.T) {
   301  	th.SetupHTTP()
   302  	defer th.TeardownHTTP()
   303  	HandlePasswordGetSuccessfully(t)
   304  
   305  	res := servers.GetPassword(client.ServiceClient(), "1234asdf")
   306  	th.AssertNoErr(t, res.Err)
   307  }
   308  
   309  func TestRebootServer(t *testing.T) {
   310  	th.SetupHTTP()
   311  	defer th.TeardownHTTP()
   312  	HandleRebootSuccessfully(t)
   313  
   314  	res := servers.Reboot(client.ServiceClient(), "1234asdf", servers.RebootOpts{
   315  		Type: servers.SoftReboot,
   316  	})
   317  	th.AssertNoErr(t, res.Err)
   318  }
   319  
   320  func TestRebuildServer(t *testing.T) {
   321  	th.SetupHTTP()
   322  	defer th.TeardownHTTP()
   323  	HandleRebuildSuccessfully(t, SingleServerBody)
   324  
   325  	opts := servers.RebuildOpts{
   326  		Name:       "new-name",
   327  		AdminPass:  "swordfish",
   328  		ImageID:    "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb",
   329  		AccessIPv4: "1.2.3.4",
   330  	}
   331  
   332  	actual, err := servers.Rebuild(client.ServiceClient(), "1234asdf", opts).Extract()
   333  	th.AssertNoErr(t, err)
   334  
   335  	th.CheckDeepEquals(t, ServerDerp, *actual)
   336  }
   337  
   338  func TestResizeServer(t *testing.T) {
   339  	th.SetupHTTP()
   340  	defer th.TeardownHTTP()
   341  
   342  	th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) {
   343  		th.TestMethod(t, r, "POST")
   344  		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
   345  		th.TestJSONRequest(t, r, `{ "resize": { "flavorRef": "2" } }`)
   346  
   347  		w.WriteHeader(http.StatusAccepted)
   348  	})
   349  
   350  	res := servers.Resize(client.ServiceClient(), "1234asdf", servers.ResizeOpts{FlavorRef: "2"})
   351  	th.AssertNoErr(t, res.Err)
   352  }
   353  
   354  func TestConfirmResize(t *testing.T) {
   355  	th.SetupHTTP()
   356  	defer th.TeardownHTTP()
   357  
   358  	th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) {
   359  		th.TestMethod(t, r, "POST")
   360  		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
   361  		th.TestJSONRequest(t, r, `{ "confirmResize": null }`)
   362  
   363  		w.WriteHeader(http.StatusNoContent)
   364  	})
   365  
   366  	res := servers.ConfirmResize(client.ServiceClient(), "1234asdf")
   367  	th.AssertNoErr(t, res.Err)
   368  }
   369  
   370  func TestRevertResize(t *testing.T) {
   371  	th.SetupHTTP()
   372  	defer th.TeardownHTTP()
   373  
   374  	th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) {
   375  		th.TestMethod(t, r, "POST")
   376  		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
   377  		th.TestJSONRequest(t, r, `{ "revertResize": null }`)
   378  
   379  		w.WriteHeader(http.StatusAccepted)
   380  	})
   381  
   382  	res := servers.RevertResize(client.ServiceClient(), "1234asdf")
   383  	th.AssertNoErr(t, res.Err)
   384  }
   385  
   386  func TestGetMetadatum(t *testing.T) {
   387  	th.SetupHTTP()
   388  	defer th.TeardownHTTP()
   389  
   390  	HandleMetadatumGetSuccessfully(t)
   391  
   392  	expected := map[string]string{"foo": "bar"}
   393  	actual, err := servers.Metadatum(client.ServiceClient(), "1234asdf", "foo").Extract()
   394  	th.AssertNoErr(t, err)
   395  	th.AssertDeepEquals(t, expected, actual)
   396  }
   397  
   398  func TestCreateMetadatum(t *testing.T) {
   399  	th.SetupHTTP()
   400  	defer th.TeardownHTTP()
   401  
   402  	HandleMetadatumCreateSuccessfully(t)
   403  
   404  	expected := map[string]string{"foo": "bar"}
   405  	actual, err := servers.CreateMetadatum(client.ServiceClient(), "1234asdf", servers.MetadatumOpts{"foo": "bar"}).Extract()
   406  	th.AssertNoErr(t, err)
   407  	th.AssertDeepEquals(t, expected, actual)
   408  }
   409  
   410  func TestDeleteMetadatum(t *testing.T) {
   411  	th.SetupHTTP()
   412  	defer th.TeardownHTTP()
   413  
   414  	HandleMetadatumDeleteSuccessfully(t)
   415  
   416  	err := servers.DeleteMetadatum(client.ServiceClient(), "1234asdf", "foo").ExtractErr()
   417  	th.AssertNoErr(t, err)
   418  }
   419  
   420  func TestGetMetadata(t *testing.T) {
   421  	th.SetupHTTP()
   422  	defer th.TeardownHTTP()
   423  
   424  	HandleMetadataGetSuccessfully(t)
   425  
   426  	expected := map[string]string{"foo": "bar", "this": "that"}
   427  	actual, err := servers.Metadata(client.ServiceClient(), "1234asdf").Extract()
   428  	th.AssertNoErr(t, err)
   429  	th.AssertDeepEquals(t, expected, actual)
   430  }
   431  
   432  func TestResetMetadata(t *testing.T) {
   433  	th.SetupHTTP()
   434  	defer th.TeardownHTTP()
   435  
   436  	HandleMetadataResetSuccessfully(t)
   437  
   438  	expected := map[string]string{"foo": "bar", "this": "that"}
   439  	actual, err := servers.ResetMetadata(client.ServiceClient(), "1234asdf", servers.MetadataOpts{
   440  		"foo":  "bar",
   441  		"this": "that",
   442  	}).Extract()
   443  	th.AssertNoErr(t, err)
   444  	th.AssertDeepEquals(t, expected, actual)
   445  }
   446  
   447  func TestUpdateMetadata(t *testing.T) {
   448  	th.SetupHTTP()
   449  	defer th.TeardownHTTP()
   450  
   451  	HandleMetadataUpdateSuccessfully(t)
   452  
   453  	expected := map[string]string{"foo": "baz", "this": "those"}
   454  	actual, err := servers.UpdateMetadata(client.ServiceClient(), "1234asdf", servers.MetadataOpts{
   455  		"foo":  "baz",
   456  		"this": "those",
   457  	}).Extract()
   458  	th.AssertNoErr(t, err)
   459  	th.AssertDeepEquals(t, expected, actual)
   460  }
   461  
   462  func TestListAddresses(t *testing.T) {
   463  	th.SetupHTTP()
   464  	defer th.TeardownHTTP()
   465  	HandleAddressListSuccessfully(t)
   466  
   467  	expected := ListAddressesExpected
   468  	pages := 0
   469  	err := servers.ListAddresses(client.ServiceClient(), "asdfasdfasdf").EachPage(func(page pagination.Page) (bool, error) {
   470  		pages++
   471  
   472  		actual, err := servers.ExtractAddresses(page)
   473  		th.AssertNoErr(t, err)
   474  
   475  		if len(actual) != 2 {
   476  			t.Fatalf("Expected 2 networks, got %d", len(actual))
   477  		}
   478  		th.CheckDeepEquals(t, expected, actual)
   479  
   480  		return true, nil
   481  	})
   482  	th.AssertNoErr(t, err)
   483  	th.CheckEquals(t, 1, pages)
   484  }
   485  
   486  func TestListAddressesByNetwork(t *testing.T) {
   487  	th.SetupHTTP()
   488  	defer th.TeardownHTTP()
   489  	HandleNetworkAddressListSuccessfully(t)
   490  
   491  	expected := ListNetworkAddressesExpected
   492  	pages := 0
   493  	err := servers.ListAddressesByNetwork(client.ServiceClient(), "asdfasdfasdf", "public").EachPage(func(page pagination.Page) (bool, error) {
   494  		pages++
   495  
   496  		actual, err := servers.ExtractNetworkAddresses(page)
   497  		th.AssertNoErr(t, err)
   498  
   499  		if len(actual) != 2 {
   500  			t.Fatalf("Expected 2 addresses, got %d", len(actual))
   501  		}
   502  		th.CheckDeepEquals(t, expected, actual)
   503  
   504  		return true, nil
   505  	})
   506  	th.AssertNoErr(t, err)
   507  	th.CheckEquals(t, 1, pages)
   508  }
   509  
   510  func TestCreateServerImage(t *testing.T) {
   511  	th.SetupHTTP()
   512  	defer th.TeardownHTTP()
   513  	HandleCreateServerImageSuccessfully(t)
   514  
   515  	_, err := servers.CreateImage(client.ServiceClient(), "serverimage", servers.CreateImageOpts{Name: "test"}).ExtractImageID()
   516  	th.AssertNoErr(t, err)
   517  }
   518  
   519  func TestMarshalPersonality(t *testing.T) {
   520  	name := "/etc/test"
   521  	contents := []byte("asdfasdf")
   522  
   523  	personality := servers.Personality{
   524  		&servers.File{
   525  			Path:     name,
   526  			Contents: contents,
   527  		},
   528  	}
   529  
   530  	data, err := json.Marshal(personality)
   531  	if err != nil {
   532  		t.Fatal(err)
   533  	}
   534  
   535  	var actual []map[string]string
   536  	err = json.Unmarshal(data, &actual)
   537  	if err != nil {
   538  		t.Fatal(err)
   539  	}
   540  
   541  	if len(actual) != 1 {
   542  		t.Fatal("expected personality length 1")
   543  	}
   544  
   545  	if actual[0]["path"] != name {
   546  		t.Fatal("file path incorrect")
   547  	}
   548  
   549  	if actual[0]["contents"] != base64.StdEncoding.EncodeToString(contents) {
   550  		t.Fatal("file contents incorrect")
   551  	}
   552  }