| 1 | package dc_test |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/CenturyLinkCloud/clc-sdk/api" |
| 10 | "github.com/CenturyLinkCloud/clc-sdk/dc" |
| 11 | "github.com/stretchr/testify/assert" |
| 12 | "github.com/stretchr/testify/mock" |
| 13 | ) |
| 14 | |
| 15 | func TestGetDatacenter(t *testing.T) { |
| 16 | assert := assert.New(t) |
| 17 | |
| 18 | client := NewMockClient() |
| 19 | client.On("Get", "http://localhost/v2/datacenters/test/dc1?groupLinks=true", mock.Anything).Return(nil) |
| 20 | service := dc.New(client) |
| 21 | |
| 22 | id := "dc1" |
| 23 | resp, err := service.Get(id) |
| 24 | |
| 25 | assert.Nil(err) |
| 26 | assert.Equal(id, resp.ID) |
| 27 | } |
| 28 | |
| 29 | func TestGetDatacenters(t *testing.T) { |
| 30 | assert := assert.New(t) |
| 31 | |
| 32 | client := NewMockClient() |
| 33 | client.On("Get", "http://localhost/v2/datacenters/test", mock.Anything).Return(nil) |
| 34 | service := dc.New(client) |
| 35 | |
| 36 | resp, err := service.GetAll() |
| 37 | |
| 38 | assert.Nil(err) |
| 39 | assert.Equal(1, len(resp)) |
| 40 | assert.Equal("dc1", resp[0].ID) |
| 41 | } |
| 42 | |
| 43 | func NewMockClient() *MockClient { |
| 44 | return &MockClient{} |
| 45 | } |
| 46 | |
| 47 | type MockClient struct { |
| 48 | mock.Mock |
| 49 | } |
| 50 | |
| 51 | func (m *MockClient) Get(url string, resp interface{}) error { |
| 52 | if strings.HasSuffix(url, "?groupLinks=true") { |
| 53 | json.Unmarshal([]byte(`{"id":"dc1","name":"test datacenter","links":[{"rel":"self","href":"/v2/datacenters/test/dc1"}]}`), resp) |
| 54 | } |
| 55 | if strings.HasSuffix(url, "test") { |
| 56 | json.Unmarshal([]byte(`[{"id":"dc1","name":"test datacenter","links":[{"rel":"self","href":"/v2/datacenters/test/dc1"}]}]`), resp) |
| 57 | } |
| 58 | |
| 59 | args := m.Called(url, resp) |
| 60 | return args.Error(0) |
| 61 | } |
| 62 | |
| 63 | func (m *MockClient) Post(url string, body, resp interface{}) error { |
| 64 | args := m.Called(url, body, resp) |
| 65 | return args.Error(0) |
| 66 | } |
| 67 | |
| 68 | func (m *MockClient) Put(url string, body, resp interface{}) error { |
| 69 | args := m.Called(url, body, resp) |
| 70 | return args.Error(0) |
| 71 | } |
| 72 | |
| 73 | func (m *MockClient) Patch(url string, body, resp interface{}) error { |
| 74 | args := m.Called(url, body, resp) |
| 75 | return args.Error(0) |
| 76 | } |
| 77 | |
| 78 | func (m *MockClient) Delete(url string, resp interface{}) error { |
| 79 | args := m.Called(url, resp) |
| 80 | return args.Error(0) |
| 81 | } |
| 82 | |
| 83 | func (m *MockClient) Config() *api.Config { |
| 84 | u, _ := url.Parse("http://localhost/v2") |
| 85 | return &api.Config{ |
| 86 | User: api.User{ |
| 87 | Username: "test.user", |
| 88 | Password: "s0s3cur3", |
| 89 | }, |
| 90 | Alias: "test", |
| 91 | BaseURL: u, |
| 92 | } |
| 93 | } |