fmt_test.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package fmt_test
  5. import (
  6. "bytes"
  7. . "fmt"
  8. "io"
  9. "math"
  10. "runtime"
  11. "strings"
  12. "testing"
  13. "time"
  14. "unicode"
  15. )
  16. type (
  17. renamedBool bool
  18. renamedInt int
  19. renamedInt8 int8
  20. renamedInt16 int16
  21. renamedInt32 int32
  22. renamedInt64 int64
  23. renamedUint uint
  24. renamedUint8 uint8
  25. renamedUint16 uint16
  26. renamedUint32 uint32
  27. renamedUint64 uint64
  28. renamedUintptr uintptr
  29. renamedString string
  30. renamedBytes []byte
  31. renamedFloat32 float32
  32. renamedFloat64 float64
  33. renamedComplex64 complex64
  34. renamedComplex128 complex128
  35. )
  36. func TestFmtInterface(t *testing.T) {
  37. var i1 interface{}
  38. i1 = "abc"
  39. s := Sprintf("%s", i1)
  40. if s != "abc" {
  41. t.Errorf(`Sprintf("%%s", empty("abc")) = %q want %q`, s, "abc")
  42. }
  43. }
  44. const b32 uint32 = 1<<32 - 1
  45. const b64 uint64 = 1<<64 - 1
  46. var array = [5]int{1, 2, 3, 4, 5}
  47. var iarray = [4]interface{}{1, "hello", 2.5, nil}
  48. var slice = array[:]
  49. var islice = iarray[:]
  50. type A struct {
  51. i int
  52. j uint
  53. s string
  54. x []int
  55. }
  56. type I int
  57. func (i I) String() string { return Sprintf("<%d>", int(i)) }
  58. type B struct {
  59. I I
  60. j int
  61. }
  62. type C struct {
  63. i int
  64. B
  65. }
  66. type F int
  67. func (f F) Format(s State, c rune) {
  68. Fprintf(s, "<%c=F(%d)>", c, int(f))
  69. }
  70. type G int
  71. func (g G) GoString() string {
  72. return Sprintf("GoString(%d)", int(g))
  73. }
  74. type S struct {
  75. F F // a struct field that Formats
  76. G G // a struct field that GoStrings
  77. }
  78. type SI struct {
  79. I interface{}
  80. }
  81. // P is a type with a String method with pointer receiver for testing %p.
  82. type P int
  83. var pValue P
  84. func (p *P) String() string {
  85. return "String(p)"
  86. }
  87. var barray = [5]renamedUint8{1, 2, 3, 4, 5}
  88. var bslice = barray[:]
  89. type byteStringer byte
  90. func (byteStringer) String() string { return "X" }
  91. var byteStringerSlice = []byteStringer{97, 98, 99, 100}
  92. type byteFormatter byte
  93. func (byteFormatter) Format(f State, _ rune) {
  94. Fprint(f, "X")
  95. }
  96. var byteFormatterSlice = []byteFormatter{97, 98, 99, 100}
  97. var b byte
  98. var fmtTests = []struct {
  99. fmt string
  100. val interface{}
  101. out string
  102. }{
  103. {"%d", 12345, "12345"},
  104. {"%v", 12345, "12345"},
  105. {"%t", true, "true"},
  106. // basic string
  107. {"%s", "abc", "abc"},
  108. {"%x", "abc", "616263"},
  109. {"%x", "xyz", "78797a"},
  110. {"%X", "xyz", "78797A"},
  111. {"%q", "abc", `"abc"`},
  112. {"%#x", []byte("abc\xff"), "0x616263ff"},
  113. {"%#X", []byte("abc\xff"), "0X616263FF"},
  114. {"%# x", []byte("abc\xff"), "0x61 0x62 0x63 0xff"},
  115. {"%# X", []byte("abc\xff"), "0X61 0X62 0X63 0XFF"},
  116. // basic bytes
  117. {"%s", []byte("abc"), "abc"},
  118. {"%x", []byte("abc"), "616263"},
  119. {"% x", []byte("abc\xff"), "61 62 63 ff"},
  120. {"%#x", []byte("abc\xff"), "0x616263ff"},
  121. {"%#X", []byte("abc\xff"), "0X616263FF"},
  122. {"%# x", []byte("abc\xff"), "0x61 0x62 0x63 0xff"},
  123. {"%# X", []byte("abc\xff"), "0X61 0X62 0X63 0XFF"},
  124. {"% X", []byte("abc\xff"), "61 62 63 FF"},
  125. {"%x", []byte("xyz"), "78797a"},
  126. {"%X", []byte("xyz"), "78797A"},
  127. {"%q", []byte("abc"), `"abc"`},
  128. // escaped strings
  129. {"%#q", `abc`, "`abc`"},
  130. {"%#q", `"`, "`\"`"},
  131. {"1 %#q", `\n`, "1 `\\n`"},
  132. {"2 %#q", "\n", `2 "\n"`},
  133. {"%q", `"`, `"\""`},
  134. {"%q", "\a\b\f\r\n\t\v", `"\a\b\f\r\n\t\v"`},
  135. {"%q", "abc\xffdef", `"abc\xffdef"`},
  136. {"%q", "\u263a", `"☺"`},
  137. {"%+q", "\u263a", `"\u263a"`},
  138. {"%q", "\U0010ffff", `"\U0010ffff"`},
  139. // escaped characters
  140. {"%q", 'x', `'x'`},
  141. {"%q", 0, `'\x00'`},
  142. {"%q", '\n', `'\n'`},
  143. {"%q", '\u0e00', `'\u0e00'`}, // not a printable rune.
  144. {"%q", '\U000c2345', `'\U000c2345'`}, // not a printable rune.
  145. {"%q", int64(0x7FFFFFFF), `%!q(int64=2147483647)`},
  146. {"%q", uint64(0xFFFFFFFF), `%!q(uint64=4294967295)`},
  147. {"%q", '"', `'"'`},
  148. {"%q", '\'', `'\''`},
  149. {"%q", "\u263a", `"☺"`},
  150. {"%+q", "\u263a", `"\u263a"`},
  151. // width
  152. {"%5s", "abc", " abc"},
  153. {"%2s", "\u263a", " ☺"},
  154. {"%-5s", "abc", "abc "},
  155. {"%-8q", "abc", `"abc" `},
  156. {"%05s", "abc", "00abc"},
  157. {"%08q", "abc", `000"abc"`},
  158. {"%5s", "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"},
  159. {"%.5s", "abcdefghijklmnopqrstuvwxyz", "abcde"},
  160. {"%.5s", "日本語日本語", "日本語日本"},
  161. {"%.5s", []byte("日本語日本語"), "日本語日本"},
  162. {"%.5q", "abcdefghijklmnopqrstuvwxyz", `"abcde"`},
  163. {"%.5x", "abcdefghijklmnopqrstuvwxyz", `6162636465`},
  164. {"%.5q", []byte("abcdefghijklmnopqrstuvwxyz"), `"abcde"`},
  165. {"%.5x", []byte("abcdefghijklmnopqrstuvwxyz"), `6162636465`},
  166. {"%.3q", "日本語日本語", `"日本語"`},
  167. {"%.3q", []byte("日本語日本語"), `"日本語"`},
  168. {"%.1q", "日本語", `"日"`},
  169. {"%.1q", []byte("日本語"), `"日"`},
  170. {"%.1x", "日本語", `e6`},
  171. {"%.1X", []byte("日本語"), `E6`},
  172. {"%10.1q", "日本語日本語", ` "日"`},
  173. {"%3c", '⌘', " ⌘"},
  174. {"%5q", '\u2026', ` '…'`},
  175. {"%10v", nil, " <nil>"},
  176. {"%-10v", nil, "<nil> "},
  177. // integers
  178. {"%d", 12345, "12345"},
  179. {"%d", -12345, "-12345"},
  180. {"%10d", 12345, " 12345"},
  181. {"%10d", -12345, " -12345"},
  182. {"%+10d", 12345, " +12345"},
  183. {"%010d", 12345, "0000012345"},
  184. {"%010d", -12345, "-000012345"},
  185. {"%-10d", 12345, "12345 "},
  186. {"%010.3d", 1, " 001"},
  187. {"%010.3d", -1, " -001"},
  188. {"%+d", 12345, "+12345"},
  189. {"%+d", -12345, "-12345"},
  190. {"%+d", 0, "+0"},
  191. {"% d", 0, " 0"},
  192. {"% d", 12345, " 12345"},
  193. {"%.0d", 0, ""},
  194. {"%.d", 0, ""},
  195. // unicode format
  196. {"%U", 0x1, "U+0001"},
  197. {"%U", uint(0x1), "U+0001"},
  198. {"%.8U", 0x2, "U+00000002"},
  199. {"%U", 0x1234, "U+1234"},
  200. {"%U", 0x12345, "U+12345"},
  201. {"%10.6U", 0xABC, " U+000ABC"},
  202. {"%-10.6U", 0xABC, "U+000ABC "},
  203. {"%U", '\n', `U+000A`},
  204. {"%#U", '\n', `U+000A`},
  205. {"%U", 'x', `U+0078`},
  206. {"%#U", 'x', `U+0078 'x'`},
  207. {"%U", '\u263a', `U+263A`},
  208. {"%#U", '\u263a', `U+263A '☺'`},
  209. // floats
  210. {"%+.3e", 0.0, "+0.000e+00"},
  211. {"%+.3e", 1.0, "+1.000e+00"},
  212. {"%+.3f", -1.0, "-1.000"},
  213. {"%+.3F", -1.0, "-1.000"},
  214. {"%+.3F", float32(-1.0), "-1.000"},
  215. {"%+07.2f", 1.0, "+001.00"},
  216. {"%+07.2f", -1.0, "-001.00"},
  217. {"%+10.2f", +1.0, " +1.00"},
  218. {"%+10.2f", -1.0, " -1.00"},
  219. {"% .3E", -1.0, "-1.000E+00"},
  220. {"% .3e", 1.0, " 1.000e+00"},
  221. {"%+.3g", 0.0, "+0"},
  222. {"%+.3g", 1.0, "+1"},
  223. {"%+.3g", -1.0, "-1"},
  224. {"% .3g", -1.0, "-1"},
  225. {"% .3g", 1.0, " 1"},
  226. {"%b", float32(1.0), "8388608p-23"},
  227. {"%b", 1.0, "4503599627370496p-52"},
  228. // complex values
  229. {"%+.3e", 0i, "(+0.000e+00+0.000e+00i)"},
  230. {"%+.3f", 0i, "(+0.000+0.000i)"},
  231. {"%+.3g", 0i, "(+0+0i)"},
  232. {"%+.3e", 1 + 2i, "(+1.000e+00+2.000e+00i)"},
  233. {"%+.3f", 1 + 2i, "(+1.000+2.000i)"},
  234. {"%+.3g", 1 + 2i, "(+1+2i)"},
  235. {"%.3e", 0i, "(0.000e+00+0.000e+00i)"},
  236. {"%.3f", 0i, "(0.000+0.000i)"},
  237. {"%.3F", 0i, "(0.000+0.000i)"},
  238. {"%.3F", complex64(0i), "(0.000+0.000i)"},
  239. {"%.3g", 0i, "(0+0i)"},
  240. {"%.3e", 1 + 2i, "(1.000e+00+2.000e+00i)"},
  241. {"%.3f", 1 + 2i, "(1.000+2.000i)"},
  242. {"%.3g", 1 + 2i, "(1+2i)"},
  243. {"%.3e", -1 - 2i, "(-1.000e+00-2.000e+00i)"},
  244. {"%.3f", -1 - 2i, "(-1.000-2.000i)"},
  245. {"%.3g", -1 - 2i, "(-1-2i)"},
  246. {"% .3E", -1 - 2i, "(-1.000E+00-2.000E+00i)"},
  247. {"%+.3g", complex64(1 + 2i), "(+1+2i)"},
  248. {"%+.3g", complex128(1 + 2i), "(+1+2i)"},
  249. {"%b", complex64(1 + 2i), "(8388608p-23+8388608p-22i)"},
  250. {"%b", 1 + 2i, "(4503599627370496p-52+4503599627370496p-51i)"},
  251. // erroneous formats
  252. {"", 2, "%!(EXTRA int=2)"},
  253. {"%d", "hello", "%!d(string=hello)"},
  254. // old test/fmt_test.go
  255. {"%d", 1234, "1234"},
  256. {"%d", -1234, "-1234"},
  257. {"%d", uint(1234), "1234"},
  258. {"%d", uint32(b32), "4294967295"},
  259. {"%d", uint64(b64), "18446744073709551615"},
  260. {"%o", 01234, "1234"},
  261. {"%#o", 01234, "01234"},
  262. {"%o", uint32(b32), "37777777777"},
  263. {"%o", uint64(b64), "1777777777777777777777"},
  264. {"%x", 0x1234abcd, "1234abcd"},
  265. {"%#x", 0x1234abcd, "0x1234abcd"},
  266. {"%x", b32 - 0x1234567, "fedcba98"},
  267. {"%X", 0x1234abcd, "1234ABCD"},
  268. {"%X", b32 - 0x1234567, "FEDCBA98"},
  269. {"%#X", 0, "0X0"},
  270. {"%x", b64, "ffffffffffffffff"},
  271. {"%b", 7, "111"},
  272. {"%b", b64, "1111111111111111111111111111111111111111111111111111111111111111"},
  273. {"%b", -6, "-110"},
  274. {"%e", 1.0, "1.000000e+00"},
  275. {"%e", 1234.5678e3, "1.234568e+06"},
  276. {"%e", 1234.5678e-8, "1.234568e-05"},
  277. {"%e", -7.0, "-7.000000e+00"},
  278. {"%e", -1e-9, "-1.000000e-09"},
  279. {"%f", 1234.5678e3, "1234567.800000"},
  280. {"%f", 1234.5678e-8, "0.000012"},
  281. {"%f", -7.0, "-7.000000"},
  282. {"%f", -1e-9, "-0.000000"},
  283. {"%g", 1234.5678e3, "1.2345678e+06"},
  284. {"%g", float32(1234.5678e3), "1.2345678e+06"},
  285. {"%g", 1234.5678e-8, "1.2345678e-05"},
  286. {"%g", -7.0, "-7"},
  287. {"%g", -1e-9, "-1e-09"},
  288. {"%g", float32(-1e-9), "-1e-09"},
  289. {"%E", 1.0, "1.000000E+00"},
  290. {"%E", 1234.5678e3, "1.234568E+06"},
  291. {"%E", 1234.5678e-8, "1.234568E-05"},
  292. {"%E", -7.0, "-7.000000E+00"},
  293. {"%E", -1e-9, "-1.000000E-09"},
  294. {"%G", 1234.5678e3, "1.2345678E+06"},
  295. {"%G", float32(1234.5678e3), "1.2345678E+06"},
  296. {"%G", 1234.5678e-8, "1.2345678E-05"},
  297. {"%G", -7.0, "-7"},
  298. {"%G", -1e-9, "-1E-09"},
  299. {"%G", float32(-1e-9), "-1E-09"},
  300. {"%c", 'x', "x"},
  301. {"%c", 0xe4, "ä"},
  302. {"%c", 0x672c, "本"},
  303. {"%c", '日', "日"},
  304. {"%20.8d", 1234, " 00001234"},
  305. {"%20.8d", -1234, " -00001234"},
  306. {"%20d", 1234, " 1234"},
  307. {"%-20.8d", 1234, "00001234 "},
  308. {"%-20.8d", -1234, "-00001234 "},
  309. {"%-#20.8x", 0x1234abc, "0x01234abc "},
  310. {"%-#20.8X", 0x1234abc, "0X01234ABC "},
  311. {"%-#20.8o", 01234, "00001234 "},
  312. {"%.20b", 7, "00000000000000000111"},
  313. {"%20.5s", "qwertyuiop", " qwert"},
  314. {"%.5s", "qwertyuiop", "qwert"},
  315. {"%-20.5s", "qwertyuiop", "qwert "},
  316. {"%20c", 'x', " x"},
  317. {"%-20c", 'x', "x "},
  318. {"%20.6e", 1.2345e3, " 1.234500e+03"},
  319. {"%20.6e", 1.2345e-3, " 1.234500e-03"},
  320. {"%20e", 1.2345e3, " 1.234500e+03"},
  321. {"%20e", 1.2345e-3, " 1.234500e-03"},
  322. {"%20.8e", 1.2345e3, " 1.23450000e+03"},
  323. {"%20f", 1.23456789e3, " 1234.567890"},
  324. {"%20f", 1.23456789e-3, " 0.001235"},
  325. {"%20f", 12345678901.23456789, " 12345678901.234568"},
  326. {"%-20f", 1.23456789e3, "1234.567890 "},
  327. {"%20.8f", 1.23456789e3, " 1234.56789000"},
  328. {"%20.8f", 1.23456789e-3, " 0.00123457"},
  329. {"%g", 1.23456789e3, "1234.56789"},
  330. {"%g", 1.23456789e-3, "0.00123456789"},
  331. {"%g", 1.23456789e20, "1.23456789e+20"},
  332. {"%20e", math.Inf(1), " +Inf"},
  333. {"%-20f", math.Inf(-1), "-Inf "},
  334. {"%20g", math.NaN(), " NaN"},
  335. // arrays
  336. {"%v", array, "[1 2 3 4 5]"},
  337. {"%v", iarray, "[1 hello 2.5 <nil>]"},
  338. {"%v", barray, "[1 2 3 4 5]"},
  339. {"%v", &array, "&[1 2 3 4 5]"},
  340. {"%v", &iarray, "&[1 hello 2.5 <nil>]"},
  341. {"%v", &barray, "&[1 2 3 4 5]"},
  342. // slices
  343. {"%v", slice, "[1 2 3 4 5]"},
  344. {"%v", islice, "[1 hello 2.5 <nil>]"},
  345. {"%v", bslice, "[1 2 3 4 5]"},
  346. {"%v", &slice, "&[1 2 3 4 5]"},
  347. {"%v", &islice, "&[1 hello 2.5 <nil>]"},
  348. {"%v", &bslice, "&[1 2 3 4 5]"},
  349. // complexes with %v
  350. {"%v", 1 + 2i, "(1+2i)"},
  351. {"%v", complex64(1 + 2i), "(1+2i)"},
  352. {"%v", complex128(1 + 2i), "(1+2i)"},
  353. // structs
  354. {"%v", A{1, 2, "a", []int{1, 2}}, `{1 2 a [1 2]}`},
  355. {"%+v", A{1, 2, "a", []int{1, 2}}, `{i:1 j:2 s:a x:[1 2]}`},
  356. // +v on structs with Stringable items
  357. {"%+v", B{1, 2}, `{I:<1> j:2}`},
  358. {"%+v", C{1, B{2, 3}}, `{i:1 B:{I:<2> j:3}}`},
  359. // other formats on Stringable items
  360. {"%s", I(23), `<23>`},
  361. {"%q", I(23), `"<23>"`},
  362. {"%x", I(23), `3c32333e`},
  363. {"%#x", I(23), `0x3c32333e`},
  364. {"%# x", I(23), `0x3c 0x32 0x33 0x3e`},
  365. {"%d", I(23), `23`}, // Stringer applies only to string formats.
  366. // go syntax
  367. {"%#v", A{1, 2, "a", []int{1, 2}}, `fmt_test.A{i:1, j:0x2, s:"a", x:[]int{1, 2}}`},
  368. {"%#v", &b, "(*uint8)(0xPTR)"},
  369. {"%#v", TestFmtInterface, "(func(*testing.T))(0xPTR)"},
  370. {"%#v", make(chan int), "(chan int)(0xPTR)"},
  371. {"%#v", uint64(1<<64 - 1), "0xffffffffffffffff"},
  372. {"%#v", 1000000000, "1000000000"},
  373. {"%#v", map[string]int{"a": 1}, `map[string]int{"a":1}`},
  374. {"%#v", map[string]B{"a": {1, 2}}, `map[string]fmt_test.B{"a":fmt_test.B{I:1, j:2}}`},
  375. {"%#v", []string{"a", "b"}, `[]string{"a", "b"}`},
  376. {"%#v", SI{}, `fmt_test.SI{I:interface {}(nil)}`},
  377. {"%#v", []int(nil), `[]int(nil)`},
  378. {"%#v", []int{}, `[]int{}`},
  379. {"%#v", array, `[5]int{1, 2, 3, 4, 5}`},
  380. {"%#v", &array, `&[5]int{1, 2, 3, 4, 5}`},
  381. {"%#v", iarray, `[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
  382. {"%#v", &iarray, `&[4]interface {}{1, "hello", 2.5, interface {}(nil)}`},
  383. {"%#v", map[int]byte(nil), `map[int]uint8(nil)`},
  384. {"%#v", map[int]byte{}, `map[int]uint8{}`},
  385. {"%#v", "foo", `"foo"`},
  386. {"%#v", barray, `[5]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
  387. {"%#v", bslice, `[]fmt_test.renamedUint8{0x1, 0x2, 0x3, 0x4, 0x5}`},
  388. {"%#v", []byte(nil), "[]byte(nil)"},
  389. {"%#v", []int32(nil), "[]int32(nil)"},
  390. // slices with other formats
  391. {"%#x", []int{1, 2, 15}, `[0x1 0x2 0xf]`},
  392. {"%x", []int{1, 2, 15}, `[1 2 f]`},
  393. {"%d", []int{1, 2, 15}, `[1 2 15]`},
  394. {"%d", []byte{1, 2, 15}, `[1 2 15]`},
  395. {"%q", []string{"a", "b"}, `["a" "b"]`},
  396. // renamings
  397. {"%v", renamedBool(true), "true"},
  398. {"%d", renamedBool(true), "%!d(fmt_test.renamedBool=true)"},
  399. {"%o", renamedInt(8), "10"},
  400. {"%d", renamedInt8(-9), "-9"},
  401. {"%v", renamedInt16(10), "10"},
  402. {"%v", renamedInt32(-11), "-11"},
  403. {"%X", renamedInt64(255), "FF"},
  404. {"%v", renamedUint(13), "13"},
  405. {"%o", renamedUint8(14), "16"},
  406. {"%X", renamedUint16(15), "F"},
  407. {"%d", renamedUint32(16), "16"},
  408. {"%X", renamedUint64(17), "11"},
  409. {"%o", renamedUintptr(18), "22"},
  410. {"%x", renamedString("thing"), "7468696e67"},
  411. {"%d", renamedBytes([]byte{1, 2, 15}), `[1 2 15]`},
  412. {"%q", renamedBytes([]byte("hello")), `"hello"`},
  413. {"%x", []renamedUint8{'a', 'b', 'c'}, "616263"},
  414. {"%s", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, "hello"},
  415. {"%q", []renamedUint8{'h', 'e', 'l', 'l', 'o'}, `"hello"`},
  416. {"%v", renamedFloat32(22), "22"},
  417. {"%v", renamedFloat64(33), "33"},
  418. {"%v", renamedComplex64(3 + 4i), "(3+4i)"},
  419. {"%v", renamedComplex128(4 - 3i), "(4-3i)"},
  420. // Formatter
  421. {"%x", F(1), "<x=F(1)>"},
  422. {"%x", G(2), "2"},
  423. {"%+v", S{F(4), G(5)}, "{F:<v=F(4)> G:5}"},
  424. // GoStringer
  425. {"%#v", G(6), "GoString(6)"},
  426. {"%#v", S{F(7), G(8)}, "fmt_test.S{F:<v=F(7)>, G:GoString(8)}"},
  427. // %T
  428. {"%T", (4 - 3i), "complex128"},
  429. {"%T", renamedComplex128(4 - 3i), "fmt_test.renamedComplex128"},
  430. {"%T", intVal, "int"},
  431. {"%6T", &intVal, " *int"},
  432. {"%10T", nil, " <nil>"},
  433. {"%-10T", nil, "<nil> "},
  434. // %p
  435. {"p0=%p", new(int), "p0=0xPTR"},
  436. {"p1=%s", &pValue, "p1=String(p)"}, // String method...
  437. {"p2=%p", &pValue, "p2=0xPTR"}, // ... not called with %p
  438. {"p3=%p", (*int)(nil), "p3=0x0"},
  439. {"p4=%#p", new(int), "p4=PTR"},
  440. // %p on non-pointers
  441. {"%p", make(chan int), "0xPTR"},
  442. {"%p", make(map[int]int), "0xPTR"},
  443. {"%p", make([]int, 1), "0xPTR"},
  444. {"%p", 27, "%!p(int=27)"}, // not a pointer at all
  445. // %q on pointers
  446. {"%q", (*int)(nil), "%!q(*int=<nil>)"},
  447. {"%q", new(int), "%!q(*int=0xPTR)"},
  448. // %v on pointers formats 0 as <nil>
  449. {"%v", (*int)(nil), "<nil>"},
  450. {"%v", new(int), "0xPTR"},
  451. // %d etc. pointers use specified base.
  452. {"%d", new(int), "PTR_d"},
  453. {"%o", new(int), "PTR_o"},
  454. {"%x", new(int), "PTR_x"},
  455. // %d on Stringer should give integer if possible
  456. {"%s", time.Time{}.Month(), "January"},
  457. {"%d", time.Time{}.Month(), "1"},
  458. // erroneous things
  459. {"%s %", "hello", "hello %!(NOVERB)"},
  460. {"%s %.2", "hello", "hello %!(NOVERB)"},
  461. {"%d", "hello", "%!d(string=hello)"},
  462. {"no args", "hello", "no args%!(EXTRA string=hello)"},
  463. {"%s", nil, "%!s(<nil>)"},
  464. {"%T", nil, "<nil>"},
  465. {"%-1", 100, "%!(NOVERB)%!(EXTRA int=100)"},
  466. // The "<nil>" show up because maps are printed by
  467. // first obtaining a list of keys and then looking up
  468. // each key. Since NaNs can be map keys but cannot
  469. // be fetched directly, the lookup fails and returns a
  470. // zero reflect.Value, which formats as <nil>.
  471. // This test is just to check that it shows the two NaNs at all.
  472. {"%v", map[float64]int{math.NaN(): 1, math.NaN(): 2}, "map[NaN:<nil> NaN:<nil>]"},
  473. // Used to crash because nByte didn't allow for a sign.
  474. {"%b", int64(-1 << 63), zeroFill("-1", 63, "")},
  475. // Used to panic.
  476. {"%0100d", 1, zeroFill("", 100, "1")},
  477. {"%0100d", -1, zeroFill("-", 99, "1")},
  478. {"%0.100f", 1.0, zeroFill("1.", 100, "")},
  479. {"%0.100f", -1.0, zeroFill("-1.", 100, "")},
  480. // Comparison of padding rules with C printf.
  481. /*
  482. C program:
  483. #include <stdio.h>
  484. char *format[] = {
  485. "[%.2f]",
  486. "[% .2f]",
  487. "[%+.2f]",
  488. "[%7.2f]",
  489. "[% 7.2f]",
  490. "[%+7.2f]",
  491. "[%07.2f]",
  492. "[% 07.2f]",
  493. "[%+07.2f]",
  494. };
  495. int main(void) {
  496. int i;
  497. for(i = 0; i < 9; i++) {
  498. printf("%s: ", format[i]);
  499. printf(format[i], 1.0);
  500. printf(" ");
  501. printf(format[i], -1.0);
  502. printf("\n");
  503. }
  504. }
  505. Output:
  506. [%.2f]: [1.00] [-1.00]
  507. [% .2f]: [ 1.00] [-1.00]
  508. [%+.2f]: [+1.00] [-1.00]
  509. [%7.2f]: [ 1.00] [ -1.00]
  510. [% 7.2f]: [ 1.00] [ -1.00]
  511. [%+7.2f]: [ +1.00] [ -1.00]
  512. [%07.2f]: [0001.00] [-001.00]
  513. [% 07.2f]: [ 001.00] [-001.00]
  514. [%+07.2f]: [+001.00] [-001.00]
  515. */
  516. {"%.2f", 1.0, "1.00"},
  517. {"%.2f", -1.0, "-1.00"},
  518. {"% .2f", 1.0, " 1.00"},
  519. {"% .2f", -1.0, "-1.00"},
  520. {"%+.2f", 1.0, "+1.00"},
  521. {"%+.2f", -1.0, "-1.00"},
  522. {"%7.2f", 1.0, " 1.00"},
  523. {"%7.2f", -1.0, " -1.00"},
  524. {"% 7.2f", 1.0, " 1.00"},
  525. {"% 7.2f", -1.0, " -1.00"},
  526. {"%+7.2f", 1.0, " +1.00"},
  527. {"%+7.2f", -1.0, " -1.00"},
  528. {"%07.2f", 1.0, "0001.00"},
  529. {"%07.2f", -1.0, "-001.00"},
  530. {"% 07.2f", 1.0, " 001.00"},
  531. {"% 07.2f", -1.0, "-001.00"},
  532. {"%+07.2f", 1.0, "+001.00"},
  533. {"%+07.2f", -1.0, "-001.00"},
  534. // Complex numbers: exhaustively tested in TestComplexFormatting.
  535. {"%7.2f", 1 + 2i, "( 1.00 +2.00i)"},
  536. {"%+07.2f", -1 - 2i, "(-001.00-002.00i)"},
  537. // Zero padding does not apply to infinities.
  538. {"%020f", math.Inf(-1), " -Inf"},
  539. {"%020f", math.Inf(+1), " +Inf"},
  540. {"% 020f", math.Inf(-1), " -Inf"},
  541. {"% 020f", math.Inf(+1), " Inf"},
  542. {"%+020f", math.Inf(-1), " -Inf"},
  543. {"%+020f", math.Inf(+1), " +Inf"},
  544. {"%20f", -1.0, " -1.000000"},
  545. // Make sure we can handle very large widths.
  546. {"%0100f", -1.0, zeroFill("-", 99, "1.000000")},
  547. // Complex fmt used to leave the plus flag set for future entries in the array
  548. // causing +2+0i and +3+0i instead of 2+0i and 3+0i.
  549. {"%v", []complex64{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
  550. {"%v", []complex128{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
  551. // Incomplete format specification caused crash.
  552. {"%.", 3, "%!.(int=3)"},
  553. // Used to panic with out-of-bounds for very large numeric representations.
  554. // nByte is set to handle one bit per uint64 in %b format, with a negative number.
  555. // See issue 6777.
  556. {"%#064x", 1, zeroFill("0x", 64, "1")},
  557. {"%#064x", -1, zeroFill("-0x", 63, "1")},
  558. {"%#064b", 1, zeroFill("", 64, "1")},
  559. {"%#064b", -1, zeroFill("-", 63, "1")},
  560. {"%#064o", 1, zeroFill("", 64, "1")},
  561. {"%#064o", -1, zeroFill("-", 63, "1")},
  562. {"%#064d", 1, zeroFill("", 64, "1")},
  563. {"%#064d", -1, zeroFill("-", 63, "1")},
  564. // Test that we handle the crossover above the size of uint64
  565. {"%#072x", 1, zeroFill("0x", 72, "1")},
  566. {"%#072x", -1, zeroFill("-0x", 71, "1")},
  567. {"%#072b", 1, zeroFill("", 72, "1")},
  568. {"%#072b", -1, zeroFill("-", 71, "1")},
  569. {"%#072o", 1, zeroFill("", 72, "1")},
  570. {"%#072o", -1, zeroFill("-", 71, "1")},
  571. {"%#072d", 1, zeroFill("", 72, "1")},
  572. {"%#072d", -1, zeroFill("-", 71, "1")},
  573. // Padding for complex numbers. Has been bad, then fixed, then bad again.
  574. {"%+10.2f", +104.66 + 440.51i, "( +104.66 +440.51i)"},
  575. {"%+10.2f", -104.66 + 440.51i, "( -104.66 +440.51i)"},
  576. {"%+10.2f", +104.66 - 440.51i, "( +104.66 -440.51i)"},
  577. {"%+10.2f", -104.66 - 440.51i, "( -104.66 -440.51i)"},
  578. {"%+010.2f", +104.66 + 440.51i, "(+000104.66+000440.51i)"},
  579. {"%+010.2f", -104.66 + 440.51i, "(-000104.66+000440.51i)"},
  580. {"%+010.2f", +104.66 - 440.51i, "(+000104.66-000440.51i)"},
  581. {"%+010.2f", -104.66 - 440.51i, "(-000104.66-000440.51i)"},
  582. // []T where type T is a byte with a Stringer method.
  583. {"%v", byteStringerSlice, "[X X X X]"},
  584. {"%s", byteStringerSlice, "abcd"},
  585. {"%q", byteStringerSlice, "\"abcd\""},
  586. {"%x", byteStringerSlice, "61626364"},
  587. {"%#v", byteStringerSlice, "[]fmt_test.byteStringer{0x61, 0x62, 0x63, 0x64}"},
  588. // And the same for Formatter.
  589. {"%v", byteFormatterSlice, "[X X X X]"},
  590. {"%s", byteFormatterSlice, "abcd"},
  591. {"%q", byteFormatterSlice, "\"abcd\""},
  592. {"%x", byteFormatterSlice, "61626364"},
  593. // This next case seems wrong, but the docs say the Formatter wins here.
  594. {"%#v", byteFormatterSlice, "[]fmt_test.byteFormatter{X, X, X, X}"},
  595. }
  596. // zeroFill generates zero-filled strings of the specified width. The length
  597. // of the suffix (but not the prefix) is compensated for in the width calculation.
  598. func zeroFill(prefix string, width int, suffix string) string {
  599. return prefix + strings.Repeat("0", width-len(suffix)) + suffix
  600. }
  601. func TestSprintf(t *testing.T) {
  602. for _, tt := range fmtTests {
  603. s := Sprintf(tt.fmt, tt.val)
  604. if i := strings.Index(tt.out, "PTR"); i >= 0 {
  605. pattern := "PTR"
  606. chars := "0123456789abcdefABCDEF"
  607. switch {
  608. case strings.HasPrefix(tt.out[i:], "PTR_d"):
  609. pattern = "PTR_d"
  610. chars = chars[:10]
  611. case strings.HasPrefix(tt.out[i:], "PTR_o"):
  612. pattern = "PTR_o"
  613. chars = chars[:8]
  614. case strings.HasPrefix(tt.out[i:], "PTR_x"):
  615. pattern = "PTR_x"
  616. }
  617. j := i
  618. for ; j < len(s); j++ {
  619. c := s[j]
  620. if !strings.ContainsRune(chars, rune(c)) {
  621. break
  622. }
  623. }
  624. s = s[0:i] + pattern + s[j:]
  625. }
  626. if s != tt.out {
  627. if _, ok := tt.val.(string); ok {
  628. // Don't requote the already-quoted strings.
  629. // It's too confusing to read the errors.
  630. t.Errorf("Sprintf(%q, %q) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
  631. } else {
  632. t.Errorf("Sprintf(%q, %v) = %q want %q", tt.fmt, tt.val, s, tt.out)
  633. }
  634. }
  635. }
  636. }
  637. // TestComplexFormatting checks that a complex always formats to the same
  638. // thing as if done by hand with two singleton prints.
  639. func TestComplexFormatting(t *testing.T) {
  640. var yesNo = []bool{true, false}
  641. var values = []float64{1, 0, -1, math.Inf(1), math.Inf(-1), math.NaN()}
  642. for _, plus := range yesNo {
  643. for _, zero := range yesNo {
  644. for _, space := range yesNo {
  645. for _, char := range "fFeEgG" {
  646. realFmt := "%"
  647. if zero {
  648. realFmt += "0"
  649. }
  650. if space {
  651. realFmt += " "
  652. }
  653. if plus {
  654. realFmt += "+"
  655. }
  656. realFmt += "10.2"
  657. realFmt += string(char)
  658. // Imaginary part always has a sign, so force + and ignore space.
  659. imagFmt := "%"
  660. if zero {
  661. imagFmt += "0"
  662. }
  663. imagFmt += "+"
  664. imagFmt += "10.2"
  665. imagFmt += string(char)
  666. for _, realValue := range values {
  667. for _, imagValue := range values {
  668. one := Sprintf(realFmt, complex(realValue, imagValue))
  669. two := Sprintf("("+realFmt+imagFmt+"i)", realValue, imagValue)
  670. if one != two {
  671. t.Error(f, one, two)
  672. }
  673. }
  674. }
  675. }
  676. }
  677. }
  678. }
  679. }
  680. type SE []interface{} // slice of empty; notational compactness.
  681. var reorderTests = []struct {
  682. fmt string
  683. val SE
  684. out string
  685. }{
  686. {"%[1]d", SE{1}, "1"},
  687. {"%[2]d", SE{2, 1}, "1"},
  688. {"%[2]d %[1]d", SE{1, 2}, "2 1"},
  689. {"%[2]*[1]d", SE{2, 5}, " 2"},
  690. {"%6.2f", SE{12.0}, " 12.00"}, // Explicit version of next line.
  691. {"%[3]*.[2]*[1]f", SE{12.0, 2, 6}, " 12.00"},
  692. {"%[1]*.[2]*[3]f", SE{6, 2, 12.0}, " 12.00"},
  693. {"%10f", SE{12.0}, " 12.000000"},
  694. {"%[1]*[3]f", SE{10, 99, 12.0}, " 12.000000"},
  695. {"%.6f", SE{12.0}, "12.000000"}, // Explicit version of next line.
  696. {"%.[1]*[3]f", SE{6, 99, 12.0}, "12.000000"},
  697. {"%6.f", SE{12.0}, " 12"}, // // Explicit version of next line; empty precision means zero.
  698. {"%[1]*.[3]f", SE{6, 3, 12.0}, " 12"},
  699. // An actual use! Print the same arguments twice.
  700. {"%d %d %d %#[1]o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015"},
  701. // Erroneous cases.
  702. {"%[d", SE{2, 1}, "%!d(BADINDEX)"},
  703. {"%]d", SE{2, 1}, "%!](int=2)d%!(EXTRA int=1)"},
  704. {"%[]d", SE{2, 1}, "%!d(BADINDEX)"},
  705. {"%[-3]d", SE{2, 1}, "%!d(BADINDEX)"},
  706. {"%[99]d", SE{2, 1}, "%!d(BADINDEX)"},
  707. {"%[3]", SE{2, 1}, "%!(NOVERB)"},
  708. {"%[1].2d", SE{5, 6}, "%!d(BADINDEX)"},
  709. {"%[1]2d", SE{2, 1}, "%!d(BADINDEX)"},
  710. {"%3.[2]d", SE{7}, "%!d(BADINDEX)"},
  711. {"%.[2]d", SE{7}, "%!d(BADINDEX)"},
  712. {"%d %d %d %#[1]o %#o %#o %#o", SE{11, 12, 13}, "11 12 13 013 014 015 %!o(MISSING)"},
  713. {"%[5]d %[2]d %d", SE{1, 2, 3}, "%!d(BADINDEX) 2 3"},
  714. {"%d %[3]d %d", SE{1, 2}, "1 %!d(BADINDEX) 2"}, // Erroneous index does not affect sequence.
  715. }
  716. func TestReorder(t *testing.T) {
  717. for _, tt := range reorderTests {
  718. s := Sprintf(tt.fmt, tt.val...)
  719. if s != tt.out {
  720. t.Errorf("Sprintf(%q, %v) = <%s> want <%s>", tt.fmt, tt.val, s, tt.out)
  721. } else {
  722. }
  723. }
  724. }
  725. func BenchmarkSprintfEmpty(b *testing.B) {
  726. b.RunParallel(func(pb *testing.PB) {
  727. for pb.Next() {
  728. Sprintf("")
  729. }
  730. })
  731. }
  732. func BenchmarkSprintfString(b *testing.B) {
  733. b.RunParallel(func(pb *testing.PB) {
  734. for pb.Next() {
  735. Sprintf("%s", "hello")
  736. }
  737. })
  738. }
  739. func BenchmarkSprintfInt(b *testing.B) {
  740. b.RunParallel(func(pb *testing.PB) {
  741. for pb.Next() {
  742. Sprintf("%d", 5)
  743. }
  744. })
  745. }
  746. func BenchmarkSprintfIntInt(b *testing.B) {
  747. b.RunParallel(func(pb *testing.PB) {
  748. for pb.Next() {
  749. Sprintf("%d %d", 5, 6)
  750. }
  751. })
  752. }
  753. func BenchmarkSprintfPrefixedInt(b *testing.B) {
  754. b.RunParallel(func(pb *testing.PB) {
  755. for pb.Next() {
  756. Sprintf("This is some meaningless prefix text that needs to be scanned %d", 6)
  757. }
  758. })
  759. }
  760. func BenchmarkSprintfFloat(b *testing.B) {
  761. b.RunParallel(func(pb *testing.PB) {
  762. for pb.Next() {
  763. Sprintf("%g", 5.23184)
  764. }
  765. })
  766. }
  767. func BenchmarkManyArgs(b *testing.B) {
  768. b.RunParallel(func(pb *testing.PB) {
  769. var buf bytes.Buffer
  770. for pb.Next() {
  771. buf.Reset()
  772. Fprintf(&buf, "%2d/%2d/%2d %d:%d:%d %s %s\n", 3, 4, 5, 11, 12, 13, "hello", "world")
  773. }
  774. })
  775. }
  776. func BenchmarkFprintInt(b *testing.B) {
  777. var buf bytes.Buffer
  778. for i := 0; i < b.N; i++ {
  779. buf.Reset()
  780. Fprint(&buf, 123456)
  781. }
  782. }
  783. func BenchmarkFprintIntNoAlloc(b *testing.B) {
  784. var x interface{} = 123456
  785. var buf bytes.Buffer
  786. for i := 0; i < b.N; i++ {
  787. buf.Reset()
  788. Fprint(&buf, x)
  789. }
  790. }
  791. var mallocBuf bytes.Buffer
  792. var mallocPointer *int // A pointer so we know the interface value won't allocate.
  793. // gccgo numbers are different because gccgo does not have escape
  794. // analysis yet.
  795. var mallocTest = []struct {
  796. count int
  797. desc string
  798. fn func()
  799. }{
  800. {5, `Sprintf("")`, func() { Sprintf("") }},
  801. {5, `Sprintf("xxx")`, func() { Sprintf("xxx") }},
  802. {5, `Sprintf("%x")`, func() { Sprintf("%x", 7) }},
  803. {5, `Sprintf("%s")`, func() { Sprintf("%s", "hello") }},
  804. {5, `Sprintf("%x %x")`, func() { Sprintf("%x %x", 7, 112) }},
  805. {20, `Sprintf("%g")`, func() { Sprintf("%g", float32(3.14159)) }}, // TODO: Can this be 1?
  806. {5, `Fprintf(buf, "%s")`, func() { mallocBuf.Reset(); Fprintf(&mallocBuf, "%s", "hello") }},
  807. // If the interface value doesn't need to allocate, amortized allocation overhead should be zero.
  808. {5, `Fprintf(buf, "%x %x %x")`, func() {
  809. mallocBuf.Reset()
  810. Fprintf(&mallocBuf, "%x %x %x", mallocPointer, mallocPointer, mallocPointer)
  811. }},
  812. }
  813. var _ bytes.Buffer
  814. func TestCountMallocs(t *testing.T) {
  815. if testing.Short() {
  816. t.Skip("skipping malloc count in short mode")
  817. }
  818. if runtime.GOMAXPROCS(0) > 1 {
  819. t.Skip("skipping; GOMAXPROCS>1")
  820. }
  821. for _, mt := range mallocTest {
  822. mallocs := testing.AllocsPerRun(100, mt.fn)
  823. if got, max := mallocs, float64(mt.count); got > max {
  824. t.Errorf("%s: got %v allocs, want <=%v", mt.desc, got, max)
  825. }
  826. }
  827. }
  828. type flagPrinter struct{}
  829. func (flagPrinter) Format(f State, c rune) {
  830. s := "%"
  831. for i := 0; i < 128; i++ {
  832. if f.Flag(i) {
  833. s += string(i)
  834. }
  835. }
  836. if w, ok := f.Width(); ok {
  837. s += Sprintf("%d", w)
  838. }
  839. if p, ok := f.Precision(); ok {
  840. s += Sprintf(".%d", p)
  841. }
  842. s += string(c)
  843. io.WriteString(f, "["+s+"]")
  844. }
  845. var flagtests = []struct {
  846. in string
  847. out string
  848. }{
  849. {"%a", "[%a]"},
  850. {"%-a", "[%-a]"},
  851. {"%+a", "[%+a]"},
  852. {"%#a", "[%#a]"},
  853. {"% a", "[% a]"},
  854. {"%0a", "[%0a]"},
  855. {"%1.2a", "[%1.2a]"},
  856. {"%-1.2a", "[%-1.2a]"},
  857. {"%+1.2a", "[%+1.2a]"},
  858. {"%-+1.2a", "[%+-1.2a]"},
  859. {"%-+1.2abc", "[%+-1.2a]bc"},
  860. {"%-1.2abc", "[%-1.2a]bc"},
  861. }
  862. func TestFlagParser(t *testing.T) {
  863. var flagprinter flagPrinter
  864. for _, tt := range flagtests {
  865. s := Sprintf(tt.in, &flagprinter)
  866. if s != tt.out {
  867. t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out)
  868. }
  869. }
  870. }
  871. func TestStructPrinter(t *testing.T) {
  872. type T struct {
  873. a string
  874. b string
  875. c int
  876. }
  877. var s T
  878. s.a = "abc"
  879. s.b = "def"
  880. s.c = 123
  881. var tests = []struct {
  882. fmt string
  883. out string
  884. }{
  885. {"%v", "{abc def 123}"},
  886. {"%+v", "{a:abc b:def c:123}"},
  887. {"%#v", `fmt_test.T{a:"abc", b:"def", c:123}`},
  888. }
  889. for _, tt := range tests {
  890. out := Sprintf(tt.fmt, s)
  891. if out != tt.out {
  892. t.Errorf("Sprintf(%q, s) = %#q, want %#q", tt.fmt, out, tt.out)
  893. }
  894. // The same but with a pointer.
  895. out = Sprintf(tt.fmt, &s)
  896. if out != "&"+tt.out {
  897. t.Errorf("Sprintf(%q, &s) = %#q, want %#q", tt.fmt, out, "&"+tt.out)
  898. }
  899. }
  900. }
  901. func TestSlicePrinter(t *testing.T) {
  902. slice := []int{}
  903. s := Sprint(slice)
  904. if s != "[]" {
  905. t.Errorf("empty slice printed as %q not %q", s, "[]")
  906. }
  907. slice = []int{1, 2, 3}
  908. s = Sprint(slice)
  909. if s != "[1 2 3]" {
  910. t.Errorf("slice: got %q expected %q", s, "[1 2 3]")
  911. }
  912. s = Sprint(&slice)
  913. if s != "&[1 2 3]" {
  914. t.Errorf("&slice: got %q expected %q", s, "&[1 2 3]")
  915. }
  916. }
  917. // presentInMap checks map printing using substrings so we don't depend on the
  918. // print order.
  919. func presentInMap(s string, a []string, t *testing.T) {
  920. for i := 0; i < len(a); i++ {
  921. loc := strings.Index(s, a[i])
  922. if loc < 0 {
  923. t.Errorf("map print: expected to find %q in %q", a[i], s)
  924. }
  925. // make sure the match ends here
  926. loc += len(a[i])
  927. if loc >= len(s) || (s[loc] != ' ' && s[loc] != ']') {
  928. t.Errorf("map print: %q not properly terminated in %q", a[i], s)
  929. }
  930. }
  931. }
  932. func TestMapPrinter(t *testing.T) {
  933. m0 := make(map[int]string)
  934. s := Sprint(m0)
  935. if s != "map[]" {
  936. t.Errorf("empty map printed as %q not %q", s, "map[]")
  937. }
  938. m1 := map[int]string{1: "one", 2: "two", 3: "three"}
  939. a := []string{"1:one", "2:two", "3:three"}
  940. presentInMap(Sprintf("%v", m1), a, t)
  941. presentInMap(Sprint(m1), a, t)
  942. // Pointer to map prints the same but with initial &.
  943. if !strings.HasPrefix(Sprint(&m1), "&") {
  944. t.Errorf("no initial & for address of map")
  945. }
  946. presentInMap(Sprintf("%v", &m1), a, t)
  947. presentInMap(Sprint(&m1), a, t)
  948. }
  949. func TestEmptyMap(t *testing.T) {
  950. const emptyMapStr = "map[]"
  951. var m map[string]int
  952. s := Sprint(m)
  953. if s != emptyMapStr {
  954. t.Errorf("nil map printed as %q not %q", s, emptyMapStr)
  955. }
  956. m = make(map[string]int)
  957. s = Sprint(m)
  958. if s != emptyMapStr {
  959. t.Errorf("empty map printed as %q not %q", s, emptyMapStr)
  960. }
  961. }
  962. // TestBlank checks that Sprint (and hence Print, Fprint) puts spaces in the
  963. // right places, that is, between arg pairs in which neither is a string.
  964. func TestBlank(t *testing.T) {
  965. got := Sprint("<", 1, ">:", 1, 2, 3, "!")
  966. expect := "<1>:1 2 3!"
  967. if got != expect {
  968. t.Errorf("got %q expected %q", got, expect)
  969. }
  970. }
  971. // TestBlankln checks that Sprintln (and hence Println, Fprintln) puts spaces in
  972. // the right places, that is, between all arg pairs.
  973. func TestBlankln(t *testing.T) {
  974. got := Sprintln("<", 1, ">:", 1, 2, 3, "!")
  975. expect := "< 1 >: 1 2 3 !\n"
  976. if got != expect {
  977. t.Errorf("got %q expected %q", got, expect)
  978. }
  979. }
  980. // TestFormatterPrintln checks Formatter with Sprint, Sprintln, Sprintf.
  981. func TestFormatterPrintln(t *testing.T) {
  982. f := F(1)
  983. expect := "<v=F(1)>\n"
  984. s := Sprint(f, "\n")
  985. if s != expect {
  986. t.Errorf("Sprint wrong with Formatter: expected %q got %q", expect, s)
  987. }
  988. s = Sprintln(f)
  989. if s != expect {
  990. t.Errorf("Sprintln wrong with Formatter: expected %q got %q", expect, s)
  991. }
  992. s = Sprintf("%v\n", f)
  993. if s != expect {
  994. t.Errorf("Sprintf wrong with Formatter: expected %q got %q", expect, s)
  995. }
  996. }
  997. func args(a ...interface{}) []interface{} { return a }
  998. var startests = []struct {
  999. fmt string
  1000. in []interface{}
  1001. out string
  1002. }{
  1003. {"%*d", args(4, 42), " 42"},
  1004. {"%.*d", args(4, 42), "0042"},
  1005. {"%*.*d", args(8, 4, 42), " 0042"},
  1006. {"%0*d", args(4, 42), "0042"},
  1007. {"%-*d", args(4, 42), "42 "},
  1008. // erroneous
  1009. {"%*d", args(nil, 42), "%!(BADWIDTH)42"},
  1010. {"%.*d", args(nil, 42), "%!(BADPREC)42"},
  1011. {"%*d", args(5, "foo"), "%!d(string= foo)"},
  1012. {"%*% %d", args(20, 5), "% 5"},
  1013. {"%*", args(4), "%!(NOVERB)"},
  1014. {"%*d", args(int32(4), 42), "%!(BADWIDTH)42"},
  1015. }
  1016. func TestWidthAndPrecision(t *testing.T) {
  1017. for _, tt := range startests {
  1018. s := Sprintf(tt.fmt, tt.in...)
  1019. if s != tt.out {
  1020. t.Errorf("%q: got %q expected %q", tt.fmt, s, tt.out)
  1021. }
  1022. }
  1023. }
  1024. // Panic is a type that panics in String.
  1025. type Panic struct {
  1026. message interface{}
  1027. }
  1028. // Value receiver.
  1029. func (p Panic) GoString() string {
  1030. panic(p.message)
  1031. }
  1032. // Value receiver.
  1033. func (p Panic) String() string {
  1034. panic(p.message)
  1035. }
  1036. // PanicF is a type that panics in Format.
  1037. type PanicF struct {
  1038. message interface{}
  1039. }
  1040. // Value receiver.
  1041. func (p PanicF) Format(f State, c rune) {
  1042. panic(p.message)
  1043. }
  1044. var panictests = []struct {
  1045. fmt string
  1046. in interface{}
  1047. out string
  1048. }{
  1049. // String
  1050. {"%s", (*Panic)(nil), "<nil>"}, // nil pointer special case
  1051. {"%s", Panic{io.ErrUnexpectedEOF}, "%!s(PANIC=unexpected EOF)"},
  1052. {"%s", Panic{3}, "%!s(PANIC=3)"},
  1053. // GoString
  1054. {"%#v", (*Panic)(nil), "<nil>"}, // nil pointer special case
  1055. {"%#v", Panic{io.ErrUnexpectedEOF}, "%!v(PANIC=unexpected EOF)"},
  1056. {"%#v", Panic{3}, "%!v(PANIC=3)"},
  1057. // Format
  1058. {"%s", (*PanicF)(nil), "<nil>"}, // nil pointer special case
  1059. {"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=unexpected EOF)"},
  1060. {"%s", PanicF{3}, "%!s(PANIC=3)"},
  1061. }
  1062. func TestPanics(t *testing.T) {
  1063. for i, tt := range panictests {
  1064. s := Sprintf(tt.fmt, tt.in)
  1065. if s != tt.out {
  1066. t.Errorf("%d: %q: got %q expected %q", i, tt.fmt, s, tt.out)
  1067. }
  1068. }
  1069. }
  1070. // recurCount tests that erroneous String routine doesn't cause fatal recursion.
  1071. var recurCount = 0
  1072. type Recur struct {
  1073. i int
  1074. failed *bool
  1075. }
  1076. func (r *Recur) String() string {
  1077. if recurCount++; recurCount > 10 {
  1078. *r.failed = true
  1079. return "FAIL"
  1080. }
  1081. // This will call badVerb. Before the fix, that would cause us to recur into
  1082. // this routine to print %!p(value). Now we don't call the user's method
  1083. // during an error.
  1084. return Sprintf("recur@%p value: %d", r, r.i)
  1085. }
  1086. func TestBadVerbRecursion(t *testing.T) {
  1087. failed := false
  1088. r := &Recur{3, &failed}
  1089. Sprintf("recur@%p value: %d\n", &r, r.i)
  1090. if failed {
  1091. t.Error("fail with pointer")
  1092. }
  1093. failed = false
  1094. r = &Recur{4, &failed}
  1095. Sprintf("recur@%p, value: %d\n", r, r.i)
  1096. if failed {
  1097. t.Error("fail with value")
  1098. }
  1099. }
  1100. func TestIsSpace(t *testing.T) {
  1101. // This tests the internal isSpace function.
  1102. // IsSpace = isSpace is defined in export_test.go.
  1103. for i := rune(0); i <= unicode.MaxRune; i++ {
  1104. if IsSpace(i) != unicode.IsSpace(i) {
  1105. t.Errorf("isSpace(%U) = %v, want %v", i, IsSpace(i), unicode.IsSpace(i))
  1106. }
  1107. }
  1108. }
  1109. func TestNilDoesNotBecomeTyped(t *testing.T) {
  1110. type A struct{}
  1111. type B struct{}
  1112. var a *A = nil
  1113. var b B = B{}
  1114. got := Sprintf("%s %s %s %s %s", nil, a, nil, b, nil)
  1115. const expect = "%!s(<nil>) %!s(*fmt_test.A=<nil>) %!s(<nil>) {} %!s(<nil>)"
  1116. if got != expect {
  1117. t.Errorf("expected:\n\t%q\ngot:\n\t%q", expect, got)
  1118. }
  1119. }
  1120. var formatterFlagTests = []struct {
  1121. in string
  1122. val interface{}
  1123. out string
  1124. }{
  1125. // scalar values with the (unused by fmt) 'a' verb.
  1126. {"%a", flagPrinter{}, "[%a]"},
  1127. {"%-a", flagPrinter{}, "[%-a]"},
  1128. {"%+a", flagPrinter{}, "[%+a]"},
  1129. {"%#a", flagPrinter{}, "[%#a]"},
  1130. {"% a", flagPrinter{}, "[% a]"},
  1131. {"%0a", flagPrinter{}, "[%0a]"},
  1132. {"%1.2a", flagPrinter{}, "[%1.2a]"},
  1133. {"%-1.2a", flagPrinter{}, "[%-1.2a]"},
  1134. {"%+1.2a", flagPrinter{}, "[%+1.2a]"},
  1135. {"%-+1.2a", flagPrinter{}, "[%+-1.2a]"},
  1136. {"%-+1.2abc", flagPrinter{}, "[%+-1.2a]bc"},
  1137. {"%-1.2abc", flagPrinter{}, "[%-1.2a]bc"},
  1138. // composite values with the 'a' verb
  1139. {"%a", [1]flagPrinter{}, "[[%a]]"},
  1140. {"%-a", [1]flagPrinter{}, "[[%-a]]"},
  1141. {"%+a", [1]flagPrinter{}, "[[%+a]]"},
  1142. {"%#a", [1]flagPrinter{}, "[[%#a]]"},
  1143. {"% a", [1]flagPrinter{}, "[[% a]]"},
  1144. {"%0a", [1]flagPrinter{}, "[[%0a]]"},
  1145. {"%1.2a", [1]flagPrinter{}, "[[%1.2a]]"},
  1146. {"%-1.2a", [1]flagPrinter{}, "[[%-1.2a]]"},
  1147. {"%+1.2a", [1]flagPrinter{}, "[[%+1.2a]]"},
  1148. {"%-+1.2a", [1]flagPrinter{}, "[[%+-1.2a]]"},
  1149. {"%-+1.2abc", [1]flagPrinter{}, "[[%+-1.2a]]bc"},
  1150. {"%-1.2abc", [1]flagPrinter{}, "[[%-1.2a]]bc"},
  1151. // simple values with the 'v' verb
  1152. {"%v", flagPrinter{}, "[%v]"},
  1153. {"%-v", flagPrinter{}, "[%-v]"},
  1154. {"%+v", flagPrinter{}, "[%+v]"},
  1155. {"%#v", flagPrinter{}, "[%#v]"},
  1156. {"% v", flagPrinter{}, "[% v]"},
  1157. {"%0v", flagPrinter{}, "[%0v]"},
  1158. {"%1.2v", flagPrinter{}, "[%1.2v]"},
  1159. {"%-1.2v", flagPrinter{}, "[%-1.2v]"},
  1160. {"%+1.2v", flagPrinter{}, "[%+1.2v]"},
  1161. {"%-+1.2v", flagPrinter{}, "[%+-1.2v]"},
  1162. {"%-+1.2vbc", flagPrinter{}, "[%+-1.2v]bc"},
  1163. {"%-1.2vbc", flagPrinter{}, "[%-1.2v]bc"},
  1164. // composite values with the 'v' verb.
  1165. {"%v", [1]flagPrinter{}, "[[%v]]"},
  1166. {"%-v", [1]flagPrinter{}, "[[%-v]]"},
  1167. {"%+v", [1]flagPrinter{}, "[[%+v]]"},
  1168. {"%#v", [1]flagPrinter{}, "[1]fmt_test.flagPrinter{[%#v]}"},
  1169. {"% v", [1]flagPrinter{}, "[[% v]]"},
  1170. {"%0v", [1]flagPrinter{}, "[[%0v]]"},
  1171. {"%1.2v", [1]flagPrinter{}, "[[%1.2v]]"},
  1172. {"%-1.2v", [1]flagPrinter{}, "[[%-1.2v]]"},
  1173. {"%+1.2v", [1]flagPrinter{}, "[[%+1.2v]]"},
  1174. {"%-+1.2v", [1]flagPrinter{}, "[[%+-1.2v]]"},
  1175. {"%-+1.2vbc", [1]flagPrinter{}, "[[%+-1.2v]]bc"},
  1176. {"%-1.2vbc", [1]flagPrinter{}, "[[%-1.2v]]bc"},
  1177. }
  1178. func TestFormatterFlags(t *testing.T) {
  1179. for _, tt := range formatterFlagTests {
  1180. s := Sprintf(tt.in, tt.val)
  1181. if s != tt.out {
  1182. t.Errorf("Sprintf(%q, %T) = %q, want %q", tt.in, tt.val, s, tt.out)
  1183. }
  1184. }
  1185. }