~samwhited/xmpp

dd64cf49f44ac9752494928cf8ce2abab7fec86d — Sam Whited 9 months ago aa94428
stream: improve error comparisons

Signed-off-by: Sam Whited <sam@samwhited.com>
3 files changed, 29 insertions(+), 0 deletions(-)

M CHANGELOG.md
M stream/error.go
M stream/error_test.go
M CHANGELOG.md => CHANGELOG.md +1 -0
@@ 27,6 27,7 @@ All notable changes to this project will be documented in this file.
- stanza: add `Error` method on the `IQ` type
- stream: new `InnerXML` and `ApplicationError` methods on `Error` provide a way
  to easily construct customized stream errors
- stream: ability to compare errors with `errors.Is`
- styling: add `Disable` and `Unstyled` to support disabling styling on some
  messages
- xmpp: `SetReadDeadline` and `SetWriteDeadline` are now proxied even if the

M stream/error.go => stream/error.go +14 -0
@@ 175,6 175,20 @@ type Error struct {
	payload  xml.TokenReader
}

// Is will be used by errors.Is when comparing errors.
// For more information see the errors package.
func (s Error) Is(err error) bool {
	se, ok := err.(Error)
	if !ok {
		return false
	}

	if se.Err == "" {
		return true
	}
	return se.Err == s.Err
}

// Error satisfies the builtin error interface and returns the name of the
// StreamError. For instance, given the error:
//

M stream/error_test.go => stream/error_test.go +14 -0
@@ 6,6 6,7 @@ package stream_test

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net"
	"testing"


@@ 24,6 25,19 @@ var (
	_ xmlstream.WriterTo  = (*stream.Error)(nil)
)

func TestCompare(t *testing.T) {
	hostGoneApp := stream.HostGone.ApplicationError(xmlstream.Wrap(nil, xml.StartElement{}))
	if !errors.Is(stream.HostGone, hostGoneApp) {
		t.Errorf("did not expect adding application error to affect comparison")
	}
	if errors.Is(stream.HostGone, stream.BadNamespacePrefix) {
		t.Errorf("did not expect two errors with different names to be equivalent")
	}
	if !errors.Is(stream.HostGone, stream.Error{}) {
		t.Errorf("expected empty stream error to compare to any other stream error")
	}
}

var marshalTests = [...]struct {
	se  stream.Error
	xml string