]> Sergey Matveev's repositories - btrtrc.git/commitdiff
bencode.Bytes: Tests and stricter checks
authorMatt Joiner <anacrolix@gmail.com>
Tue, 2 Nov 2021 06:28:05 +0000 (17:28 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Tue, 2 Nov 2021 06:28:05 +0000 (17:28 +1100)
bencode/bytes.go
bencode/bytes_test.go [new file with mode: 0644]

index 5e1018e406779879197bcb3502c31b880c77b41a..c3a51cd0e285370cfde9517a449cba3566c281f7 100644 (file)
@@ -1,5 +1,9 @@
 package bencode
 
+import (
+       "errors"
+)
+
 type Bytes []byte
 
 var (
@@ -14,5 +18,8 @@ func (me *Bytes) UnmarshalBencode(b []byte) error {
 }
 
 func (me Bytes) MarshalBencode() ([]byte, error) {
+       if len(me) == 0 {
+               return nil, errors.New("marshalled Bytes should not be zero-length")
+       }
        return me, nil
 }
diff --git a/bencode/bytes_test.go b/bencode/bytes_test.go
new file mode 100644 (file)
index 0000000..08b4f98
--- /dev/null
@@ -0,0 +1,39 @@
+package bencode
+
+import (
+       "testing"
+
+       qt "github.com/frankban/quicktest"
+)
+
+func TestBytesMarshalNil(t *testing.T) {
+       var b Bytes
+       Marshal(b)
+}
+
+type structWithBytes struct {
+       A Bytes
+       B Bytes
+}
+
+func TestMarshalNilStructBytes(t *testing.T) {
+       _, err := Marshal(structWithBytes{B: Bytes("i42e")})
+       c := qt.New(t)
+       c.Assert(err, qt.IsNotNil)
+}
+
+type structWithOmitEmptyBytes struct {
+       A Bytes `bencode:",omitempty"`
+       B Bytes `bencode:",omitempty"`
+}
+
+func TestMarshalNilStructBytesOmitEmpty(t *testing.T) {
+       c := qt.New(t)
+       b, err := Marshal(structWithOmitEmptyBytes{B: Bytes("i42e")})
+       c.Assert(err, qt.IsNil)
+       t.Logf("%q", b)
+       var s structWithBytes
+       err = Unmarshal(b, &s)
+       c.Assert(err, qt.IsNil)
+       c.Check(s.B, qt.DeepEquals, Bytes("i42e"))
+}