File: slice_test.go

package info (click to toggle)
golang-github-juju-collections 1.0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie, trixie-proposed-updates
  • size: 176 kB
  • sloc: makefile: 18
file content (121 lines) | stat: -rw-r--r-- 2,121 bytes parent folder | download
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright 2022 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package transform_test

import (
	"errors"

	"github.com/juju/testing"
	gc "gopkg.in/check.v1"

	"github.com/juju/collections/transform"
)

type sliceSuite struct {
	testing.IsolationSuite
}

var _ = gc.Suite(sliceSuite{})

func (sliceSuite) TestSliceTransformation(c *gc.C) {
	type this struct {
		number int
	}

	type that struct {
		numero int
	}

	from := []this{
		{number: 1},
		{number: 2},
	}

	thisToThat := func(from this) that { return that{numero: from.number} }

	to := []that{
		{numero: 1},
		{numero: 2},
	}

	c.Assert(transform.Slice(from, thisToThat), gc.DeepEquals, to)
}

func (sliceSuite) TestSliceOrErrTransformationSucceeds(c *gc.C) {
	type this struct {
		number int
	}

	type that struct {
		numero int
	}

	from := []this{
		{number: 1},
		{number: 2},
	}

	thisToThat := func(from this) (that, error) { return that{numero: from.number}, nil }

	to := []that{
		{numero: 1},
		{numero: 2},
	}

	res, err := transform.SliceOrErr(from, thisToThat)
	c.Assert(err, gc.IsNil)
	c.Assert(res, gc.DeepEquals, to)
}

func (sliceSuite) TestSliceOrErrTransformationErrors(c *gc.C) {
	type this struct {
		number int
	}

	type that struct {
		numero int
	}

	from := []this{
		{number: 1},
		{number: 0},
		{number: 2},
	}

	testErr := errors.New("cannot transform 0")
	thisToThat := func(from this) (that, error) {
		if from.number == 0 {
			return that{}, testErr
		}
		return that{numero: from.number}, nil
	}

	_, err := transform.SliceOrErr(from, thisToThat)
	c.Assert(errors.Is(err, testErr), gc.Equals, true)
	c.Assert(err, gc.ErrorMatches, "transforming slice at index 1: cannot transform 0")
}

func (sliceSuite) TestSliceToMapTransformation(c *gc.C) {
	type this struct {
		number int
	}

	type that struct {
		numero int
	}

	from := []this{
		{number: 1},
		{number: 2},
	}

	thisToThat := func(from this) (int, that) { return from.number, that{numero: from.number} }

	to := map[int]that{
		1: {numero: 1},
		2: {numero: 2},
	}

	c.Assert(transform.SliceToMap(from, thisToThat), gc.DeepEquals, to)
}