|
| 1 | +/* |
| 2 | + Copyright 2024 The CloudEvents Authors |
| 3 | + SPDX-License-Identifier: Apache-2.0 |
| 4 | +*/ |
| 5 | + |
| 6 | +package extensions |
| 7 | + |
| 8 | +import ( |
| 9 | + "net/url" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/cloudevents/sdk-go/v2/event" |
| 13 | +) |
| 14 | + |
| 15 | +func TestAddDataRefExtensionValidURL(t *testing.T) { |
| 16 | + e := event.New() |
| 17 | + expectedDataRef := "https://example.com/data" |
| 18 | + |
| 19 | + err := AddDataRefExtension(&e, expectedDataRef) |
| 20 | + if err != nil { |
| 21 | + t.Fatalf("Failed to add DataRefExtension with valid URL: %s", err) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +func TestAddDataRefExtensionInvalidURL(t *testing.T) { |
| 26 | + e := event.New() |
| 27 | + invalidDataRef := "://invalid-url" |
| 28 | + |
| 29 | + err := AddDataRefExtension(&e, invalidDataRef) |
| 30 | + if err == nil { |
| 31 | + t.Fatal("Expected error when adding DataRefExtension with invalid URL, but got none") |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func TestGetDataRefExtensionNotFound(t *testing.T) { |
| 36 | + e := event.New() |
| 37 | + |
| 38 | + _, ok := GetDataRefExtension(e) |
| 39 | + if ok { |
| 40 | + t.Fatal("Expected not to find DataRefExtension, but did") |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func TestSerializationAndDeserialization(t *testing.T) { |
| 45 | + e := event.New() |
| 46 | + dataRef := "https://example.com/data" |
| 47 | + |
| 48 | + err := AddDataRefExtension(&e, dataRef) |
| 49 | + if err != nil { |
| 50 | + t.Fatalf("Failed to add DataRefExtension: %s", err) |
| 51 | + } |
| 52 | + |
| 53 | + bytes, err := e.MarshalJSON() |
| 54 | + if err != nil { |
| 55 | + t.Fatalf("Failed to marshal event with DataRefExtension: %s", err) |
| 56 | + } |
| 57 | + |
| 58 | + var deserializedEvent event.Event |
| 59 | + err = deserializedEvent.UnmarshalJSON(bytes) |
| 60 | + if err != nil { |
| 61 | + t.Fatalf("Failed to unmarshal event with DataRefExtension: %s", err) |
| 62 | + } |
| 63 | + |
| 64 | + dataRefExtension, ok := GetDataRefExtension(deserializedEvent) |
| 65 | + if !ok { |
| 66 | + t.Fatal("Expected to find DataRefExtension after deserialization, but did not") |
| 67 | + } |
| 68 | + |
| 69 | + expectedURL, err := url.Parse(dataRef) |
| 70 | + if err != nil { |
| 71 | + t.Fatalf("Failed to parse expected DataRef URL: %s", err) |
| 72 | + } |
| 73 | + |
| 74 | + if dataRefExtension.DataRef.String() != expectedURL.String() { |
| 75 | + t.Errorf("Expected DataRefExtension.DataRef to be '%s', but got '%s' after deserialization", expectedURL, dataRefExtension.DataRef) |
| 76 | + } |
| 77 | +} |
0 commit comments