authorgravatar for xq@random-projects.netFelix "xq" Queißner <xq@random-projects.net> 2019-11-27 22:35:32+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-11-27 16:35:32-05:00
logf0d6447569e89a7b862da806a78da52d15160ef4
tree3720226ab1c19246b4645bcc9ab7c4c3175188e3
parent0f2a9af4aacc018a06839993475991a034aa137f

Implements std.testing.expectEqual for tagged unions. (#3773)


1 files changed, 33 insertions(+), 1 deletions(-)

lib/std/testing.zig+33-1
......@@ -89,7 +89,26 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void {
8989 if (union_info.tag_type == null) {
9090 @compileError("Unable to compare untagged union values");
9191 }
92 @compileError("TODO implement testing.expectEqual for tagged unions");
92
93 const TagType = @TagType(@typeOf(expected));
94
95 const expectedTag = @as(TagType, expected);
96 const actualTag = @as(TagType, actual);
97
98 expectEqual(expectedTag, actualTag);
99
100 // we only reach this loop if the tags are equal
101 inline for (std.meta.fields(@typeOf(actual))) |fld| {
102 if (std.mem.eql(u8, fld.name, @tagName(actualTag))) {
103 expectEqual(@field(expected, fld.name), @field(actual, fld.name));
104 return;
105 }
106 }
107
108 // we iterate over *all* union fields
109 // => we should never get here as the loop above is
110 // including all possible values.
111 unreachable;
93112 },
94113
95114 .Optional => {
......@@ -124,6 +143,19 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void {
124143 }
125144}
126145
146test "expectEqual.union(enum)"
147{
148 const T = union(enum) {
149 a: i32,
150 b: f32,
151 };
152
153 const a10 = T { .a = 10 };
154 const a20 = T { .a = 20 };
155
156 expectEqual(a10, a10);
157}
158
127159/// This function is intended to be used only in tests. When the two slices are not
128160/// equal, prints diagnostics to stderr to show exactly how they are not equal,
129161/// then aborts.