Skip to content
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

added null checks to NewCarbonInterval #73

Merged
merged 4 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions carboninterval.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,25 @@ import (
// CarbonInterval represents an interval between two carbons.
type CarbonInterval struct {
Start *Carbon
End *Carbon
End *Carbon
}

// NewCarbonInterval returns a pointer to a new CarbonInterval instance
func NewCarbonInterval(start, end *Carbon) (*CarbonInterval, error) {
if start == nil {
return nil, errors.New("start date cannot be nil")
}
if end == nil {
return nil, errors.New("end date cannot be nil")
}

if start.Gte(end) {
return nil, errors.New("The end date must be greater than the start date.")
return nil, errors.New("the end date must be greater than or equal to the start date")
}

return &CarbonInterval{
Start: start,
End: end,
End: end,
}, nil
}

Expand Down
22 changes: 21 additions & 1 deletion carboninterval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package carbon
import (
"testing"
"time"

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

Expand All @@ -11,7 +12,7 @@ func TestErrorOnConstruction(t *testing.T) {
endDate, _ := Create(2009, time.November, 9, 23, 0, 0, 0, "UTC")

_, err := NewCarbonInterval(startDate, endDate)
assert.Error(t, err, "The end date must be greater than the start date.")
assert.Error(t, err, "the end date must be greater than or equal to the start date")
}

func TestDiffInHours(t *testing.T) {
Expand All @@ -21,3 +22,22 @@ func TestDiffInHours(t *testing.T) {
interval, _ := NewCarbonInterval(startDate, endDate)
assert.Equal(t, int64(1), interval.DiffInHours())
}

func TestErrorOnNilStartDate(t *testing.T) {
endDate, _ := Create(2009, time.November, 10, 24, 0, 0, 0, "UTC")

_, err := NewCarbonInterval(nil, endDate)
assert.Error(t, err, "start date cannot be nil")
}

func TestErrorOnNilEndDate(t *testing.T) {
startDate, _ := Create(2009, time.November, 10, 23, 0, 0, 0, "UTC")

_, err := NewCarbonInterval(startDate, nil)
assert.Error(t, err, "end date cannot be nil")
}

func TestErrorOnNilDates(t *testing.T) {
_, err := NewCarbonInterval(nil, nil)
assert.Error(t, err, "start date cannot be nil")
}
Loading