format.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /*
  2. Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information.
  3. */
  4. // untested sections: 4
  5. package format
  6. import (
  7. "fmt"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // Use MaxDepth to set the maximum recursion depth when printing deeply nested objects
  14. var MaxDepth = uint(10)
  15. /*
  16. By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output.
  17. Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead.
  18. Note that GoString and String don't always have all the information you need to understand why a test failed!
  19. */
  20. var UseStringerRepresentation = false
  21. /*
  22. Print the content of context objects. By default it will be suppressed.
  23. Set PrintContextObjects = true to enable printing of the context internals.
  24. */
  25. var PrintContextObjects = false
  26. // TruncatedDiff choose if we should display a truncated pretty diff or not
  27. var TruncatedDiff = true
  28. // TruncateThreshold (default 50) specifies the maximum length string to print in string comparison assertion error
  29. // messages.
  30. var TruncateThreshold uint = 50
  31. // CharactersAroundMismatchToInclude (default 5) specifies how many contextual characters should be printed before and
  32. // after the first diff location in a truncated string assertion error message.
  33. var CharactersAroundMismatchToInclude uint = 5
  34. // Ctx interface defined here to keep backwards compatibility with go < 1.7
  35. // It matches the context.Context interface
  36. type Ctx interface {
  37. Deadline() (deadline time.Time, ok bool)
  38. Done() <-chan struct{}
  39. Err() error
  40. Value(key interface{}) interface{}
  41. }
  42. var contextType = reflect.TypeOf((*Ctx)(nil)).Elem()
  43. var timeType = reflect.TypeOf(time.Time{})
  44. //The default indentation string emitted by the format package
  45. var Indent = " "
  46. var longFormThreshold = 20
  47. /*
  48. Generates a formatted matcher success/failure message of the form:
  49. Expected
  50. <pretty printed actual>
  51. <message>
  52. <pretty printed expected>
  53. If expected is omitted, then the message looks like:
  54. Expected
  55. <pretty printed actual>
  56. <message>
  57. */
  58. func Message(actual interface{}, message string, expected ...interface{}) string {
  59. if len(expected) == 0 {
  60. return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message)
  61. }
  62. return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1))
  63. }
  64. /*
  65. Generates a nicely formatted matcher success / failure message
  66. Much like Message(...), but it attempts to pretty print diffs in strings
  67. Expected
  68. <string>: "...aaaaabaaaaa..."
  69. to equal |
  70. <string>: "...aaaaazaaaaa..."
  71. */
  72. func MessageWithDiff(actual, message, expected string) string {
  73. if TruncatedDiff && len(actual) >= int(TruncateThreshold) && len(expected) >= int(TruncateThreshold) {
  74. diffPoint := findFirstMismatch(actual, expected)
  75. formattedActual := truncateAndFormat(actual, diffPoint)
  76. formattedExpected := truncateAndFormat(expected, diffPoint)
  77. spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected)
  78. tabLength := 4
  79. spaceFromMessageToActual := tabLength + len("<string>: ") - len(message)
  80. padding := strings.Repeat(" ", spaceFromMessageToActual+spacesBeforeFormattedMismatch) + "|"
  81. return Message(formattedActual, message+padding, formattedExpected)
  82. }
  83. actual = escapedWithGoSyntax(actual)
  84. expected = escapedWithGoSyntax(expected)
  85. return Message(actual, message, expected)
  86. }
  87. func escapedWithGoSyntax(str string) string {
  88. withQuotes := fmt.Sprintf("%q", str)
  89. return withQuotes[1 : len(withQuotes)-1]
  90. }
  91. func truncateAndFormat(str string, index int) string {
  92. leftPadding := `...`
  93. rightPadding := `...`
  94. start := index - int(CharactersAroundMismatchToInclude)
  95. if start < 0 {
  96. start = 0
  97. leftPadding = ""
  98. }
  99. // slice index must include the mis-matched character
  100. lengthOfMismatchedCharacter := 1
  101. end := index + int(CharactersAroundMismatchToInclude) + lengthOfMismatchedCharacter
  102. if end > len(str) {
  103. end = len(str)
  104. rightPadding = ""
  105. }
  106. return fmt.Sprintf("\"%s\"", leftPadding+str[start:end]+rightPadding)
  107. }
  108. func findFirstMismatch(a, b string) int {
  109. aSlice := strings.Split(a, "")
  110. bSlice := strings.Split(b, "")
  111. for index, str := range aSlice {
  112. if index > len(bSlice)-1 {
  113. return index
  114. }
  115. if str != bSlice[index] {
  116. return index
  117. }
  118. }
  119. if len(b) > len(a) {
  120. return len(a) + 1
  121. }
  122. return 0
  123. }
  124. /*
  125. Pretty prints the passed in object at the passed in indentation level.
  126. Object recurses into deeply nested objects emitting pretty-printed representations of their components.
  127. Modify format.MaxDepth to control how deep the recursion is allowed to go
  128. Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of
  129. recursing into the object.
  130. Set PrintContextObjects to true to print the content of objects implementing context.Context
  131. */
  132. func Object(object interface{}, indentation uint) string {
  133. indent := strings.Repeat(Indent, int(indentation))
  134. value := reflect.ValueOf(object)
  135. return fmt.Sprintf("%s<%s>: %s", indent, formatType(object), formatValue(value, indentation))
  136. }
  137. /*
  138. IndentString takes a string and indents each line by the specified amount.
  139. */
  140. func IndentString(s string, indentation uint) string {
  141. components := strings.Split(s, "\n")
  142. result := ""
  143. indent := strings.Repeat(Indent, int(indentation))
  144. for i, component := range components {
  145. result += indent + component
  146. if i < len(components)-1 {
  147. result += "\n"
  148. }
  149. }
  150. return result
  151. }
  152. func formatType(object interface{}) string {
  153. t := reflect.TypeOf(object)
  154. if t == nil {
  155. return "nil"
  156. }
  157. switch t.Kind() {
  158. case reflect.Chan:
  159. v := reflect.ValueOf(object)
  160. return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap())
  161. case reflect.Ptr:
  162. return fmt.Sprintf("%T | %p", object, object)
  163. case reflect.Slice:
  164. v := reflect.ValueOf(object)
  165. return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap())
  166. case reflect.Map:
  167. v := reflect.ValueOf(object)
  168. return fmt.Sprintf("%T | len:%d", object, v.Len())
  169. default:
  170. return fmt.Sprintf("%T", object)
  171. }
  172. }
  173. func formatValue(value reflect.Value, indentation uint) string {
  174. if indentation > MaxDepth {
  175. return "..."
  176. }
  177. if isNilValue(value) {
  178. return "nil"
  179. }
  180. if UseStringerRepresentation {
  181. if value.CanInterface() {
  182. obj := value.Interface()
  183. switch x := obj.(type) {
  184. case fmt.GoStringer:
  185. return x.GoString()
  186. case fmt.Stringer:
  187. return x.String()
  188. }
  189. }
  190. }
  191. if !PrintContextObjects {
  192. if value.Type().Implements(contextType) && indentation > 1 {
  193. return "<suppressed context>"
  194. }
  195. }
  196. switch value.Kind() {
  197. case reflect.Bool:
  198. return fmt.Sprintf("%v", value.Bool())
  199. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  200. return fmt.Sprintf("%v", value.Int())
  201. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  202. return fmt.Sprintf("%v", value.Uint())
  203. case reflect.Uintptr:
  204. return fmt.Sprintf("0x%x", value.Uint())
  205. case reflect.Float32, reflect.Float64:
  206. return fmt.Sprintf("%v", value.Float())
  207. case reflect.Complex64, reflect.Complex128:
  208. return fmt.Sprintf("%v", value.Complex())
  209. case reflect.Chan:
  210. return fmt.Sprintf("0x%x", value.Pointer())
  211. case reflect.Func:
  212. return fmt.Sprintf("0x%x", value.Pointer())
  213. case reflect.Ptr:
  214. return formatValue(value.Elem(), indentation)
  215. case reflect.Slice:
  216. return formatSlice(value, indentation)
  217. case reflect.String:
  218. return formatString(value.String(), indentation)
  219. case reflect.Array:
  220. return formatSlice(value, indentation)
  221. case reflect.Map:
  222. return formatMap(value, indentation)
  223. case reflect.Struct:
  224. if value.Type() == timeType && value.CanInterface() {
  225. t, _ := value.Interface().(time.Time)
  226. return t.Format(time.RFC3339Nano)
  227. }
  228. return formatStruct(value, indentation)
  229. case reflect.Interface:
  230. return formatValue(value.Elem(), indentation)
  231. default:
  232. if value.CanInterface() {
  233. return fmt.Sprintf("%#v", value.Interface())
  234. }
  235. return fmt.Sprintf("%#v", value)
  236. }
  237. }
  238. func formatString(object interface{}, indentation uint) string {
  239. if indentation == 1 {
  240. s := fmt.Sprintf("%s", object)
  241. components := strings.Split(s, "\n")
  242. result := ""
  243. for i, component := range components {
  244. if i == 0 {
  245. result += component
  246. } else {
  247. result += Indent + component
  248. }
  249. if i < len(components)-1 {
  250. result += "\n"
  251. }
  252. }
  253. return result
  254. } else {
  255. return fmt.Sprintf("%q", object)
  256. }
  257. }
  258. func formatSlice(v reflect.Value, indentation uint) string {
  259. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && isPrintableString(string(v.Bytes())) {
  260. return formatString(v.Bytes(), indentation)
  261. }
  262. l := v.Len()
  263. result := make([]string, l)
  264. longest := 0
  265. for i := 0; i < l; i++ {
  266. result[i] = formatValue(v.Index(i), indentation+1)
  267. if len(result[i]) > longest {
  268. longest = len(result[i])
  269. }
  270. }
  271. if longest > longFormThreshold {
  272. indenter := strings.Repeat(Indent, int(indentation))
  273. return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter)
  274. }
  275. return fmt.Sprintf("[%s]", strings.Join(result, ", "))
  276. }
  277. func formatMap(v reflect.Value, indentation uint) string {
  278. l := v.Len()
  279. result := make([]string, l)
  280. longest := 0
  281. for i, key := range v.MapKeys() {
  282. value := v.MapIndex(key)
  283. result[i] = fmt.Sprintf("%s: %s", formatValue(key, indentation+1), formatValue(value, indentation+1))
  284. if len(result[i]) > longest {
  285. longest = len(result[i])
  286. }
  287. }
  288. if longest > longFormThreshold {
  289. indenter := strings.Repeat(Indent, int(indentation))
  290. return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter)
  291. }
  292. return fmt.Sprintf("{%s}", strings.Join(result, ", "))
  293. }
  294. func formatStruct(v reflect.Value, indentation uint) string {
  295. t := v.Type()
  296. l := v.NumField()
  297. result := []string{}
  298. longest := 0
  299. for i := 0; i < l; i++ {
  300. structField := t.Field(i)
  301. fieldEntry := v.Field(i)
  302. representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1))
  303. result = append(result, representation)
  304. if len(representation) > longest {
  305. longest = len(representation)
  306. }
  307. }
  308. if longest > longFormThreshold {
  309. indenter := strings.Repeat(Indent, int(indentation))
  310. return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter)
  311. }
  312. return fmt.Sprintf("{%s}", strings.Join(result, ", "))
  313. }
  314. func isNilValue(a reflect.Value) bool {
  315. switch a.Kind() {
  316. case reflect.Invalid:
  317. return true
  318. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  319. return a.IsNil()
  320. }
  321. return false
  322. }
  323. /*
  324. Returns true when the string is entirely made of printable runes, false otherwise.
  325. */
  326. func isPrintableString(str string) bool {
  327. for _, runeValue := range str {
  328. if !strconv.IsPrint(runeValue) {
  329. return false
  330. }
  331. }
  332. return true
  333. }