docs: add README, per-resource examples, unit tests, CI, and pre-commit

- Add README.md with provider docs, resource/data-source reference, and
  development instructions
- Reorganize examples into per-resource-type subdirectories following
  Terraform provider conventions, add missing pypi/npm/puppet examples
- Add unit tests for helpers, HTTP client, model conversions, and
  provider registration
- Add Woodpecker CI pipelines for lint, test, and build
- Add pre-commit config with standard and Go-specific hooks
This commit is contained in:
2026-06-07 18:55:48 +10:00
parent 31057182aa
commit 7c94f06be6
23 changed files with 1872 additions and 31 deletions
+318
View File
@@ -0,0 +1,318 @@
package provider
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewAPIClient(t *testing.T) {
c := newAPIClient("http://example.com")
if c.baseURL != "http://example.com" {
t.Errorf("expected baseURL http://example.com, got %s", c.baseURL)
}
if c.httpClient == nil {
t.Error("expected non-nil httpClient")
}
}
func TestGet_Success(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
t.Errorf("expected GET, got %s", r.Method)
}
if r.URL.Path != "/api/v2/remotes/test" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"name": "test"})
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
err := c.get(context.Background(), "/api/v2/remotes/test", &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out["name"] != "test" {
t.Errorf("expected name=test, got %s", out["name"])
}
}
func TestGet_NotFound(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
err := c.get(context.Background(), "/api/v2/remotes/missing", &out)
if err == nil {
t.Fatal("expected error for 404")
}
if !isNotFound(err) {
t.Errorf("expected notFoundError, got %T: %v", err, err)
}
}
func TestGet_ServerError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "internal server error")
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
err := c.get(context.Background(), "/api/v2/remotes/fail", &out)
if err == nil {
t.Fatal("expected error for 500")
}
if isNotFound(err) {
t.Error("500 should not be notFoundError")
}
expected := "api error 500: internal server error"
if err.Error() != expected {
t.Errorf("expected error %q, got %q", expected, err.Error())
}
}
func TestPost_Success(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("expected POST, got %s", r.Method)
}
if r.Header.Get("Content-Type") != "application/json" {
t.Error("expected Content-Type application/json")
}
// Decode the request body and echo it back
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(body)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
input := map[string]string{"name": "new-remote"}
var out map[string]string
err := c.post(context.Background(), "/api/v2/remotes", input, &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out["name"] != "new-remote" {
t.Errorf("expected name=new-remote, got %s", out["name"])
}
}
func TestPut_Success(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
t.Errorf("expected PUT, got %s", r.Method)
}
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(body)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
input := map[string]string{"name": "updated"}
var out map[string]string
err := c.put(context.Background(), "/api/v2/remotes/updated", input, &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out["name"] != "updated" {
t.Errorf("expected name=updated, got %s", out["name"])
}
}
func TestDel_Success(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
t.Errorf("expected DELETE, got %s", r.Method)
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
err := c.del(context.Background(), "/api/v2/remotes/test")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestDel_NotFound(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
err := c.del(context.Background(), "/api/v2/remotes/missing")
if err == nil {
t.Fatal("expected error for 404")
}
if !isNotFound(err) {
t.Errorf("expected notFoundError, got %T", err)
}
}
func TestDo_BadRequest(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "invalid input")
}))
defer srv.Close()
c := newAPIClient(srv.URL)
err := c.do(context.Background(), http.MethodPost, "/api/v2/remotes", map[string]string{"bad": "data"}, nil)
if err == nil {
t.Fatal("expected error for 400")
}
expected := "api error 400: invalid input"
if err.Error() != expected {
t.Errorf("expected %q, got %q", expected, err.Error())
}
}
func TestDo_NoContent(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
// Should not attempt to decode 204 even with out pointer
err := c.do(context.Background(), http.MethodDelete, "/test", nil, &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestDo_JSONEncoding(t *testing.T) {
type payload struct {
Name string `json:"name"`
Count int `json:"count"`
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var p payload
if err := json.Unmarshal(body, &p); err != nil {
t.Errorf("failed to decode request body: %v", err)
}
if p.Name != "test" || p.Count != 42 {
t.Errorf("unexpected payload: %+v", p)
}
// Return a different payload
resp := payload{Name: "response", Count: 99}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}))
defer srv.Close()
c := newAPIClient(srv.URL)
input := payload{Name: "test", Count: 42}
var out payload
err := c.post(context.Background(), "/test", input, &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.Name != "response" || out.Count != 99 {
t.Errorf("unexpected response: %+v", out)
}
}
func TestNotFoundError_Error(t *testing.T) {
e := &notFoundError{path: "/api/v2/remotes/test"}
expected := "not found: /api/v2/remotes/test"
if e.Error() != expected {
t.Errorf("expected %q, got %q", expected, e.Error())
}
}
func TestIsNotFound_True(t *testing.T) {
err := &notFoundError{path: "/test"}
if !isNotFound(err) {
t.Error("expected isNotFound to return true for *notFoundError")
}
}
func TestIsNotFound_False(t *testing.T) {
err := fmt.Errorf("some other error")
if isNotFound(err) {
t.Error("expected isNotFound to return false for non-notFoundError")
}
}
func TestIsNotFound_Nil(t *testing.T) {
if isNotFound(nil) {
t.Error("expected isNotFound to return false for nil")
}
}
func TestIsNotFound_WrappedError(t *testing.T) {
// isNotFound uses type assertion, not errors.As, so a wrapped notFoundError should NOT match
inner := &notFoundError{path: "/test"}
wrapped := fmt.Errorf("wrapped: %w", inner)
// The current implementation uses type assertion, so wrapped should be false
if isNotFound(wrapped) {
t.Error("expected isNotFound to return false for wrapped notFoundError (uses type assertion)")
}
// But errors.As would find it
var nfe *notFoundError
if !errors.As(wrapped, &nfe) {
t.Error("errors.As should find wrapped notFoundError")
}
}
func TestGet_DecodeError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, "not valid json")
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
err := c.get(context.Background(), "/test", &out)
if err == nil {
t.Fatal("expected error for invalid JSON response")
}
}
func TestDo_NilBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "" {
t.Error("Content-Type should not be set for nil body")
}
if r.Body != nil {
body, _ := io.ReadAll(r.Body)
if len(body) > 0 {
t.Errorf("expected empty body, got %s", string(body))
}
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "{}")
}))
defer srv.Close()
c := newAPIClient(srv.URL)
var out map[string]string
err := c.get(context.Background(), "/test", &out)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
+105
View File
@@ -0,0 +1,105 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestListToStrings_NullList(t *testing.T) {
ctx := context.Background()
null := types.ListNull(types.StringType)
result := listToStrings(ctx, null)
if result != nil {
t.Fatalf("expected nil for null list, got %v", result)
}
}
func TestListToStrings_UnknownList(t *testing.T) {
ctx := context.Background()
unknown := types.ListUnknown(types.StringType)
result := listToStrings(ctx, unknown)
if result != nil {
t.Fatalf("expected nil for unknown list, got %v", result)
}
}
func TestListToStrings_EmptyList(t *testing.T) {
ctx := context.Background()
list, diags := types.ListValueFrom(ctx, types.StringType, []types.String{})
if diags.HasError() {
t.Fatalf("unexpected diags: %v", diags)
}
result := listToStrings(ctx, list)
if len(result) != 0 {
t.Fatalf("expected empty slice, got %v", result)
}
}
func TestListToStrings_WithValues(t *testing.T) {
ctx := context.Background()
elems := []types.String{
types.StringValue("alpha"),
types.StringValue("beta"),
types.StringValue("gamma"),
}
list, diags := types.ListValueFrom(ctx, types.StringType, elems)
if diags.HasError() {
t.Fatalf("unexpected diags: %v", diags)
}
result := listToStrings(ctx, list)
if len(result) != 3 {
t.Fatalf("expected 3 elements, got %d", len(result))
}
expected := []string{"alpha", "beta", "gamma"}
for i, v := range result {
if v != expected[i] {
t.Errorf("index %d: expected %q, got %q", i, expected[i], v)
}
}
}
func TestStringsToList_EmptySlice(t *testing.T) {
ctx := context.Background()
result := stringsToList(ctx, []string{})
if !result.IsNull() {
t.Fatalf("expected null list for empty slice, got %v", result)
}
}
func TestStringsToList_NilSlice(t *testing.T) {
ctx := context.Background()
result := stringsToList(ctx, nil)
if !result.IsNull() {
t.Fatalf("expected null list for nil slice, got %v", result)
}
}
func TestStringsToList_WithValues(t *testing.T) {
ctx := context.Background()
result := stringsToList(ctx, []string{"one", "two", "three"})
if result.IsNull() || result.IsUnknown() {
t.Fatalf("expected non-null non-unknown list, got null=%v unknown=%v", result.IsNull(), result.IsUnknown())
}
// Round-trip: convert back and verify
back := listToStrings(ctx, result)
if len(back) != 3 {
t.Fatalf("expected 3 elements after round-trip, got %d", len(back))
}
expected := []string{"one", "two", "three"}
for i, v := range back {
if v != expected[i] {
t.Errorf("round-trip index %d: expected %q, got %q", i, expected[i], v)
}
}
}
func TestStringsToList_SingleValue(t *testing.T) {
ctx := context.Background()
result := stringsToList(ctx, []string{"solo"})
back := listToStrings(ctx, result)
if len(back) != 1 || back[0] != "solo" {
t.Fatalf("expected [\"solo\"], got %v", back)
}
}
+164
View File
@@ -0,0 +1,164 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/datasource"
fwprovider "github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/resource"
)
func TestNew_ReturnsFactory(t *testing.T) {
factory := New("1.0.0")
if factory == nil {
t.Fatal("expected non-nil factory")
}
p := factory()
if p == nil {
t.Fatal("expected non-nil provider")
}
_, ok := p.(*ArtifactAPIProvider)
if !ok {
t.Fatalf("expected *ArtifactAPIProvider, got %T", p)
}
}
func TestNew_VersionPropagated(t *testing.T) {
factory := New("2.3.4")
p := factory().(*ArtifactAPIProvider)
if p.version != "2.3.4" {
t.Errorf("expected version 2.3.4, got %s", p.version)
}
}
func TestProvider_Metadata(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.2.3"}
req := fwprovider.MetadataRequest{}
var resp fwprovider.MetadataResponse
p.Metadata(context.Background(), req, &resp)
if resp.TypeName != "artifactapi" {
t.Errorf("expected type name 'artifactapi', got %s", resp.TypeName)
}
if resp.Version != "1.2.3" {
t.Errorf("expected version '1.2.3', got %s", resp.Version)
}
}
func TestProvider_Schema(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
req := fwprovider.SchemaRequest{}
var resp fwprovider.SchemaResponse
p.Schema(context.Background(), req, &resp)
if resp.Schema.Description == "" {
t.Error("expected non-empty schema description")
}
_, ok := resp.Schema.Attributes["endpoint"]
if !ok {
t.Fatal("missing 'endpoint' attribute in schema")
}
}
func TestProvider_Resources(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
resources := p.Resources(context.Background())
// 10 remote resource types + 1 virtual = 11
expectedCount := 11
if len(resources) != expectedCount {
t.Fatalf("expected %d resources, got %d", expectedCount, len(resources))
}
// Verify each factory produces a valid resource
for i, factory := range resources {
r := factory()
if r == nil {
t.Errorf("resource factory %d returned nil", i)
}
}
}
func TestProvider_Resources_ContainsExpectedTypes(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
resources := p.Resources(context.Background())
// Collect type names by calling Metadata on each
typeNames := make(map[string]bool)
for _, factory := range resources {
r := factory()
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
typeNames[resp.TypeName] = true
}
expected := []string{
"artifactapi_remote_generic",
"artifactapi_remote_docker",
"artifactapi_remote_helm",
"artifactapi_remote_pypi",
"artifactapi_remote_npm",
"artifactapi_remote_rpm",
"artifactapi_remote_alpine",
"artifactapi_remote_puppet",
"artifactapi_remote_terraform",
"artifactapi_remote_goproxy",
"artifactapi_virtual",
}
for _, name := range expected {
if !typeNames[name] {
t.Errorf("missing expected resource type: %s", name)
}
}
}
func TestProvider_DataSources(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
dataSources := p.DataSources(context.Background())
expectedCount := 2
if len(dataSources) != expectedCount {
t.Fatalf("expected %d data sources, got %d", expectedCount, len(dataSources))
}
// Verify each factory produces a valid data source
for i, factory := range dataSources {
ds := factory()
if ds == nil {
t.Errorf("data source factory %d returned nil", i)
}
}
}
func TestProvider_DataSources_ContainsExpectedTypes(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
dataSources := p.DataSources(context.Background())
typeNames := make(map[string]bool)
for _, factory := range dataSources {
ds := factory()
req := datasource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp datasource.MetadataResponse
ds.Metadata(context.Background(), req, &resp)
typeNames[resp.TypeName] = true
}
expected := []string{
"artifactapi_remote",
"artifactapi_virtual",
}
for _, name := range expected {
if !typeNames[name] {
t.Errorf("missing expected data source type: %s", name)
}
}
}
func TestProvider_ImplementsInterface(t *testing.T) {
var _ fwprovider.Provider = &ArtifactAPIProvider{}
}
+447
View File
@@ -0,0 +1,447 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestModelToAPI_FullFields(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "docker"}
model := remoteResourceModel{
Name: types.StringValue("my-remote"),
BaseURL: types.StringValue("https://registry.example.com"),
Description: types.StringValue("A test remote"),
Username: types.StringValue("user"),
Password: types.StringValue("pass"),
ImmutableTTL: types.Int64Value(86400),
MutableTTL: types.Int64Value(3600),
CheckMutable: types.BoolValue(true),
Patterns: stringsToList(ctx, []string{"*.tar.gz", "*.whl"}),
Blocklist: stringsToList(ctx, []string{"blocked/*"}),
MutablePatterns: stringsToList(ctx, []string{"latest"}),
ImmutablePatterns: stringsToList(ctx, []string{"v*"}),
BanTagsEnabled: types.BoolValue(true),
BanTags: stringsToList(ctx, []string{"latest", "dev"}),
QuarantineEnabled: types.BoolValue(true),
QuarantineDays: types.Int64Value(7),
StaleOnError: types.BoolValue(false),
ReleasesRemote: types.StringValue("cdn-remote"),
}
api := r.modelToAPI(ctx, model)
if api.Name != "my-remote" {
t.Errorf("Name: expected my-remote, got %s", api.Name)
}
if api.PackageType != "docker" {
t.Errorf("PackageType: expected docker, got %s", api.PackageType)
}
if api.BaseURL != "https://registry.example.com" {
t.Errorf("BaseURL: expected https://registry.example.com, got %s", api.BaseURL)
}
if api.Description != "A test remote" {
t.Errorf("Description: expected 'A test remote', got %s", api.Description)
}
if api.Username != "user" {
t.Errorf("Username: expected user, got %s", api.Username)
}
if api.Password != "pass" {
t.Errorf("Password: expected pass, got %s", api.Password)
}
if api.ImmutableTTL != 86400 {
t.Errorf("ImmutableTTL: expected 86400, got %d", api.ImmutableTTL)
}
if api.MutableTTL != 3600 {
t.Errorf("MutableTTL: expected 3600, got %d", api.MutableTTL)
}
if !api.CheckMutable {
t.Error("CheckMutable: expected true")
}
if len(api.Patterns) != 2 || api.Patterns[0] != "*.tar.gz" {
t.Errorf("Patterns: expected [*.tar.gz *.whl], got %v", api.Patterns)
}
if len(api.Blocklist) != 1 || api.Blocklist[0] != "blocked/*" {
t.Errorf("Blocklist: expected [blocked/*], got %v", api.Blocklist)
}
if len(api.MutablePatterns) != 1 || api.MutablePatterns[0] != "latest" {
t.Errorf("MutablePatterns: expected [latest], got %v", api.MutablePatterns)
}
if len(api.ImmutablePatterns) != 1 || api.ImmutablePatterns[0] != "v*" {
t.Errorf("ImmutablePatterns: expected [v*], got %v", api.ImmutablePatterns)
}
if !api.BanTagsEnabled {
t.Error("BanTagsEnabled: expected true")
}
if len(api.BanTags) != 2 || api.BanTags[0] != "latest" {
t.Errorf("BanTags: expected [latest dev], got %v", api.BanTags)
}
if !api.QuarantineEnabled {
t.Error("QuarantineEnabled: expected true")
}
if api.QuarantineDays != 7 {
t.Errorf("QuarantineDays: expected 7, got %d", api.QuarantineDays)
}
if api.StaleOnError {
t.Error("StaleOnError: expected false")
}
if api.ReleasesRemote != "cdn-remote" {
t.Errorf("ReleasesRemote: expected cdn-remote, got %s", api.ReleasesRemote)
}
}
func TestModelToAPI_NullLists(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "generic"}
model := remoteResourceModel{
Name: types.StringValue("minimal"),
BaseURL: types.StringValue("https://example.com"),
Description: types.StringValue(""),
Username: types.StringValue(""),
Password: types.StringValue(""),
ImmutableTTL: types.Int64Value(0),
MutableTTL: types.Int64Value(3600),
CheckMutable: types.BoolValue(true),
Patterns: types.ListNull(types.StringType),
Blocklist: types.ListNull(types.StringType),
MutablePatterns: types.ListNull(types.StringType),
ImmutablePatterns: types.ListNull(types.StringType),
BanTagsEnabled: types.BoolValue(false),
BanTags: types.ListNull(types.StringType),
QuarantineEnabled: types.BoolValue(false),
QuarantineDays: types.Int64Value(3),
StaleOnError: types.BoolValue(true),
ReleasesRemote: types.StringValue(""),
}
api := r.modelToAPI(ctx, model)
if api.Patterns != nil {
t.Errorf("Patterns: expected nil, got %v", api.Patterns)
}
if api.Blocklist != nil {
t.Errorf("Blocklist: expected nil, got %v", api.Blocklist)
}
if api.MutablePatterns != nil {
t.Errorf("MutablePatterns: expected nil, got %v", api.MutablePatterns)
}
if api.ImmutablePatterns != nil {
t.Errorf("ImmutablePatterns: expected nil, got %v", api.ImmutablePatterns)
}
if api.BanTags != nil {
t.Errorf("BanTags: expected nil, got %v", api.BanTags)
}
}
func TestModelToAPI_PackageTypeFromResource(t *testing.T) {
ctx := context.Background()
tests := []struct {
pkgType string
}{
{"generic"},
{"docker"},
{"helm"},
{"pypi"},
{"npm"},
{"rpm"},
{"alpine"},
{"puppet"},
{"terraform"},
{"goproxy"},
}
for _, tt := range tests {
t.Run(tt.pkgType, func(t *testing.T) {
r := &remoteResource{packageType: tt.pkgType}
model := remoteResourceModel{
Name: types.StringValue("test"),
BaseURL: types.StringValue("https://example.com"),
Description: types.StringValue(""),
Username: types.StringValue(""),
Password: types.StringValue(""),
ImmutableTTL: types.Int64Value(0),
MutableTTL: types.Int64Value(0),
CheckMutable: types.BoolValue(false),
Patterns: types.ListNull(types.StringType),
Blocklist: types.ListNull(types.StringType),
MutablePatterns: types.ListNull(types.StringType),
ImmutablePatterns: types.ListNull(types.StringType),
BanTagsEnabled: types.BoolValue(false),
BanTags: types.ListNull(types.StringType),
QuarantineEnabled: types.BoolValue(false),
QuarantineDays: types.Int64Value(0),
StaleOnError: types.BoolValue(false),
ReleasesRemote: types.StringValue(""),
}
api := r.modelToAPI(ctx, model)
if api.PackageType != tt.pkgType {
t.Errorf("expected package_type %s, got %s", tt.pkgType, api.PackageType)
}
})
}
}
func TestAPIToModel_FullFields(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "docker"}
api := remoteAPI{
Name: "my-remote",
PackageType: "docker",
BaseURL: "https://registry.example.com",
Description: "A test remote",
Username: "user",
Password: "pass",
ImmutableTTL: 86400,
MutableTTL: 3600,
CheckMutable: true,
Patterns: []string{"*.tar.gz"},
Blocklist: []string{"blocked/*"},
MutablePatterns: []string{"latest"},
ImmutablePatterns: []string{"v*"},
BanTagsEnabled: true,
BanTags: []string{"latest"},
QuarantineEnabled: true,
QuarantineDays: 7,
StaleOnError: false,
ReleasesRemote: "cdn-remote",
ManagedBy: "terraform",
}
model := r.apiToModel(ctx, api)
if model.Name.ValueString() != "my-remote" {
t.Errorf("Name: expected my-remote, got %s", model.Name.ValueString())
}
if model.BaseURL.ValueString() != "https://registry.example.com" {
t.Errorf("BaseURL: expected https://registry.example.com, got %s", model.BaseURL.ValueString())
}
if model.Description.ValueString() != "A test remote" {
t.Errorf("Description: expected 'A test remote', got %s", model.Description.ValueString())
}
if model.Username.ValueString() != "user" {
t.Errorf("Username: expected user, got %s", model.Username.ValueString())
}
if model.Password.ValueString() != "pass" {
t.Errorf("Password: expected pass, got %s", model.Password.ValueString())
}
if model.ImmutableTTL.ValueInt64() != 86400 {
t.Errorf("ImmutableTTL: expected 86400, got %d", model.ImmutableTTL.ValueInt64())
}
if model.MutableTTL.ValueInt64() != 3600 {
t.Errorf("MutableTTL: expected 3600, got %d", model.MutableTTL.ValueInt64())
}
if !model.CheckMutable.ValueBool() {
t.Error("CheckMutable: expected true")
}
if !model.QuarantineEnabled.ValueBool() {
t.Error("QuarantineEnabled: expected true")
}
if model.QuarantineDays.ValueInt64() != 7 {
t.Errorf("QuarantineDays: expected 7, got %d", model.QuarantineDays.ValueInt64())
}
if model.StaleOnError.ValueBool() {
t.Error("StaleOnError: expected false")
}
if !model.BanTagsEnabled.ValueBool() {
t.Error("BanTagsEnabled: expected true")
}
if model.ReleasesRemote.ValueString() != "cdn-remote" {
t.Errorf("ReleasesRemote: expected cdn-remote, got %s", model.ReleasesRemote.ValueString())
}
// Verify list fields via round-trip
patterns := listToStrings(ctx, model.Patterns)
if len(patterns) != 1 || patterns[0] != "*.tar.gz" {
t.Errorf("Patterns: expected [*.tar.gz], got %v", patterns)
}
blocklist := listToStrings(ctx, model.Blocklist)
if len(blocklist) != 1 || blocklist[0] != "blocked/*" {
t.Errorf("Blocklist: expected [blocked/*], got %v", blocklist)
}
banTags := listToStrings(ctx, model.BanTags)
if len(banTags) != 1 || banTags[0] != "latest" {
t.Errorf("BanTags: expected [latest], got %v", banTags)
}
}
func TestAPIToModel_EmptyLists(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "generic"}
api := remoteAPI{
Name: "minimal",
PackageType: "generic",
BaseURL: "https://example.com",
// All lists are nil/empty
}
model := r.apiToModel(ctx, api)
if !model.Patterns.IsNull() {
t.Errorf("Patterns: expected null for nil input, got %v", model.Patterns)
}
if !model.Blocklist.IsNull() {
t.Errorf("Blocklist: expected null for nil input, got %v", model.Blocklist)
}
if !model.MutablePatterns.IsNull() {
t.Errorf("MutablePatterns: expected null for nil input, got %v", model.MutablePatterns)
}
if !model.ImmutablePatterns.IsNull() {
t.Errorf("ImmutablePatterns: expected null for nil input, got %v", model.ImmutablePatterns)
}
if !model.BanTags.IsNull() {
t.Errorf("BanTags: expected null for nil input, got %v", model.BanTags)
}
}
func TestModelToAPI_RoundTrip(t *testing.T) {
ctx := context.Background()
r := &remoteResource{packageType: "helm"}
original := remoteAPI{
Name: "helm-remote",
PackageType: "helm",
BaseURL: "https://charts.example.com",
Description: "Helm chart mirror",
Username: "helmuser",
Password: "helmpass",
ImmutableTTL: 172800,
MutableTTL: 7200,
CheckMutable: true,
Patterns: []string{"stable/*", "incubator/*"},
Blocklist: []string{"deprecated/*"},
MutablePatterns: []string{"latest"},
ImmutablePatterns: []string{"v1.*"},
BanTagsEnabled: false,
BanTags: nil,
QuarantineEnabled: false,
QuarantineDays: 3,
StaleOnError: true,
ReleasesRemote: "",
}
// API -> Model -> API round-trip
model := r.apiToModel(ctx, original)
result := r.modelToAPI(ctx, model)
if result.Name != original.Name {
t.Errorf("Name: expected %s, got %s", original.Name, result.Name)
}
if result.PackageType != original.PackageType {
t.Errorf("PackageType: expected %s, got %s", original.PackageType, result.PackageType)
}
if result.BaseURL != original.BaseURL {
t.Errorf("BaseURL: expected %s, got %s", original.BaseURL, result.BaseURL)
}
if result.Description != original.Description {
t.Errorf("Description: expected %s, got %s", original.Description, result.Description)
}
if result.ImmutableTTL != original.ImmutableTTL {
t.Errorf("ImmutableTTL: expected %d, got %d", original.ImmutableTTL, result.ImmutableTTL)
}
if result.MutableTTL != original.MutableTTL {
t.Errorf("MutableTTL: expected %d, got %d", original.MutableTTL, result.MutableTTL)
}
if result.CheckMutable != original.CheckMutable {
t.Errorf("CheckMutable: expected %v, got %v", original.CheckMutable, result.CheckMutable)
}
if len(result.Patterns) != len(original.Patterns) {
t.Errorf("Patterns length: expected %d, got %d", len(original.Patterns), len(result.Patterns))
}
for i := range original.Patterns {
if result.Patterns[i] != original.Patterns[i] {
t.Errorf("Patterns[%d]: expected %s, got %s", i, original.Patterns[i], result.Patterns[i])
}
}
if result.QuarantineDays != original.QuarantineDays {
t.Errorf("QuarantineDays: expected %d, got %d", original.QuarantineDays, result.QuarantineDays)
}
if result.StaleOnError != original.StaleOnError {
t.Errorf("StaleOnError: expected %v, got %v", original.StaleOnError, result.StaleOnError)
}
}
func TestRemoteResource_Metadata(t *testing.T) {
tests := []struct {
pkgType string
expected string
}{
{"generic", "artifactapi_remote_generic"},
{"docker", "artifactapi_remote_docker"},
{"helm", "artifactapi_remote_helm"},
{"pypi", "artifactapi_remote_pypi"},
{"npm", "artifactapi_remote_npm"},
}
for _, tt := range tests {
t.Run(tt.pkgType, func(t *testing.T) {
r := &remoteResource{packageType: tt.pkgType}
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
if resp.TypeName != tt.expected {
t.Errorf("expected %s, got %s", tt.expected, resp.TypeName)
}
})
}
}
func TestRemoteResource_Schema(t *testing.T) {
r := &remoteResource{packageType: "docker"}
req := resource.SchemaRequest{}
var resp resource.SchemaResponse
r.Schema(context.Background(), req, &resp)
expectedAttrs := []string{
"name", "base_url", "description", "username", "password",
"immutable_ttl", "mutable_ttl", "check_mutable",
"patterns", "blocklist", "mutable_patterns", "immutable_patterns",
"ban_tags_enabled", "ban_tags",
"quarantine_enabled", "quarantine_days",
"stale_on_error", "releases_remote",
}
for _, attr := range expectedAttrs {
if _, ok := resp.Schema.Attributes[attr]; !ok {
t.Errorf("missing expected attribute: %s", attr)
}
}
}
func TestNewRemoteResource_Constructors(t *testing.T) {
tests := []struct {
name string
fn func() resource.Resource
expected string
}{
{"generic", func() resource.Resource { return NewRemoteGeneric() }, "generic"},
{"docker", func() resource.Resource { return NewRemoteDocker() }, "docker"},
{"helm", func() resource.Resource { return NewRemoteHelm() }, "helm"},
{"pypi", func() resource.Resource { return NewRemotePyPI() }, "pypi"},
{"npm", func() resource.Resource { return NewRemoteNPM() }, "npm"},
{"rpm", func() resource.Resource { return NewRemoteRPM() }, "rpm"},
{"alpine", func() resource.Resource { return NewRemoteAlpine() }, "alpine"},
{"puppet", func() resource.Resource { return NewRemotePuppet() }, "puppet"},
{"terraform", func() resource.Resource { return NewRemoteTerraform() }, "terraform"},
{"goproxy", func() resource.Resource { return NewRemoteGoProxy() }, "goproxy"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := tt.fn()
rr, ok := r.(*remoteResource)
if !ok {
t.Fatal("expected *remoteResource")
}
if rr.packageType != tt.expected {
t.Errorf("expected packageType %s, got %s", tt.expected, rr.packageType)
}
})
}
}
+167
View File
@@ -0,0 +1,167 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestVirtualModelToAPI(t *testing.T) {
ctx := context.Background()
model := virtualResourceModel{
Name: types.StringValue("my-virtual"),
PackageType: types.StringValue("helm"),
Description: types.StringValue("Virtual helm repo"),
Members: stringsToList(ctx, []string{"remote-a", "remote-b"}),
}
api := virtualModelToAPI(ctx, model)
if api.Name != "my-virtual" {
t.Errorf("Name: expected my-virtual, got %s", api.Name)
}
if api.PackageType != "helm" {
t.Errorf("PackageType: expected helm, got %s", api.PackageType)
}
if api.Description != "Virtual helm repo" {
t.Errorf("Description: expected 'Virtual helm repo', got %s", api.Description)
}
if len(api.Members) != 2 {
t.Fatalf("Members: expected 2, got %d", len(api.Members))
}
if api.Members[0] != "remote-a" || api.Members[1] != "remote-b" {
t.Errorf("Members: expected [remote-a remote-b], got %v", api.Members)
}
}
func TestVirtualModelToAPI_NullMembers(t *testing.T) {
ctx := context.Background()
model := virtualResourceModel{
Name: types.StringValue("no-members"),
PackageType: types.StringValue("pypi"),
Description: types.StringValue(""),
Members: types.ListNull(types.StringType),
}
api := virtualModelToAPI(ctx, model)
if api.Members != nil {
t.Errorf("Members: expected nil for null list, got %v", api.Members)
}
}
func TestVirtualAPIToModel(t *testing.T) {
ctx := context.Background()
api := virtualAPI{
Name: "my-virtual",
PackageType: "helm",
Description: "Virtual helm repo",
Members: []string{"remote-a", "remote-b"},
ManagedBy: "terraform",
}
model := virtualAPIToModel(ctx, api)
if model.Name.ValueString() != "my-virtual" {
t.Errorf("Name: expected my-virtual, got %s", model.Name.ValueString())
}
if model.PackageType.ValueString() != "helm" {
t.Errorf("PackageType: expected helm, got %s", model.PackageType.ValueString())
}
if model.Description.ValueString() != "Virtual helm repo" {
t.Errorf("Description: expected 'Virtual helm repo', got %s", model.Description.ValueString())
}
members := listToStrings(ctx, model.Members)
if len(members) != 2 {
t.Fatalf("Members: expected 2, got %d", len(members))
}
if members[0] != "remote-a" || members[1] != "remote-b" {
t.Errorf("Members: expected [remote-a remote-b], got %v", members)
}
}
func TestVirtualAPIToModel_EmptyMembers(t *testing.T) {
ctx := context.Background()
api := virtualAPI{
Name: "empty-members",
PackageType: "pypi",
Members: nil,
}
model := virtualAPIToModel(ctx, api)
if !model.Members.IsNull() {
t.Errorf("Members: expected null for nil/empty slice, got %v", model.Members)
}
}
func TestVirtualRoundTrip(t *testing.T) {
ctx := context.Background()
original := virtualAPI{
Name: "roundtrip-virtual",
PackageType: "helm",
Description: "Round trip test",
Members: []string{"a", "b", "c"},
}
model := virtualAPIToModel(ctx, original)
result := virtualModelToAPI(ctx, model)
if result.Name != original.Name {
t.Errorf("Name: expected %s, got %s", original.Name, result.Name)
}
if result.PackageType != original.PackageType {
t.Errorf("PackageType: expected %s, got %s", original.PackageType, result.PackageType)
}
if result.Description != original.Description {
t.Errorf("Description: expected %s, got %s", original.Description, result.Description)
}
if len(result.Members) != len(original.Members) {
t.Fatalf("Members length: expected %d, got %d", len(original.Members), len(result.Members))
}
for i := range original.Members {
if result.Members[i] != original.Members[i] {
t.Errorf("Members[%d]: expected %s, got %s", i, original.Members[i], result.Members[i])
}
}
}
func TestVirtualResource_Metadata(t *testing.T) {
r := NewVirtualResource()
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
if resp.TypeName != "artifactapi_virtual" {
t.Errorf("expected artifactapi_virtual, got %s", resp.TypeName)
}
}
func TestVirtualResource_Schema(t *testing.T) {
r := NewVirtualResource()
req := resource.SchemaRequest{}
var resp resource.SchemaResponse
r.Schema(context.Background(), req, &resp)
expectedAttrs := []string{"name", "package_type", "description", "members"}
for _, attr := range expectedAttrs {
if _, ok := resp.Schema.Attributes[attr]; !ok {
t.Errorf("missing expected attribute: %s", attr)
}
}
}
func TestNewVirtualResource_Type(t *testing.T) {
r := NewVirtualResource()
_, ok := r.(*virtualResource)
if !ok {
t.Error("expected *virtualResource")
}
}