Skip to content

Commit

Permalink
refactor: Add more support for provider functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
skyzyx committed Mar 11, 2024
1 parent ad94772 commit cea02c3
Show file tree
Hide file tree
Showing 68 changed files with 2,309 additions and 337 deletions.
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,8 @@ mutate:
terratest:
@ $(ECHO) " "
@ $(ECHO) "\033[1;33m=====> Running Terratest tests...\033[0m"
cd ./terratest && $(GO) test -count 1
cd ./terratest/data-sources && $(GO) test -count 1
cd ./terratest/functions && $(GO) test -count 1

.PHONY: examples
## examples: [test] Runs tests for examples. Set NAME= (without 'Example') 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.
97 changes: 55 additions & 42 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.
8 changes: 3 additions & 5 deletions corefuncprovider/env_ensure_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ package corefuncprovider
import (
"bytes"
"fmt"
"log"
"os"
"regexp"
"strings"
"testing"
"text/template"
Expand All @@ -44,7 +42,7 @@ func TestAccEnvEnsureDataSource(t *testing.T) {

err = os.Setenv(tc.EnvVarName, tc.SetValue)
if err != nil {
log.Fatalln(err)
t.Error(err)
}

buf := &bytes.Buffer{}
Expand All @@ -54,7 +52,7 @@ func TestAccEnvEnsureDataSource(t *testing.T) {

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

if os.Getenv("PROVIDER_DEBUG") != "" {
Expand Down Expand Up @@ -82,7 +80,7 @@ func TestAccEnvEnsureDataSource(t *testing.T) {
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
ExpectError: regexp.MustCompile(`environment variable (\w+) (is not defined|does not match pattern)`),
ExpectError: tc.ExpectedErrRE,
},
},
})
Expand Down
147 changes: 147 additions & 0 deletions corefuncprovider/env_ensure_function.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <[email protected]>
//
// 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"
"os"
"regexp"
"strings"

"github.com/hashicorp/terraform-plugin-framework/function"
"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 _ function.Function = &envEnsureFunction{}

type (
// envEnsureFunction is the function implementation.
envEnsureFunction struct{}
)

// EnvEnsureFunction is a method that exposes its paired Go function as a
// Terraform Function.
// https://developer.hashicorp.com/terraform/plugin/framework/functions/implementation
func EnvEnsureFunction() function.Function { // lint:allow_return_interface
return &envEnsureFunction{}
}

func (f *envEnsureFunction) Metadata(
ctx context.Context,
req function.MetadataRequest,
resp *function.MetadataResponse,
) {
tflog.Debug(ctx, "Starting EnvEnsure Function Metadata method.")

resp.Name = "env_ensure"

tflog.Debug(ctx, fmt.Sprintf("resp.Name = %s", resp.Name))

tflog.Debug(ctx, "Ending EnvEnsure Function Metadata method.")
}

// Definition defines the parameters and return type for the function.
func (f *envEnsureFunction) Definition(
ctx context.Context,
req function.DefinitionRequest,
resp *function.DefinitionResponse,
) {
tflog.Debug(ctx, "Starting EnvEnsure Function Definition method.")

resp.Definition = function.Definition{
Summary: "Ensures that a given environment variable is set to a non-empty value.",
MarkdownDescription: strings.TrimSpace(dedent.Dedent(`
Ensures that a given environment variable is set to a non-empty value.
If the environment variable is unset or if it is set to an empty string,
it will trigger a Terraform-level error.
-> Not every Terraform provider checks to ensure that the environment variables it
requires are properly set before performing work, leading to late-stage errors.
This will force an error to occur early in the execution if the environment
variable is not set, or if its value doesn't match the expected patttern.
Maps to the ` + linkPackage("EnvEnsure") + ` Go method, which can be used in
` + Terratest + `.
`)),
Parameters: []function.Parameter{
function.StringParameter{
Name: "name",
MarkdownDescription: "The name of the environment variable to check.",
},
},
VariadicParameter: function.StringParameter{
Name: "pattern",
MarkdownDescription: "A valid Go ([re2](https://github.com/google/re2/wiki/Syntax)) " +
"regular expression pattern.",
AllowNullValue: true,
},
Return: function.StringReturn{},
}

tflog.Debug(ctx, "Ending EnvEnsure Function Definition method.")
}

func (f *envEnsureFunction) Run(ctx context.Context, req function.RunRequest, resp *function.RunResponse) {
tflog.Debug(ctx, "Starting EnvEnsure Function Run method.")

var (
name string
pattern []string
)

resp.Error = function.ConcatFuncErrors(req.Arguments.Get(ctx, &name, &pattern))
if resp.Error != nil {
return
}

if len(pattern) > 0 && pattern[0] != "" {
rePattern, err := regexp.Compile(pattern[0])
if err != nil {
resp.Error = function.ConcatFuncErrors(
function.NewArgumentFuncError(1, err.Error()),
)

return
}

err = corefunc.EnvEnsure(name, rePattern)
if err != nil {
resp.Error = function.ConcatFuncErrors(
function.NewArgumentFuncError(0, err.Error()),
)

return
}
} else {
err := corefunc.EnvEnsure(name)
if err != nil {
resp.Error = function.ConcatFuncErrors(
function.NewArgumentFuncError(0, err.Error()),
)

return
}
}

value := os.Getenv(name)
resp.Error = function.ConcatFuncErrors(resp.Result.Set(ctx, value))

tflog.Debug(ctx, "Ending EnvEnsure Function Run method.")
}
9 changes: 9 additions & 0 deletions corefuncprovider/env_ensure_function_fixture.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{{ $root := . }}
output "env_var" {
{{- with .PatternStr }}
value = provider::corefunc::env_ensure("{{ $root.EnvVarName }}", "{{ . }}")
{{- else }}
value = provider::corefunc::env_ensure("{{ $root.EnvVarName }}")
{{- end }}
}
#=> {{ .ExpectedErr }}
103 changes: 103 additions & 0 deletions corefuncprovider/env_ensure_function_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright 2023-2024, Northwood Labs
// Copyright 2023-2024, Ryan Parman <[email protected]>
//
// 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"
"os"
"regexp"
"strings"
"testing"
"text/template"

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

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

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

funcName := traceFuncName()

for name, tc := range testfixtures.EnvEnsureTestTable { // lint:no_dupe
var err error

fmt.Printf(
"=== RUN %s/%s\n",
strings.TrimSpace(funcName),
strings.TrimSpace(name),
)

err = os.Setenv(tc.EnvVarName, tc.SetValue)
if err != nil {
t.Error(err)
}

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

err = tmpl.Execute(buf, tc)
if err != nil {
t.Error(err)
}

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

if tc.ExpectedErr == nil {
resource.UnitTest(t, resource.TestCase{
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.SkipBelow(
version.Must(version.NewVersion("1.7.999")),
),
},
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckOutput("env_var", tc.SetValue),
),
},
},
})
} else {
// We DO expect an error.
// https://developer.hashicorp.com/terraform/plugin/testing/testing-patterns
resource.UnitTest(t, resource.TestCase{
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.SkipBelow(
version.Must(version.NewVersion("1.7.999")),
),
},
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: providerConfig + buf.String(),
ExpectError: regexp.MustCompile(`.*`),
},
},
})
}
}
}
3 changes: 1 addition & 2 deletions corefuncprovider/homedir_expand_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package corefuncprovider // lint:no_dupe
import (
"bytes"
"fmt"
"log"
"os"
"regexp"
"strings"
Expand Down Expand Up @@ -47,7 +46,7 @@ func TestAccHomedirExpandDataSource(t *testing.T) {

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

if os.Getenv("PROVIDER_DEBUG") != "" {
Expand Down
3 changes: 1 addition & 2 deletions corefuncprovider/homedir_get_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package corefuncprovider // lint:no_dupe
import (
"bytes"
"fmt"
"log"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -46,7 +45,7 @@ func TestAccHomedirGetDataSource(t *testing.T) {

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

if os.Getenv("PROVIDER_DEBUG") != "" {
Expand Down
3 changes: 1 addition & 2 deletions corefuncprovider/int_leftpad_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package corefuncprovider // lint:no_dupe
import (
"bytes"
"fmt"
"log"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -46,7 +45,7 @@ func TestAccIntLeftpadDataSource(t *testing.T) {

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

if os.Getenv("PROVIDER_DEBUG") != "" {
Expand Down
1 change: 1 addition & 0 deletions corefuncprovider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func (p *coreFuncProvider) DataSources(ctx context.Context) []func() datasource.
// Functions defines the functions implemented in the provider.
func (p *coreFuncProvider) Functions(ctx context.Context) []func() function.Function {
return []func() function.Function{
EnvEnsureFunction,
StrSnakeFunction,
}
}
Expand Down
3 changes: 1 addition & 2 deletions corefuncprovider/runtime_cpuarch_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package corefuncprovider // lint:no_dupe
import (
"bytes"
"fmt"
"log"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -46,7 +45,7 @@ func TestAccRuntimeCpuarchDataSource(t *testing.T) {

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

if os.Getenv("PROVIDER_DEBUG") != "" {
Expand Down
Loading

0 comments on commit cea02c3

Please sign in to comment.