Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(cdn): refactor the billing_option resource and dataSource code style #6177

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/data-sources/cdn_billing_option.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
subcategory: Content Delivery Network (CDN)
layout: "huaweicloud"
page_title: "HuaweiCloud: huaweicloud_cdn_billing_option"
description: "Use this data source to get CDN billing option."
description: |-
Use this data source to get CDN billing option within HuaweiCloud.
---

# huaweicloud_cdn_billing_option

Use this data source to get CDN billing option.
Use this data source to get CDN billing option within HuaweiCloud.

## Example Usage

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/acceptance"
)

func TestAccDatasourceBillingOption_basic(t *testing.T) {
func TestAccDataSourceBillingOption_basic(t *testing.T) {
var (
rName = "data.huaweicloud_cdn_billing_option.test"
dc = acceptance.InitDataSourceCheck(rName)
Expand All @@ -19,11 +19,13 @@ func TestAccDatasourceBillingOption_basic(t *testing.T) {
)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acceptance.TestAccPreCheck(t) },
PreCheck: func() {
acceptance.TestAccPreCheck(t)
},
ProviderFactories: acceptance.TestAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccDatasourceBillingOption_basic,
Config: testDataSourceBillingOption_basic,
Check: resource.ComposeTestCheckFunc(
dc.CheckResourceExists(),
resource.TestCheckResourceAttrSet(rName, "product_type"),
Expand All @@ -43,15 +45,15 @@ func TestAccDatasourceBillingOption_basic(t *testing.T) {
),
},
{
Config: testAccDatasourceBillingOption_expectError,
Config: testDataSourceBillingOption_expectError,
ExpectError: regexp.MustCompile("Your query returned no results. " +
"Please change your search criteria and try again."),
},
},
})
}

const testAccDatasourceBillingOption_basic = `
const testDataSourceBillingOption_basic = `
data "huaweicloud_cdn_billing_option" "test" {
product_type = "base"
}
Expand All @@ -63,7 +65,7 @@ data "huaweicloud_cdn_billing_option" "all_filter" {
}
`

const testAccDatasourceBillingOption_expectError = `
const testDataSourceBillingOption_expectError = `
data "huaweicloud_cdn_billing_option" "test" {
product_type = "base"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,50 +7,43 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"

"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/cdn/v2/model"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/acceptance"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/services/cdn"
)

func getBillingOptionResourceFunc(cfg *config.Config, state *terraform.ResourceState) (interface{}, error) {
region := acceptance.HW_REGION_NAME
hcCdnClient, err := cfg.HcCdnV2Client(region)
if err != nil {
return nil, fmt.Errorf("error creating CDN v2 client: %s", err)
}

request := model.ShowChargeModesRequest{
ProductType: state.Primary.Attributes["product_type"],
}

resp, err := hcCdnClient.ShowChargeModes(&request)
var (
region = acceptance.HW_REGION_NAME
product = "cdn"
productType = state.Primary.Attributes["product_type"]
)
client, err := cfg.NewServiceClient(product, region)
if err != nil {
return nil, fmt.Errorf("error retrieving CDN billing option: %s", err)
}

if resp == nil || resp.Result == nil || len(*resp.Result) == 0 {
return nil, fmt.Errorf("error retrieving CDN billing option: Result is not found in API response")
return nil, fmt.Errorf("error creating CDN client: %s", err)
}

resultArray := *resp.Result
return resultArray[0], nil
return cdn.GetBillingOptionDetail(client, productType)
}

func TestAccBillingOption_basic(t *testing.T) {
var obj interface{}

rName := "huaweicloud_cdn_billing_option.test"
var (
obj interface{}
rName = "huaweicloud_cdn_billing_option.test"
)

rc := acceptance.InitResourceCheck(
rName,
&obj,
getBillingOptionResourceFunc,
)

// Avoid CheckDestroy, because there is nothing in the resource destroy method.
// lintignore:AT001
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acceptance.TestAccPreCheck(t) },
PreCheck: func() {
acceptance.TestAccPreCheck(t)
},
ProviderFactories: acceptance.TestAccProviderFactories,
Steps: []resource.TestStep{
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ package cdn

import (
"context"
"fmt"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"

"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/cdn/v2/model"
"github.com/chnsz/golangsdk"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
Expand All @@ -22,7 +23,7 @@ import (
// @API CDN GET /v1.0/cdn/charge/charge-modes
func DataSourceBillingOption() *schema.Resource {
return &schema.Resource{
ReadContext: dataBillingOptionRead,
ReadContext: dataSourceBillingOptionRead,
Schema: map[string]*schema.Schema{
"product_type": {
Type: schema.TypeString,
Expand All @@ -33,7 +34,7 @@ func DataSourceBillingOption() *schema.Resource {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the service area`,
Description: `Specifies the service area.`,
},
"status": {
Type: schema.TypeString,
Expand All @@ -60,50 +61,69 @@ func DataSourceBillingOption() *schema.Resource {
}
}

func dataBillingOptionRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
hcCdnClient, err := cfg.HcCdnV2Client(region)
func buildDataSourceBillingOptionQueryParams(d *schema.ResourceData) string {
queryParams := fmt.Sprintf("?product_type=%v", d.Get("product_type"))
if v, ok := d.GetOk("service_area"); ok {
queryParams = fmt.Sprintf("%s&service_area=%v", queryParams, v)
}
if v, ok := d.GetOk("status"); ok {
queryParams = fmt.Sprintf("%s&status=%v", queryParams, v)
}

return queryParams
}

func dataSourceBillingOptionRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var (
cfg = meta.(*config.Config)
region = cfg.GetRegion(d)
product = "cdn"
mErr *multierror.Error
)

client, err := cfg.NewServiceClient(product, region)
if err != nil {
return diag.Errorf("error creating CDN v2 client: %s", err)
return diag.Errorf("error creating CDN client: %s", err)
}

request := model.ShowChargeModesRequest{
ProductType: d.Get("product_type").(string),
Status: utils.StringIgnoreEmpty(d.Get("status").(string)),
ServiceArea: utils.StringIgnoreEmpty(d.Get("service_area").(string)),
getPath := client.Endpoint + "v1.0/cdn/charge/charge-modes"
getPath += buildDataSourceBillingOptionQueryParams(d)
getOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}

resp, err := hcCdnClient.ShowChargeModes(&request)
getResp, err := client.Request("GET", getPath, &getOpt)
if err != nil {
return diag.Errorf("error retrieving CDN billing option: %s", err)
}

if resp == nil || resp.Result == nil {
return diag.Errorf("error retrieving CDN billing option: Result is not found in API response")
getRespBody, err := utils.FlattenResponse(getResp)
if err != nil {
return diag.FromErr(err)
}

if len(*resp.Result) == 0 {
result := utils.PathSearch("result[0]", getRespBody, nil)
if result == nil {
return diag.Errorf("Your query returned no results. Please change your search criteria and try again.")
}

generateUUID, err := uuid.GenerateUUID()
if err != nil {
return diag.Errorf("unable to generate ID: %s", err)
}

d.SetId(generateUUID)

resultArray := *resp.Result
resultMap := resultArray[0]
var mErr *multierror.Error
mErr = multierror.Append(
mErr,
d.Set("product_type", resultMap["product_type"]),
d.Set("service_area", resultMap["service_area"]),
d.Set("status", resultMap["status"]),
d.Set("charge_mode", resultMap["charge_mode"]),
d.Set("created_at", flattenTimeStamp(resultMap["create_time"])),
d.Set("effective_time", flattenTimeStamp(resultMap["effective_time"])),
d.Set("product_type", utils.PathSearch("product_type", result, nil)),
d.Set("service_area", utils.PathSearch("service_area", result, nil)),
d.Set("status", utils.PathSearch("status", result, nil)),
d.Set("charge_mode", utils.PathSearch("charge_mode", result, nil)),
d.Set("created_at", flattenCreatedAt(result)),
d.Set("effective_time", flattenEffectiveTime(result)),
)

return diag.FromErr(mErr.ErrorOrNil())
}
Loading
Loading