initial commits

master
Charles Iliya Krempeaux 2023-11-01 18:36:14 -07:00
parent fa844fd34c
commit 0c8c3456a5
2 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package tmp
import (
"encoding/json"
"sourcecode.social/reiver/go-erorr"
)
var _ json.Marshaler = Nothing[bool]()
var _ json.Marshaler = Nothing[string]()
// MarshalJSON makes it so json.Marshaler is implemented.
func (receiver Temporal[T]) MarshalJSON() ([]byte, error) {
switch interface{}(receiver.value).(type) {
case bool, string,json.Marshaler:
// these are OK.
default:
return nil, erorr.Errorf("tmp: cannot marshal something of type %T into JSON because parameterized type is %T rather than bool, string, or json.Marshaler", receiver, receiver.value)
}
if receiver.isnothing() {
return nil, erorr.Errorf("tmp: cannot marshal opt.Nothing[%T]() into JSON", receiver.value)
}
if receiver.IsDefunct() {
return nil, erorr.Errorf("tmp: cannot marshal defunct %#v into JSON", receiver.value)
}
return json.Marshal(receiver.value)
}

View File

@ -0,0 +1,96 @@
package tmp_test
import (
"testing"
"sourcecode.social/reiver/go-tmp"
)
func TestTemporal_MarshalJSON_bool(t *testing.T) {
tests := []struct{
Value tmp.Temporal[bool]
Expected string
}{
{
Value: tmp.Permanent(false),
Expected: "false",
},
{
Value: tmp.Permanent(true),
Expected: "true",
},
{
Value: tmp.Temporary(false, 9_223_372_036_854_775_807), // supposed to be a time far in the future
Expected: "false",
},
{
Value: tmp.Temporary(true, 9_223_372_036_854_775_806), // supposed to be a time far in the future
Expected: "true",
},
}
for testNumber, test := range tests {
actualBytes, err := test.Value.MarshalJSON()
if nil != err {
t.Errorf("For test #%d, did not expect an error but actually got one." , testNumber)
t.Logf("ERROR: (%T) %s", err, err)
t.Logf("VALUE: %#v", test.Value)
continue
}
actual := string(actualBytes)
expected := test.Expected
if expected != actual {
t.Errorf("For test #%d, the actual value for the JSON marshaling is not what was expected.", testNumber)
t.Logf("EXPECTED: %q", expected)
t.Logf("ACTUAL: %q", actual)
t.Logf("VALUE: %#v", test.Value)
continue
}
}
}
func TestTemporal_MarshalJSON_bool_fail(t *testing.T) {
tests := []struct{
Value tmp.Temporal[bool]
}{
{
Value: tmp.Nothing[bool](),
},
{
Value: tmp.Temporary(false, 1234), // supposed to be a time that is already expired
},
{
Value: tmp.Temporary(true, 5678), // supposed to be a time that is already expired
},
}
for testNumber, test := range tests {
actualBytes, err := test.Value.MarshalJSON()
if nil == err {
t.Errorf("For test #%d, expected an error but did not actually get one.", testNumber)
t.Logf("ACTUAL: %q", actualBytes)
t.Logf("ERROR: (%T) %s", err, err)
continue
}
if nil != actualBytes {
t.Errorf("For test #%d, expected not bytes but actually get some.", testNumber)
t.Logf("ACTUAL: %q", actualBytes)
t.Logf("ERROR: (%T) %s", err, err)
continue
}
}
}