Skip to content

Commit

Permalink
fix(api): unmarshal env last modified date (#5205)
Browse files Browse the repository at this point in the history
  • Loading branch information
richardlt authored May 26, 2020
1 parent 9599374 commit 675cda3
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
41 changes: 41 additions & 0 deletions sdk/environment.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sdk

import (
json "encoding/json"
"time"
)

Expand All @@ -18,6 +19,46 @@ type Environment struct {
FromRepository string `json:"from_repository,omitempty"`
}

// UnmarshalJSON custom for last modified.
func (e *Environment) UnmarshalJSON(data []byte) error {
var tmp struct {
ID int64 `json:"id"`
Name string `json:"name"`
Variables []Variable `json:"variables"`
ProjectKey string `json:"project_key"`
Created time.Time `json:"created"`
Keys []EnvironmentKey `json:"keys"`
Usage *Usage `json:"usage"`
FromRepository string `json:"from_repository"`
}

if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
e.ID = tmp.ID
e.Name = tmp.Name
e.Variables = tmp.Variables
e.ProjectKey = tmp.ProjectKey
e.Created = tmp.Created
e.Keys = tmp.Keys
e.Usage = tmp.Usage
e.FromRepository = tmp.FromRepository

var v map[string]interface{}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
if lastModifiedNumber, ok := v["last_modified"].(float64); ok {
e.LastModified = time.Unix(int64(lastModifiedNumber), 0)
}
if lastModifiedString, ok := v["last_modified"].(string); ok {
date, _ := time.Parse(time.RFC3339, lastModifiedString)
e.LastModified = date
}

return nil
}

// EnvironmentVariableAudit represents an audit on an environment variable
type EnvironmentVariableAudit struct {
ID int64 `json:"id" yaml:"-" db:"id"`
Expand Down
32 changes: 32 additions & 0 deletions sdk/environment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package sdk_test

import (
json "encoding/json"
"fmt"
"testing"
"time"

"github.com/ovh/cds/sdk"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestEnvironmentUnmarshal(t *testing.T) {
now := time.Unix(time.Now().Unix(), 0)

nowBytes, err := json.Marshal(now)
require.NoError(t, err)

data1 := []byte(fmt.Sprintf("{\"name\":\"one\",\"last_modified\":%s}", nowBytes))
data2 := []byte(fmt.Sprintf("{\"name\":\"two\",\"last_modified\":%d}", now.Unix()))

var one sdk.Environment
require.NoError(t, json.Unmarshal(data1, &one))
assert.Equal(t, "one", one.Name)
assert.True(t, now.Equal(one.LastModified))

var two sdk.Environment
require.NoError(t, json.Unmarshal(data2, &two))
assert.Equal(t, "two", two.Name)
assert.True(t, now.Equal(two.LastModified))
}

0 comments on commit 675cda3

Please sign in to comment.