Skip to content

Commit

Permalink
feat: Plugin Framework wrappers for CIDRContains().
Browse files Browse the repository at this point in the history
  • Loading branch information
skyzyx committed Nov 10, 2024
1 parent 985c0cc commit 81ab1e2
Show file tree
Hide file tree
Showing 21 changed files with 713 additions and 92 deletions.
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,10 @@ list-tests:

.PHONY: bats
## bats: [test] Tests the output of the provider using tfschema and BATS.
bats: build
bats: build clean
@ $(HEADER) "=====> Running BATS/tfschema tests..."
cd ./bats && terraform init && bats *.bats.sh
@ # cd ./bats && terraform init && bats *.bats.sh
cd ./bats && bats *.bats.sh

.PHONY: acc
## acc: [test] Runs Terraform provider acceptance tests. Set NAME= (without 'TestAcc') to run a specific test by name.
Expand Down
Binary file modified acc-coverage.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
172 changes: 99 additions & 73 deletions acc-coverage.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions bats/ds_net_cidr_contains.bats.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env bats
# https://bats-core.readthedocs.io/en/stable/writing-tests.html

@test "corefunc_net_cidr_contains: attrs" {
run bash -c "tfschema data show -format=json corefunc_net_cidr_contains | jq -Mrc '.attributes[]'"

[[ ${status} -eq 0 ]]
[[ ${lines[0]} == '{"name":"contained_ip_or_cidr","type":"string","required":true,"optional":false,"computed":false,"sensitive":false}' ]]
[[ ${lines[1]} == '{"name":"containing_cidr","type":"string","required":true,"optional":false,"computed":false,"sensitive":false}' ]]
[[ ${lines[2]} == '{"name":"value","type":"bool","required":false,"optional":false,"computed":true,"sensitive":false}' ]]
}
27 changes: 14 additions & 13 deletions bats/tfschema_listing.bats.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@
[[ ${lines[1]} == "corefunc_homedir_expand" ]]
[[ ${lines[2]} == "corefunc_homedir_get" ]]
[[ ${lines[3]} == "corefunc_int_leftpad" ]]
[[ ${lines[4]} == "corefunc_runtime_cpuarch" ]]
[[ ${lines[5]} == "corefunc_runtime_goroot" ]]
[[ ${lines[6]} == "corefunc_runtime_numcpus" ]]
[[ ${lines[7]} == "corefunc_runtime_os" ]]
[[ ${lines[8]} == "corefunc_str_camel" ]]
[[ ${lines[9]} == "corefunc_str_constant" ]]
[[ ${lines[10]} == "corefunc_str_iterative_replace" ]]
[[ ${lines[11]} == "corefunc_str_kebab" ]]
[[ ${lines[12]} == "corefunc_str_leftpad" ]]
[[ ${lines[13]} == "corefunc_str_pascal" ]]
[[ ${lines[14]} == "corefunc_str_snake" ]]
[[ ${lines[15]} == "corefunc_str_truncate_label" ]]
[[ ${lines[16]} == "corefunc_url_parse" ]]
[[ ${lines[4]} == "corefunc_net_cidr_contains" ]]
[[ ${lines[5]} == "corefunc_runtime_cpuarch" ]]
[[ ${lines[6]} == "corefunc_runtime_goroot" ]]
[[ ${lines[7]} == "corefunc_runtime_numcpus" ]]
[[ ${lines[8]} == "corefunc_runtime_os" ]]
[[ ${lines[9]} == "corefunc_str_camel" ]]
[[ ${lines[10]} == "corefunc_str_constant" ]]
[[ ${lines[11]} == "corefunc_str_iterative_replace" ]]
[[ ${lines[12]} == "corefunc_str_kebab" ]]
[[ ${lines[13]} == "corefunc_str_leftpad" ]]
[[ ${lines[14]} == "corefunc_str_pascal" ]]
[[ ${lines[15]} == "corefunc_str_snake" ]]
[[ ${lines[16]} == "corefunc_str_truncate_label" ]]
[[ ${lines[17]} == "corefunc_url_parse" ]]
}
2 changes: 1 addition & 1 deletion corefunc/cidr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func ExampleCIDRContains() {
}

func TestCIDRContains(t *testing.T) { // lint:allow_complexity
for name, tc := range testfixtures.CIDRContainsTestTable {
for name, tc := range testfixtures.NetCidrContainsTestTable {
t.Run(name, func(t *testing.T) {
output, err := CIDRContains(tc.ContainerCidr, tc.ContainedIPOrCidr)

Expand Down
177 changes: 177 additions & 0 deletions corefuncprovider/net_cidr_contains_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <rparman@northwood-labs.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package corefuncprovider // lint:no_dupe

import (
"context"
"fmt"
"strings"

"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/lithammer/dedent"
"github.com/northwood-labs/terraform-provider-corefunc/corefunc"
)

// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &netCidrContainsDataSource{}
_ datasource.DataSourceWithConfigure = &netCidrContainsDataSource{}
)

// netCidrContainsDataSource is the data source implementation.
type (
netCidrContainsDataSource struct{}

// netCidrContainsDataSourceModel maps the data source schema data.
netCidrContainsDataSourceModel struct {
ContainingCidr types.String `tfsdk:"containing_cidr"`
ContainedIPOrCidr types.String `tfsdk:"contained_ip_or_cidr"`
Value types.Bool `tfsdk:"value"`
}
)

// NetCidrContainsDataSource is a method that exposes its paired Go function as a
// Terraform Data Source.
func NetCidrContainsDataSource() datasource.DataSource { // lint:allow_return_interface
return &netCidrContainsDataSource{}
}

// Metadata returns the data source type name.
func (d *netCidrContainsDataSource) Metadata(
ctx context.Context,
req datasource.MetadataRequest,
resp *datasource.MetadataResponse,
) {
tflog.Debug(ctx, "Starting NetCidrContains DataSource Metadata method.")

resp.TypeName = req.ProviderTypeName + "_net_cidr_contains"

tflog.Debug(ctx, fmt.Sprintf("req.ProviderTypeName = %s", req.ProviderTypeName))
tflog.Debug(ctx, fmt.Sprintf("resp.TypeName = %s", resp.TypeName))

tflog.Debug(ctx, "Ending NetCidrContains DataSource Metadata method.")
}

// Schema defines the schema for the data source.
func (d *netCidrContainsDataSource) Schema(
ctx context.Context,
_ datasource.SchemaRequest,
resp *datasource.SchemaResponse,
) {
tflog.Debug(ctx, "Starting NetCidrContains DataSource Schema method.")

resp.Schema = schema.Schema{
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
CIDRContains checks to see if an IP address or CIDR block is contained
within another CIDR block.
-> Ported from OpenTofu.
Maps to the ` + linkPackage("CIDRContains") + ` Go method, which can be used in ` + Terratest + `.
`)),
Attributes: map[string]schema.Attribute{
"containing_cidr": schema.StringAttribute{
MarkdownDescription: "A CIDR range to check as a containing range.",
Required: true,
},
"contained_ip_or_cidr": schema.StringAttribute{
MarkdownDescription: "An IP address or CIDR range to check as a contained range.",
Required: true,
},
"value": schema.BoolAttribute{
MarkdownDescription: "Whether or not the IP address or CIDR range is contained within the container CIDR range.",
Computed: true,
},
},
}

tflog.Debug(ctx, "Ending NetCidrContains DataSource Schema method.")
}

// Configure adds the provider configured client to the data source.
func (d *netCidrContainsDataSource) Configure(
ctx context.Context,
req datasource.ConfigureRequest,
_ *datasource.ConfigureResponse,
) {
tflog.Debug(ctx, "Starting NetCidrContains DataSource Configure method.")

if req.ProviderData == nil {
return
}

tflog.Debug(ctx, "Ending NetCidrContains DataSource Configure method.")
}

func (d *netCidrContainsDataSource) Create(
ctx context.Context,
req resource.CreateRequest, // lint:allow_large_memory
resp *resource.CreateResponse,
) {
tflog.Debug(ctx, "Starting NetCidrContains DataSource Create method.")

var plan netCidrContainsDataSourceModel

diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

tflog.Debug(ctx, "Ending NetCidrContains DataSource Create method.")
}

// Read refreshes the Terraform state with the latest data.
func (d *netCidrContainsDataSource) Read( // lint:no_dupe
ctx context.Context,
_ datasource.ReadRequest, // lint:allow_large_memory
resp *datasource.ReadResponse,
) {
tflog.Debug(ctx, "Starting NetCidrContains DataSource Read method.")

var state netCidrContainsDataSourceModel
diags := resp.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)

isContained, err := corefunc.CIDRContains(
state.ContainingCidr.ValueString(),
state.ContainedIPOrCidr.ValueString(),
)
if err != nil {
resp.Diagnostics.AddError(
"Problem with CIDR",
err.Error(),
)

return
}

state.Value = types.BoolValue(isContained)

diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)

if resp.Diagnostics.HasError() {
return
}

tflog.Debug(ctx, "Ending NetCidrContains DataSource Read method.")
}
6 changes: 6 additions & 0 deletions corefuncprovider/net_cidr_contains_data_source_fixture.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
data "corefunc_net_cidr_contains" "cidr" {
containing_cidr = "{{ .ContainerCidr }}"
contained_ip_or_cidr = "{{ .ContainedIPOrCidr }}"
}
#=> {{ .Expected }}
{{ if eq .ExpectedErr true }}#=> ExpectedErr: {{ .ExpectedErr }}{{ end }}
94 changes: 94 additions & 0 deletions corefuncprovider/net_cidr_contains_data_source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <rparman@northwood-labs.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package corefuncprovider // lint:no_dupe

import (
"bytes"
"fmt"
"log"
"os"
"regexp"
"strings"
"testing"
"text/template"

"github.com/northwood-labs/terraform-provider-corefunc/testfixtures"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
)

func TestAccNetCidrContainsDataSource(t *testing.T) {
t.Parallel()

funcName := traceFuncName()

for name, tc := range testfixtures.NetCidrContainsTestTable { // lint:no_dupe
fmt.Printf(
"=== RUN %s/%s\n",
strings.TrimSpace(funcName),
strings.TrimSpace(name),
)

buf := &bytes.Buffer{}
tmpl := template.Must(
template.ParseFiles("net_cidr_contains_data_source_fixture.tftpl"),
)

err := tmpl.Execute(buf, tc)
if err != nil {
log.Fatalln(err)
}

if os.Getenv("PROVIDER_DEBUG") != "" {
fmt.Fprintln(os.Stderr, buf.String())
}

if tc.ExpectedErr {
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(
"data.corefunc_net_cidr_contains.cidr",
"value",
fmt.Sprintf("%v", tc.Expected),
),
),
ExpectError: regexp.MustCompile(".*"),
},
},
})
} else {
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(
"data.corefunc_net_cidr_contains.cidr",
"value",
fmt.Sprintf("%v", tc.Expected),
),
),
},
},
})
}
}
}
Loading

0 comments on commit 81ab1e2

Please sign in to comment.