Skip to content

Commit 14d1956

Browse files
authored
Merge pull request #200 from planetlabs/validate-bytes
Validate a single resource
2 parents 6932acc + 995eb1a commit 14d1956

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

validator/validator.go

+22
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package validator
33

44
import (
55
"context"
6+
"encoding/json"
67
"errors"
78
"fmt"
89
"net/url"
@@ -160,6 +161,27 @@ func (v *Validator) Validate(ctx context.Context, resource string) error {
160161
})
161162
}
162163

164+
// ValidateBytes validates a single STAC resource.
165+
//
166+
// The location is a URL or file path that represents the resource and will
167+
// be used in any validation error.
168+
func ValidateBytes(ctx context.Context, data []byte, location string) error {
169+
resource := crawler.Resource{}
170+
if err := json.Unmarshal(data, &resource); err != nil {
171+
return fmt.Errorf("failed to parse data as JSON: %w", err)
172+
}
173+
v := New(&Options{NoRecursion: true})
174+
info := &crawler.ResourceInfo{
175+
Location: location,
176+
Entry: location,
177+
}
178+
err := v.validate(resource, info)
179+
if !errors.Is(err, crawler.ErrStopRecursion) {
180+
return err
181+
}
182+
return nil
183+
}
184+
163185
func (v *Validator) validate(resource crawler.Resource, info *crawler.ResourceInfo) error {
164186
v.logger.Info("validating resource", "resource", info.Location)
165187
version := resource.Version()

validator/validator_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,40 @@ func (s *Suite) TestValidCases() {
6868
}
6969
}
7070

71+
func (s *Suite) TestValidateBytes() {
72+
cases := []string{
73+
"v1.0.0-beta.2/LC08_L1TP_097073_20130319_20200913_02_T1.json",
74+
"v1.0.0/catalog.json",
75+
"v1.0.0/collection.json",
76+
"v1.0.0/item.json",
77+
"v1.0.0/catalog-with-item.json",
78+
"v1.0.0/catalog-with-multiple-items.json",
79+
"v1.0.0/item-eo.json",
80+
}
81+
82+
ctx := context.Background()
83+
for _, c := range cases {
84+
s.Run(c, func() {
85+
location := path.Join("testdata", "cases", c)
86+
data, err := os.ReadFile(location)
87+
s.Require().NoError(err)
88+
s.NoError(validator.ValidateBytes(ctx, data, location))
89+
})
90+
}
91+
}
92+
93+
func (s *Suite) TestValidateBytesInvalidItem() {
94+
location := "testdata/cases/v1.0.0/item-missing-id.json"
95+
96+
data, readErr := os.ReadFile(location)
97+
s.Require().NoError(readErr)
98+
ctx := context.Background()
99+
100+
err := validator.ValidateBytes(ctx, data, location)
101+
s.Require().Error(err)
102+
s.Assert().True(strings.HasSuffix(fmt.Sprintf("%#v", err), "missing properties: 'id'"))
103+
}
104+
71105
func (s *Suite) TestSchemaMap() {
72106
v := validator.New(&validator.Options{
73107
SchemaMap: map[string]string{

0 commit comments

Comments
 (0)