1
0
mirror of https://github.com/golang/go synced 2024-11-07 14:36:17 -07:00
go/src/strconv/ctoa_test.go
Ben Hoyt 60f42ea61c strconv: fix incorrect bit size in ParseComplex; add tests
In ParseComplex, the "size" passed to parseFloatPrefix should be 64 for
complex128, not 128. It still works because of how parseFloatPrefix
is forgiving about the size if it's not 32, but worth fixing anyway.

Make ParseComplex and ParseFloat return a bit size error for anything
other than 128 or 64 (for ParseComplex), or 64 or 32 (for ParseFloat).
Add "InvalidBitSize" tests for these cases.

Add tests for ParseComplex with bitSize==64: this is done in a similar
way to how the ParseFloat 32-bit tests work, re-using the tests for the
larger bit size.

Add tests for FormatComplex -- there were none before.

Fixes #40706

Change-Id: I16ddd546e5237207cc3b8c2181dd708eca42b04f
Reviewed-on: https://go-review.googlesource.com/c/go/+/248219
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Minux Ma <minux@golang.org>
Trust: Robert Griesemer <gri@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
2020-10-30 00:13:25 +00:00

54 lines
1.4 KiB
Go

// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package strconv_test
import (
. "strconv"
"testing"
)
func TestFormatComplex(t *testing.T) {
tests := []struct {
c complex128
fmt byte
prec int
bitSize int
out string
}{
// a variety of signs
{1 + 2i, 'g', -1, 128, "(1+2i)"},
{3 - 4i, 'g', -1, 128, "(3-4i)"},
{-5 + 6i, 'g', -1, 128, "(-5+6i)"},
{-7 - 8i, 'g', -1, 128, "(-7-8i)"},
// test that fmt and prec are working
{3.14159 + 0.00123i, 'e', 3, 128, "(3.142e+00+1.230e-03i)"},
{3.14159 + 0.00123i, 'f', 3, 128, "(3.142+0.001i)"},
{3.14159 + 0.00123i, 'g', 3, 128, "(3.14+0.00123i)"},
// ensure bitSize rounding is working
{1.2345678901234567 + 9.876543210987654i, 'f', -1, 128, "(1.2345678901234567+9.876543210987654i)"},
{1.2345678901234567 + 9.876543210987654i, 'f', -1, 64, "(1.2345679+9.876543i)"},
// other cases are handled by FormatFloat tests
}
for _, test := range tests {
out := FormatComplex(test.c, test.fmt, test.prec, test.bitSize)
if out != test.out {
t.Fatalf("FormatComplex(%v, %q, %d, %d) = %q; want %q",
test.c, test.fmt, test.prec, test.bitSize, out, test.out)
}
}
}
func TestFormatComplexInvalidBitSize(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Fatalf("expected panic due to invalid bitSize")
}
}()
_ = FormatComplex(1+2i, 'g', -1, 100)
}