Skip to content

Commit

Permalink
Merge pull request #160 from maksym-nazarenko/poc-generic-crud-functions
Browse files Browse the repository at this point in the history
Poc generic crud functions
  • Loading branch information
ddelnano authored Jun 30, 2023
2 parents eb18fb3 + 88a987b commit 62355f5
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 144 deletions.
4 changes: 2 additions & 2 deletions client/bridge_vlan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
func TestBridgeVlanBasic(t *testing.T) {
c := NewClient(GetConfigFromEnv())

bridge1Name := "test_bridge1"
bridge1Name := "test_bridge1_" + RandomString()
bridge1 := &Bridge{
Name: bridge1Name,
FastForward: false,
Expand All @@ -27,7 +27,7 @@ func TestBridgeVlanBasic(t *testing.T) {
}
}()

bridge2Name := "test_bridge2"
bridge2Name := "test_bridge2_" + RandomString()
bridge2 := &Bridge{
Name: bridge2Name,
FastForward: false,
Expand Down
18 changes: 10 additions & 8 deletions client/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package client

import (
"os"
"strconv"
"testing"
"time"
)

func SkipLegacyBgpIfUnsupported(t *testing.T) {
Expand All @@ -12,10 +14,7 @@ func SkipLegacyBgpIfUnsupported(t *testing.T) {
}

func IsLegacyBgpSupported() bool {
if os.Getenv("LEGACY_BGP_SUPPORT") == "true" {
return true
}
return false
return os.Getenv("LEGACY_BGP_SUPPORT") == "true"
}

func SkipInterfaceWireguardIfUnsupported(t *testing.T) {
Expand All @@ -25,8 +24,11 @@ func SkipInterfaceWireguardIfUnsupported(t *testing.T) {
}

func IsInterfaceWireguardSupported() bool {
if os.Getenv("INTERFACE_WIREGUARD_SUPPORT") == "true" {
return true
}
return false
return os.Getenv("INTERFACE_WIREGUARD_SUPPORT") == "true"
}

// RandomString returns a random string
func RandomString() string {
// a naive implementation with all-digits for now
return strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
}
30 changes: 17 additions & 13 deletions client/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,37 +54,41 @@ func (b *Scheduler) DeleteField() string {
}

func (b *Scheduler) DeleteFieldValue() string {
return b.Name
return b.Id
}

// typed wrappers
func (client Mikrotik) AddScheduler(s *Scheduler) (*Scheduler, error) {
return client.CreateScheduler(s)
}

// Typed wrappers
func (c Mikrotik) AddScheduler(r *Scheduler) (*Scheduler, error) {
res, err := c.Add(r)
func (client Mikrotik) CreateScheduler(s *Scheduler) (*Scheduler, error) {
r, err := client.Add(s)
if err != nil {
return nil, err
}

return res.(*Scheduler), nil
return r.(*Scheduler), nil
}

func (c Mikrotik) UpdateScheduler(r *Scheduler) (*Scheduler, error) {
res, err := c.Update(r)
func (client Mikrotik) UpdateScheduler(s *Scheduler) (*Scheduler, error) {
r, err := client.Update(s)
if err != nil {
return nil, err
}

return res.(*Scheduler), nil
return r.(*Scheduler), nil
}

func (c Mikrotik) FindScheduler(name string) (*Scheduler, error) {
res, err := c.Find(&Scheduler{Name: name})
func (client Mikrotik) FindScheduler(name string) (*Scheduler, error) {
r, err := client.Find(&Scheduler{Name: name})
if err != nil {
return nil, err
}

return res.(*Scheduler), nil
return r.(*Scheduler), nil
}

func (c Mikrotik) DeleteScheduler(name string) error {
return c.Delete(&Scheduler{Name: name})
func (client Mikrotik) DeleteScheduler(name string) error {
return client.Delete(&Scheduler{Name: name})
}
23 changes: 6 additions & 17 deletions client/scheduler_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package client

import (
"reflect"
"testing"

"github.com/ddelnano/terraform-provider-mikrotik/client/types"
Expand All @@ -11,7 +10,7 @@ import (
func TestCreateUpdateDeleteAndFindScheduler(t *testing.T) {
c := NewClient(GetConfigFromEnv())

schedulerName := "scheduler"
schedulerName := "scheduler_" + RandomString()
onEvent := "onevent"
interval := 0
expectedScheduler := &Scheduler{
Expand All @@ -20,32 +19,22 @@ func TestCreateUpdateDeleteAndFindScheduler(t *testing.T) {
Interval: types.MikrotikDuration(interval),
}
scheduler, err := c.AddScheduler(expectedScheduler)

if err != nil || scheduler == nil {
t.Errorf("Error creating a scheduler with: %v and value: %v", err, scheduler)
}
require.NoError(t, err)
require.NotNil(t, scheduler)

expectedScheduler.Id = scheduler.Id
expectedScheduler.StartDate = scheduler.StartDate
expectedScheduler.StartTime = scheduler.StartTime

if !reflect.DeepEqual(scheduler, expectedScheduler) {
t.Errorf("The scheduler does not match what we expected. actual: %v expected: %v", scheduler, expectedScheduler)
}
require.Equal(t, expectedScheduler, scheduler)

// update and reassert
expectedScheduler.OnEvent = "test"
scheduler, err = c.UpdateScheduler(expectedScheduler)

if !reflect.DeepEqual(scheduler, expectedScheduler) {
t.Errorf("The updated scheduler does not match what we expected. actual: %v expected: %v", scheduler, expectedScheduler)
}
require.Equal(t, expectedScheduler, scheduler)

err = c.DeleteScheduler(schedulerName)

if err != nil {
t.Errorf("Error deleting a scheduler with: %v", err)
}
require.NoError(t, err)
}

func TestFindScheduler_onNonExistantScript(t *testing.T) {
Expand Down
117 changes: 13 additions & 104 deletions mikrotik/resource_scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ package mikrotik

import (
"context"
"fmt"

"github.com/ddelnano/terraform-provider-mikrotik/client"
"github.com/ddelnano/terraform-provider-mikrotik/client/types"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
Expand Down Expand Up @@ -91,90 +88,30 @@ func (s *scheduler) Schema(_ context.Context, _ resource.SchemaRequest, resp *re

// Create creates the resource and sets the initial Terraform state.
func (s *scheduler) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan schedulerModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
created, err := s.client.AddScheduler(modelToScheduler(&plan))
if err != nil {
resp.Diagnostics.AddError("creation failed", err.Error())
return
}

resp.Diagnostics.Append(schedulerToModel(created, &plan)...)
if resp.Diagnostics.HasError() {
return
}

resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var terraformModel schedulerModel
var mikrotikModel client.Scheduler
GenericCreateResource(&terraformModel, &mikrotikModel, s.client)(ctx, req, resp)
}

// Read refreshes the Terraform state with the latest data.
func (s *scheduler) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state schedulerModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}

resource, err := s.client.FindScheduler(state.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error reading remote resource",
fmt.Sprintf("Could not read scheduler with name %q", state.Name.ValueString()),
)
return
}

resp.Diagnostics.Append(schedulerToModel(resource, &state)...)
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var terraformModel schedulerModel
var mikrotikModel client.Scheduler
GenericReadResource(&terraformModel, &mikrotikModel, s.client)(ctx, req, resp)
}

// Update updates the resource and sets the updated Terraform state on success.
func (s *scheduler) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan schedulerModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}

updated, err := s.client.UpdateScheduler(modelToScheduler(&plan))
if err != nil {
resp.Diagnostics.AddError("update failed", err.Error())
return
}

resp.Diagnostics.Append(schedulerToModel(updated, &plan)...)
if resp.Diagnostics.HasError() {
return
}

resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var terraformModel schedulerModel
var mikrotikModel client.Scheduler
GenericUpdateResource(&terraformModel, &mikrotikModel, s.client)(ctx, req, resp)
}

// Delete deletes the resource and removes the Terraform state on success.
func (s *scheduler) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state schedulerModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}

if err := s.client.DeleteScheduler(state.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("Could not delete scheduler", err.Error())
return
}
var terraformModel schedulerModel
var mikrotikModel client.Scheduler
GenericDeleteResource(&terraformModel, &mikrotikModel, s.client)(ctx, req, resp)
}

func (s *scheduler) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
Expand All @@ -183,38 +120,10 @@ func (s *scheduler) ImportState(ctx context.Context, req resource.ImportStateReq
}

type schedulerModel struct {
ID tftypes.String `tfsdk:"id"`
Id tftypes.String `tfsdk:"id"`
Name tftypes.String `tfsdk:"name"`
OnEvent tftypes.String `tfsdk:"on_event"`
StartDate tftypes.String `tfsdk:"start_date"`
StartTime tftypes.String `tfsdk:"start_time"`
Interval tftypes.Int64 `tfsdk:"interval"`
}

func schedulerToModel(s *client.Scheduler, m *schedulerModel) diag.Diagnostics {
var diags diag.Diagnostics
if s == nil {
diags.AddError("Scheduler cannot be nil", "Cannot build model from nil object")
return diags
}

m.ID = tftypes.StringValue(s.Id)
m.Name = tftypes.StringValue(s.Name)
m.Interval = tftypes.Int64Value(int64(s.Interval))
m.OnEvent = tftypes.StringValue(s.OnEvent)
m.StartDate = tftypes.StringValue(s.StartDate)
m.StartTime = tftypes.StringValue(s.StartTime)

return diags
}

func modelToScheduler(m *schedulerModel) *client.Scheduler {
return &client.Scheduler{
Id: m.ID.ValueString(),
Name: m.Name.ValueString(),
OnEvent: m.OnEvent.ValueString(),
StartDate: m.StartDate.ValueString(),
StartTime: m.StartTime.ValueString(),
Interval: types.MikrotikDuration(m.Interval.ValueInt64()),
}
}

0 comments on commit 62355f5

Please sign in to comment.