Skip to content

Commit

Permalink
Fix issues and increase unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
ahelmy committed Jan 27, 2024
1 parent 42d5040 commit c8e96b9
Show file tree
Hide file tree
Showing 25 changed files with 202 additions and 90 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
go.work

.vscode/

.idea/
coverage.txt
coverage.html
8 changes: 0 additions & 8 deletions .idea/.gitignore

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/modules.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

9 changes: 0 additions & 9 deletions .idea/xdev.iml

This file was deleted.

16 changes: 16 additions & 0 deletions api/properties_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,21 @@ func TestPropertiesAPI(t *testing.T) {
assert.NoError(t, err)
assert.False(t, response.Success)
})
t.Run("Properties2Yaml Error", func(t *testing.T) {
propertiesRequest := PropertiesRequest{
Properties: "x\n",
}
requestBody, _ := json.Marshal(propertiesRequest)

req := httptest.NewRequest(http.MethodPost, "/api/properties", bytes.NewReader(requestBody))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)

var response Response
err = json.NewDecoder(resp.Body).Decode(&response)
assert.NoError(t, err)
assert.False(t, response.Success)
})
}
30 changes: 30 additions & 0 deletions api/yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"

"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/assert"
)

func TestYamlAPI(t *testing.T) {
Expand Down Expand Up @@ -149,4 +150,33 @@ func TestYamlAPI(t *testing.T) {
t.Errorf("Unexpected response data: %+v", response)
}
})

t.Run("Test YAML to Properties conversion - invalid req", func(t *testing.T) {
requestBody := `x{"yaml": "c"}`

// Create a new request
req := httptest.NewRequest(http.MethodPost, "/api/yaml?action=to_properties", strings.NewReader(requestBody))
req.Header.Set("Content-Type", "application/json")

// Perform the request
resp, err := app.Test(req)
if err != nil {
t.Fatalf("Failed to perform request: %v", err)
}
defer resp.Body.Close()

// Check the response status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status code %d, but got %d", http.StatusOK, resp.StatusCode)
}

// Parse the response body
var response Response
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
t.Fatalf("Failed to parse response body: %v", err)
}

assert.Equal(t, false, response.Success)
})
}
20 changes: 19 additions & 1 deletion internal/properties_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package internal

import (
"github.com/stretchr/testify/assert"
"testing"

"github.com/stretchr/testify/assert"
)

func TestProperties2Yaml(t *testing.T) {
Expand Down Expand Up @@ -43,3 +44,20 @@ func TestProperties2Yaml(t *testing.T) {
})
}
}

func TestPropertiesErrors(t *testing.T) {
t.Run("Invalid Properties", func(t *testing.T) {
_, err := Properties2Yaml("x[0=aaa")
if err != nil {
t.Errorf("Unexpected error status. Got error: %v, expected error: %v", err, false)
}
})

t.Run("Invalid Properties - invalid array key", func(t *testing.T) {
_, err := Properties2Yaml("x[yz]=aaa")
if err == nil {
t.Errorf("Unexpected error status. Got error: %v, expected error: %v", err, false)
}
})

}
25 changes: 19 additions & 6 deletions internal/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,16 @@ func Now(format string, timeZone *string) (Time, error) {
return Time{UTC: t.UTC().Format(format), YourTimezone: t.Format(format), Epoch: t.Unix()}, nil
}

var yourTZ string

location, err := time.LoadLocation(*timeZone)
if err != nil {
return Time{}, err
yourTZ = t.Format(format)
} else {
yourTZ = t.In(location).Format(format)
}
return Time{UTC: t.UTC().Format(format), YourTimezone: t.In(location).Format(format), Epoch: t.Unix()}, nil

return Time{UTC: t.UTC().Format(format), YourTimezone: yourTZ, Epoch: t.Unix()}, nil
}

func ConvertTimeFromEpoch(epoch int64, format string, timeZone *string) Time {
Expand All @@ -67,12 +72,16 @@ func ConvertTimeFromEpoch(epoch int64, format string, timeZone *string) Time {
return Time{UTC: t.UTC().Format(format), YourTimezone: t.Format(format), Epoch: t.Unix()}
}

var yourTZ string

location, err := time.LoadLocation(*timeZone)
if err != nil {
return Time{}
yourTZ = t.Format(format)
} else {
yourTZ = t.In(location).Format(format)
}

return Time{UTC: t.UTC().Format(format), YourTimezone: t.In(location).Format(format), Epoch: t.Unix()}
return Time{UTC: t.UTC().Format(format), YourTimezone: yourTZ, Epoch: t.Unix()}
}

func ConvertTimeFromFormat(datetime string, fromFormat string, toFormat string, timeZone *string) (Time, error) {
Expand All @@ -85,10 +94,14 @@ func ConvertTimeFromFormat(datetime string, fromFormat string, toFormat string,
return Time{UTC: t.UTC().Format(toFormat), YourTimezone: t.Format(toFormat), Epoch: t.Unix()}, nil
}

var yourTZ string

location, err := time.LoadLocation(*timeZone)
if err != nil {
return Time{}, err
yourTZ = t.Format(toFormat)
} else {
yourTZ = t.In(location).Format(toFormat)
}

return Time{UTC: t.UTC().Format(toFormat), YourTimezone: t.In(location).Format(toFormat), Epoch: t.Unix()}, nil
return Time{UTC: t.UTC().Format(toFormat), YourTimezone: yourTZ, Epoch: t.Unix()}, nil
}
27 changes: 27 additions & 0 deletions internal/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestNow(t *testing.T) {
Expand Down Expand Up @@ -159,3 +161,28 @@ func TestTimeString(t *testing.T) {
t.Errorf("Expected string %s, but got %s", expectedString, result)
}
}

func TestTimeError(t *testing.T) {
t.Run("Test Time Error", func(t *testing.T) {
tz := "xyz"
_, err := Now("dd-MM-yyyy", &tz)
if err != nil {
t.Errorf("Expected error, but got nil")
}
})

t.Run("Test Convert Time From Epoch Error", func(t *testing.T) {
tz := "xyz"
time := ConvertTimeFromEpoch(1625097600, ParseFormat("dd-MM-yyyy"), &tz)
assert.Equal(t, "01-07-2021", time.UTC)
})

t.Run("Test Convert Time From Format Error", func(t *testing.T) {
tz := "xyz"
_, err := ConvertTimeFromFormat("2022-01-01 10:00:00", ParseFormat("yyyy-MM-dd HH:mm:ss"), "dd-MM-yyyy", &tz)
if err != nil {
t.Errorf("Expected error, but got nil")
}
})

}
66 changes: 29 additions & 37 deletions internal/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package internal
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v3"
"strings"

"gopkg.in/yaml.v3"
)

func Yaml2Json(yamlString string) (string, error) {
Expand All @@ -29,58 +30,49 @@ func Yaml2Properties(yamlData string) (string, error) {

// Write Properties
var propertiesBuilder strings.Builder
err = writeProperties(&propertiesBuilder, "", yamlNode.Content[0])
if err != nil {
return "", err
}
writeProperties(&propertiesBuilder, "", yamlNode.Content[0])

return propertiesBuilder.String(), nil
}

func writeProperties(builder *strings.Builder, prefix string, node *yaml.Node) error {

// invalid yaml
func writeProperties(builder *strings.Builder, prefix string, node *yaml.Node) {
if node.Kind != yaml.MappingNode {
return fmt.Errorf("expected a MappingNode, got %v", node.Kind)
return
}

// This loop iterates over the key-value pairs in the YAML mapping.
// It increments by 2 because each pair of nodes in the 'Content' slice represents a key-value pair.
// 'i' is the index of the key node and 'i+1' is the index of the value node.
for i := 0; i < len(node.Content); i += 2 {
keyNode, valueNode := node.Content[i], node.Content[i+1]

var fullKey string
if prefix == "" {
fullKey = keyNode.Value
} else {
fullKey = fmt.Sprintf("%v.%v", prefix, keyNode.Value)
}
fullKey := getFullKey(prefix, keyNode.Value)

switch valueNode.Kind {
case yaml.MappingNode:
// Recursively write nested maps
err := writeProperties(builder, fullKey, valueNode)
if err != nil {
return err
}
writeNestedMaps(builder, fullKey, valueNode)
case yaml.SequenceNode:
// Handle lists
for i, element := range valueNode.Content {
_, err := fmt.Fprintf(builder, "%s[%d]=%v\n", fullKey, i, element.Value)
if err != nil {
return err
}
}

writeSequence(builder, fullKey, valueNode)
default:
// Write key-value pairs
_, err := fmt.Fprintf(builder, "%s=%v\n", fullKey, valueNode.Value)
if err != nil {
return err
}
writeKeyValue(builder, fullKey, valueNode.Value)
}
}
}

func getFullKey(prefix, key string) string {
if prefix == "" {
return key
}
return fmt.Sprintf("%v.%v", prefix, key)
}

func writeNestedMaps(builder *strings.Builder, prefix string, node *yaml.Node) {
writeProperties(builder, prefix, node)
}

func writeSequence(builder *strings.Builder, prefix string, node *yaml.Node) {
for i, element := range node.Content {
builder.WriteString(fmt.Sprintf("%s[%d]=%v\n", prefix, i, element.Value))
}
}

return nil
func writeKeyValue(builder *strings.Builder, key, value string) {
builder.WriteString(fmt.Sprintf("%s=%v\n", key, value))
}
8 changes: 8 additions & 0 deletions internal/yaml_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package internal

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v3"
)

func TestYaml2JSON(t *testing.T) {
Expand Down Expand Up @@ -84,4 +86,10 @@ func TestYaml2Properties(t *testing.T) {
assert.Equal(t, tt.expectedProperty, result)
})
}

t.Run("write properties - invalid kind", func(t *testing.T) {
builder := &strings.Builder{}
writeProperties(builder, "xyz", &yaml.Node{Kind: yaml.DocumentNode})
assert.Equal(t, "", builder.String())
})
}
18 changes: 18 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,21 @@ func TestTimePage(t *testing.T) {
// TODO: Add assertions for the response body or other expectations
})
}

func TestPropertiesPage(t *testing.T) {
app := newApp()
propertiesPage(app)

t.Run("Test Properties Page - Properties to YAML", func(t *testing.T) {
// Create a test request to the "/properties" route with action=properties2Yaml and properties=...
req := httptest.NewRequest(http.MethodGet, "/properties?action=properties2Yaml&properties=...", nil)
resp, err := app.Test(req)
if err != nil {
t.Fatalf("Failed to send test request: %v", err)
}
// Check the response status code
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status code %d, but got %d", http.StatusOK, resp.StatusCode)
}
})
}
2 changes: 2 additions & 0 deletions server/ui/base64.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
<!-- Your custom script for copying text and showing tooltip -->
<script>
function encodeBase64() {
clearAlert();
$.ajax({
url: "/api/base64?action=encode",
contentType: "application/json",
Expand All @@ -64,6 +65,7 @@
});
}
function decodeBase64() {
clearAlert();
$.ajax({
url: "/api/base64?action=decode",
contentType: "application/json",
Expand Down
Loading

0 comments on commit c8e96b9

Please sign in to comment.