| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/stretchr/testify/require" |
| 9 |
) |
| 10 |
|
| 11 |
// String() and MarshalJSON() must stay on value receivers. With pointer |
| 12 |
// receivers, a ChunkID value doesn't implement these interfaces and gets |
| 13 |
// formatted or marshalled as a raw byte array instead of hex. |
| 14 |
var ( |
| 15 |
_ fmt.Stringer = ChunkID{} |
| 16 |
_ json.Marshaler = ChunkID{} |
| 17 |
) |
| 18 |
|
| 19 |
const testChunkIDHex = "dda036cc9be7d1b1c3f6f4d3d1e2ed0f9e1f74e8b0d1a2b3c4d5e6f708192a3b" |
| 20 |
|
| 21 |
func TestChunkIDFormatting(t *testing.T) { |
| 22 |
id, err := ChunkIDFromString(testChunkIDHex) |
| 23 |
require.NoError(t, err) |
| 24 |
|
| 25 |
// A value, not just a pointer, needs to render as hex |
| 26 |
require.Equal(t, testChunkIDHex, fmt.Sprintf("%s", id)) |
| 27 |
require.Equal(t, testChunkIDHex, fmt.Sprintf("%v", id)) |
| 28 |
require.Equal(t, `"`+testChunkIDHex+`"`, fmt.Sprintf("%q", id)) |
| 29 |
require.Equal(t, testChunkIDHex, fmt.Sprintf("%s", &id)) |
| 30 |
|
| 31 |
// Same for values carried in errors, which are printed by value |
| 32 |
require.Equal(t, |
| 33 |
fmt.Sprintf("chunk %s missing from store", testChunkIDHex), |
| 34 |
ChunkMissing{ID: id}.Error(), |
| 35 |
) |
| 36 |
} |
| 37 |
|
| 38 |
func TestChunkIDMarshalJSON(t *testing.T) { |
| 39 |
id, err := ChunkIDFromString(testChunkIDHex) |
| 40 |
require.NoError(t, err) |
| 41 |
|
| 42 |
// Map values aren't addressable, so a pointer-receiver MarshalJSON would |
| 43 |
// be skipped here and the ID emitted as an array of numbers |
| 44 |
b, err := json.Marshal(map[string]ChunkID{"id": id}) |
| 45 |
require.NoError(t, err) |
| 46 |
require.JSONEq(t, `{"id":"`+testChunkIDHex+`"}`, string(b)) |
| 47 |
|
| 48 |
// Round-trip through a struct, as done by inspect-chunks |
| 49 |
b, err = json.Marshal([]ChunkAdditionalInfo{{ID: id, UncompressedSize: 1024}}) |
| 50 |
require.NoError(t, err) |
| 51 |
require.JSONEq(t, `[{"id":"`+testChunkIDHex+`","uncompressed_size":1024}]`, string(b)) |
| 52 |
|
| 53 |
var got []ChunkAdditionalInfo |
| 54 |
require.NoError(t, json.Unmarshal(b, &got)) |
| 55 |
require.Equal(t, id, got[0].ID) |
| 56 |
} |