-
Notifications
You must be signed in to change notification settings - Fork 73
Test Well Known Types #1273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Test Well Known Types #1273
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package types | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/url" | ||
| "time" | ||
| ) | ||
|
|
||
| // Duration is a wrapper for time.Duration to provide custom marshaling | ||
| // for JSON and URL query strings. | ||
| // | ||
| // It embeds time.Duration, so all standard methods (Seconds, String, etc.) | ||
| // are directly accessible. The underlying time.Duration value can be | ||
| // accessed via the .Duration field. | ||
| // | ||
| // Example: | ||
| // | ||
| // customDur := types.NewDuration(30 * time.Second) | ||
| // goDur := customDur.Duration // Access the underlying time.Duration | ||
| type Duration struct { | ||
| time.Duration | ||
| } | ||
|
|
||
| // NewDuration creates a custom Duration from a standard time.Duration. | ||
| func NewDuration(d time.Duration) Duration { | ||
| return Duration{Duration: d} | ||
| } | ||
|
|
||
| // MarshalJSON implements the json.Marshaler interface by formatting the | ||
| // duration as a string according to Google Well Known Type | ||
| func (d Duration) MarshalJSON() ([]byte, error) { | ||
| return []byte(fmt.Sprintf(`"%s"`, d.ToWireFormat())), nil | ||
| } | ||
|
|
||
| // String returns a string representation of Duration | ||
| // which follows the wire format from Google Well Known Type: | ||
| // a String that ends in s to indicate seconds and is preceded by | ||
| // the number of seconds, with nanoseconds expressed as fractional seconds. | ||
| // https://protobuf.dev/reference/protobuf/google.protobuf/#duration | ||
| func (d Duration) ToWireFormat() string { | ||
| // We do not use the standard time.Duration.String() method because it | ||
| // loses precision when converting to a string. | ||
|
|
||
| // Get the total nanoseconds as a precise integer. | ||
| nanos := d.Duration.Nanoseconds() | ||
|
|
||
| // Calculate seconds and fractional nanoseconds. | ||
| secs := nanos / 1_000_000_000 | ||
| fracNanos := nanos % 1_000_000_000 | ||
|
|
||
| // Format the string, ensuring the fractional part is zero-padded to 9 digits. | ||
| // This correctly handles both positive and negative durations. | ||
| if nanos < 0 { | ||
| // For negative values, both parts should be negative. | ||
| secs = -(-nanos / 1_000_000_000) | ||
| fracNanos = -(-nanos % 1_000_000_000) | ||
| return fmt.Sprintf(`%d.%09ds`, secs, -fracNanos) | ||
| } | ||
|
|
||
| return fmt.Sprintf(`%d.%09ds`, secs, fracNanos) | ||
| } | ||
|
|
||
| // EncodeValues implements the query.Encoder interface by formatting the | ||
| // duration as a string, like "3.3s". | ||
| func (d Duration) EncodeValues(key string, v *url.Values) error { | ||
| v.Set(key, d.ToWireFormat()) | ||
| return nil | ||
| } | ||
|
|
||
| // UnmarshalJSON implements the json.Unmarshaler interface. It can parse a | ||
| // duration from the Google well-known type format (e.g., "3.123s"). | ||
| func (d *Duration) UnmarshalJSON(b []byte) error { | ||
| if d == nil { | ||
| return fmt.Errorf("json.Unmarshal on nil pointer") | ||
| } | ||
| // Remove the quotes from the string | ||
| var s string | ||
| if err := json.Unmarshal(b, &s); err != nil { | ||
| return err | ||
| } | ||
| dur, err := time.ParseDuration(s) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| *d = NewDuration(dur) | ||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,252 @@ | ||
| package types | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/url" | ||
| "testing" | ||
| "time" | ||
| ) | ||
|
|
||
| func TestDuration_MarshalJSON(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| duration Duration | ||
| expected string | ||
| wantErr bool | ||
| }{ | ||
| { | ||
| name: "zero duration", | ||
| duration: NewDuration(0), | ||
| expected: "0.000000000s", | ||
| }, | ||
| { | ||
| name: "positive duration", | ||
| duration: NewDuration(5 * time.Second), | ||
| expected: "5.000000000s", | ||
| }, | ||
| { | ||
| name: "negative duration", | ||
| duration: NewDuration(-2 * time.Minute), | ||
| expected: "-120.000000000s", | ||
| }, | ||
| { | ||
| name: "negative duration with fractional seconds", | ||
| duration: NewDuration(-2*time.Minute + 100*time.Millisecond), | ||
| expected: "-119.900000000s", | ||
| }, | ||
| { | ||
| name: "fractional seconds", | ||
| duration: NewDuration(1500 * time.Millisecond), | ||
| expected: "1.500000000s", | ||
| }, | ||
| { | ||
| name: "large duration", | ||
| duration: NewDuration(9223372036*time.Second + 854775000*time.Nanosecond), | ||
| expected: "9223372036.854775000s", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| result, err := tt.duration.MarshalJSON() | ||
| if (err != nil) != tt.wantErr { | ||
| t.Errorf("Duration.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr) | ||
| return | ||
| } | ||
| if string(result) != `"`+tt.expected+`"` { | ||
| t.Errorf("Duration.MarshalJSON() = %v, want %v", string(result), `"`+tt.expected+`"`) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestDuration_UnmarshalJSON(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| input string | ||
| want Duration | ||
| wantErr bool | ||
| }{ | ||
| { | ||
| name: "zero duration", | ||
| input: `"0s"`, | ||
| want: NewDuration(0), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "positive duration", | ||
| input: `"5s"`, | ||
| want: NewDuration(5 * time.Second), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "negative duration", | ||
| input: `"-2s"`, | ||
| want: NewDuration(-2 * time.Second), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "negative duration with fractional seconds", | ||
| input: `"-2.1s"`, | ||
| want: NewDuration(-2*time.Second - 100*time.Millisecond), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "fractional seconds", | ||
| input: `"1.5s"`, | ||
| want: NewDuration(1500 * time.Millisecond), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "large duration", | ||
| input: `"9223372036.854775000s"`, | ||
| want: NewDuration(9223372036*time.Second + 854775000*time.Nanosecond), | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "invalid duration format", | ||
| input: `"invalid"`, | ||
| want: NewDuration(0), | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "empty string", | ||
| input: `""`, | ||
| want: NewDuration(0), | ||
| wantErr: true, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| var d Duration | ||
| err := d.UnmarshalJSON([]byte(tt.input)) | ||
| if (err != nil) != tt.wantErr { | ||
| t.Errorf("Duration.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) | ||
| return | ||
| } | ||
| if !tt.wantErr && d != tt.want { | ||
| t.Errorf("Duration.UnmarshalJSON() = %v, want %v", d, tt.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestDuration_UnmarshalJSON_NilPointer(t *testing.T) { | ||
| var d *Duration | ||
| err := d.UnmarshalJSON([]byte(`"5s"`)) | ||
| if err == nil { | ||
| t.Error("Duration.UnmarshalJSON() on nil pointer should return error") | ||
| } | ||
| expectedErr := "json.Unmarshal on nil pointer" | ||
| if err.Error() != expectedErr { | ||
| t.Errorf("Duration.UnmarshalJSON() error = %v, want %v", err.Error(), expectedErr) | ||
| } | ||
| } | ||
|
|
||
| func TestDuration_EncodeValues(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| duration Duration | ||
| key string | ||
| expected string | ||
| }{ | ||
| { | ||
| name: "zero duration", | ||
| duration: NewDuration(0), | ||
| key: "duration", | ||
| expected: "0.000000000s", | ||
| }, | ||
| { | ||
| name: "positive duration", | ||
| duration: NewDuration(5 * time.Second), | ||
| key: "timeout", | ||
| expected: "5.000000000s", | ||
| }, | ||
| { | ||
| name: "negative duration", | ||
| duration: NewDuration(-2 * time.Minute), | ||
| key: "delay", | ||
| expected: "-120.000000000s", | ||
| }, | ||
| { | ||
| name: "fractional seconds", | ||
| duration: NewDuration(1500 * time.Millisecond), | ||
| key: "interval", | ||
| expected: "1.500000000s", | ||
| }, | ||
| { | ||
| name: "large duration", | ||
| duration: NewDuration(24 * time.Hour), | ||
| key: "period", | ||
| expected: "86400.000000000s", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| values := url.Values{} | ||
| err := tt.duration.EncodeValues(tt.key, &values) | ||
| if err != nil { | ||
| t.Errorf("Duration.EncodeValues() error = %v", err) | ||
| return | ||
| } | ||
| result := values.Get(tt.key) | ||
| if result != tt.expected { | ||
| t.Errorf("Duration.EncodeValues() = %v, want %v", result, tt.expected) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestDuration_JSONRoundTrip(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| duration Duration | ||
| }{ | ||
| { | ||
| name: "zero duration", | ||
| duration: NewDuration(0), | ||
| }, | ||
| { | ||
| name: "positive duration", | ||
| duration: NewDuration(5 * time.Second), | ||
| }, | ||
| { | ||
| name: "negative duration", | ||
| duration: NewDuration(-2 * time.Minute), | ||
| }, | ||
| { | ||
| name: "fractional seconds", | ||
| duration: NewDuration(1500 * time.Millisecond), | ||
| }, | ||
| { | ||
| name: "complex duration", | ||
| duration: NewDuration(1*time.Hour + 2*time.Minute + 3*time.Second), | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| // Marshal to JSON | ||
| jsonData, err := json.Marshal(tt.duration) | ||
| if err != nil { | ||
| t.Errorf("json.Marshal() error = %v", err) | ||
| return | ||
| } | ||
|
|
||
| // Unmarshal from JSON | ||
| var result Duration | ||
| err = json.Unmarshal(jsonData, &result) | ||
| if err != nil { | ||
| t.Errorf("json.Unmarshal() error = %v", err) | ||
| return | ||
| } | ||
|
|
||
| // Check that the round trip preserved the value | ||
| if result != tt.duration { | ||
| t.Errorf("JSON round trip failed: original = %v, result = %v", tt.duration, result) | ||
| } | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought this would be a wrapper over the Google types, as the marshalling/unmarshalling function will be defined by the Google library. It's just that it is not a JSON marshal.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We were split between native types (better CUX) and well known types (easier code) and decided for the second. Since well known types do support native json marshall, we do need to wrap and convert anyway. So the reason to use well known does not exist anymore.