summaryrefslogtreecommitdiff
path: root/decode_test.go
blob: 456f363ef9ca661b788c6e16c5752dbaf7c80ab8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package lowmemjson

import (
	"bytes"
	"io"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestDecodeNumber(t *testing.T) {
	t.Parallel()
	r := strings.NewReader(`1{}`)

	var num int
	assert.NoError(t, NewDecoder(r).Decode(&num))
	assert.Equal(t, 1, num)
	assert.Equal(t, 2, r.Len()) // check that it didn't read too far
}

func TestDecodeObject(t *testing.T) {
	t.Parallel()
	err := DecodeObject(strings.NewReader(`{"foo":9}`),
		func(r io.RuneScanner) error {
			return nil
		},
		func(r io.RuneScanner) error {
			var n int
			return NewDecoder(r).Decode(&n)
		})
	assert.ErrorContains(t, err, "did not consume entire")
}

func TestDecodeGrowing(t *testing.T) {
	t.Parallel()
	var buf bytes.Buffer
	dec := NewDecoder(&buf)
	var x any
	assert.ErrorIs(t, dec.Decode(&x), io.EOF)
	buf.WriteString("1\n")
	assert.NoError(t, dec.Decode(&x))
	buf.WriteString("1\n")
	assert.NoError(t, dec.Decode(&x))
	assert.ErrorIs(t, dec.Decode(&x), io.EOF)
}