~samwhited/xmpp

bc0b84a558fb48bfa3ee8cf3c2ade06d66c6cac5 — Sam Whited 4 months ago d26cf32
form: add Len and Raw methods

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

M CHANGELOG.md
M form/form.go
M form/form_test.go
M CHANGELOG.md => CHANGELOG.md +1 -0
@@ 29,6 29,7 @@ All notable changes to this project will be documented in this file.
- carbons: new package implementing [XEP-0280: Message Carbons]
- commands: new package implementing [XEP-0050: Ad-Hoc Commands]
- history: implement [XEP-0313: Message Archive Management]
- form: add `Len` and `Raw` methods to form data
- muc: new package implementing [XEP-0045: Multi-User Chat] and [XEP-0249: Direct MUC Invitations]
- mux: `mux.ServeMux` now implements `info.FeatureIter` and `items.Iter`
- roster: the roster `Iter` now returns the roster version being iterated over

M form/form.go => form/form.go +21 -0
@@ 165,6 165,27 @@ func (d *Data) UnmarshalXML(decoder *xml.Decoder, start xml.StartElement) error 
	return decoder.Skip()
}

// Len returns the number of fields on the form.
func (d *Data) Len() int {
	if d == nil {
		return 0
	}
	return len(d.fields)
}

// Raw looks up the value parsed for a form field as it appeared in the XML.
func (d *Data) Raw(id string) (v []string, ok bool) {
	if d == nil {
		return nil, false
	}
	for _, field := range d.fields {
		if field.varName == id {
			return field.value, true
		}
	}
	return nil, false
}

// Get looks up the value submitted for a form field.
// If the value has not been set yet and no default value exists, ok will be
// false.

M form/form_test.go => form/form_test.go +23 -1
@@ 496,8 496,17 @@ func TestUnmarshalChardata(t *testing.T) {
	if err != nil {
		t.Fatalf("error unmarshaling: %v", err)
	}
	if data.Len() != 1 {
		t.Errorf("wrong length: want=1, got=%d", data.Len())
	}
	if b, ok := data.GetBool("foo"); !ok || !b {
		t.Fatalf("expected form field 'foo' to be set, got %t, %t", b, ok)
		t.Errorf("expected form field 'foo' to be set, got %t, %t", b, ok)
	}
	if v, ok := data.Raw("foo"); !ok || len(v) == 0 || v[0] != "true" {
		t.Errorf("expected form field 'foo' to have raw value, got %s, %t", v, ok)
	}
	if v, ok := data.Raw("test"); v != nil || ok {
		t.Errorf("did not expect raw values for unkonwn key, got %v, %t", v, ok)
	}
}



@@ 505,7 514,20 @@ func TestUnmarshalInvalidToken(t *testing.T) {
	const formData = `<x xmlns="jabber:x:data"><!-- Not allowed --></x>`
	data := &form.Data{}
	err := xml.Unmarshal([]byte(formData), data)
	if data.Len() != 0 {
		t.Errorf("wrong length: want=0, got=%d", data.Len())
	}
	if err == nil {
		t.Fatalf("expected error when unmarshaling disallowed token type")
	}
}

func TestNilLen(t *testing.T) {
	var data *form.Data
	if data.Len() != 0 {
		t.Errorf("wrong length: want=0, got=%d", data.Len())
	}
	if v, ok := data.Raw("test"); v != nil || ok {
		t.Errorf("did not expect raw values, got %v, %t", v, ok)
	}
}