tty_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package display
  14. import (
  15. "bytes"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "unicode/utf8"
  21. "gotest.tools/v3/assert"
  22. "github.com/docker/compose/v5/pkg/api"
  23. )
  24. func newTestWriter() (*ttyWriter, *bytes.Buffer) {
  25. var buf bytes.Buffer
  26. w := &ttyWriter{
  27. out: &buf,
  28. info: &buf,
  29. tasks: map[string]*task{},
  30. done: make(chan bool),
  31. mtx: &sync.Mutex{},
  32. operation: "pull",
  33. }
  34. return w, &buf
  35. }
  36. func addTask(w *ttyWriter, id, text, details string, status api.EventStatus) {
  37. t := &task{
  38. ID: id,
  39. parents: make(map[string]struct{}),
  40. startTime: time.Now(),
  41. text: text,
  42. details: details,
  43. status: status,
  44. spinner: NewSpinner(),
  45. }
  46. w.tasks[id] = t
  47. w.ids = append(w.ids, id)
  48. }
  49. // extractLines parses the output buffer and returns lines without ANSI control sequences
  50. func extractLines(buf *bytes.Buffer) []string {
  51. content := buf.String()
  52. // Split by newline
  53. rawLines := strings.Split(content, "\n")
  54. var lines []string
  55. for _, line := range rawLines {
  56. // Skip empty lines and lines that are just ANSI codes
  57. if lenAnsi(line) > 0 {
  58. lines = append(lines, line)
  59. }
  60. }
  61. return lines
  62. }
  63. func TestPrintWithDimensions_LinesFitTerminalWidth(t *testing.T) {
  64. testCases := []struct {
  65. name string
  66. taskID string
  67. status string
  68. details string
  69. terminalWidth int
  70. }{
  71. {
  72. name: "short task fits wide terminal",
  73. taskID: "Image foo",
  74. status: "Pulling",
  75. details: "layer abc123",
  76. terminalWidth: 100,
  77. },
  78. {
  79. name: "long details truncated to fit",
  80. taskID: "Image foo",
  81. status: "Pulling",
  82. details: "downloading layer sha256:abc123def456789xyz0123456789abcdef",
  83. terminalWidth: 50,
  84. },
  85. {
  86. name: "long taskID truncated to fit",
  87. taskID: "very-long-image-name-that-exceeds-terminal-width",
  88. status: "Pulling",
  89. details: "",
  90. terminalWidth: 40,
  91. },
  92. {
  93. name: "both long taskID and details",
  94. taskID: "my-very-long-service-name-here",
  95. status: "Downloading",
  96. details: "layer sha256:abc123def456789xyz0123456789",
  97. terminalWidth: 50,
  98. },
  99. {
  100. name: "narrow terminal",
  101. taskID: "service-name",
  102. status: "Pulling",
  103. details: "some details",
  104. terminalWidth: 35,
  105. },
  106. }
  107. for _, tc := range testCases {
  108. t.Run(tc.name, func(t *testing.T) {
  109. w, buf := newTestWriter()
  110. addTask(w, tc.taskID, tc.status, tc.details, api.Working)
  111. w.printWithDimensions(tc.terminalWidth, 24)
  112. lines := extractLines(buf)
  113. for i, line := range lines {
  114. lineLen := lenAnsi(line)
  115. assert.Assert(t, lineLen <= tc.terminalWidth,
  116. "line %d has length %d which exceeds terminal width %d: %q",
  117. i, lineLen, tc.terminalWidth, line)
  118. }
  119. })
  120. }
  121. }
  122. func TestPrintWithDimensions_MultipleTasksFitTerminalWidth(t *testing.T) {
  123. w, buf := newTestWriter()
  124. // Add multiple tasks with varying lengths
  125. addTask(w, "Image nginx", "Pulling", "layer sha256:abc123", api.Working)
  126. addTask(w, "Image postgres-database", "Pulling", "downloading", api.Working)
  127. addTask(w, "Image redis", "Pulled", "", api.Done)
  128. terminalWidth := 60
  129. w.printWithDimensions(terminalWidth, 24)
  130. lines := extractLines(buf)
  131. for i, line := range lines {
  132. lineLen := lenAnsi(line)
  133. assert.Assert(t, lineLen <= terminalWidth,
  134. "line %d has length %d which exceeds terminal width %d: %q",
  135. i, lineLen, terminalWidth, line)
  136. }
  137. }
  138. func TestPrintWithDimensions_VeryNarrowTerminal(t *testing.T) {
  139. w, buf := newTestWriter()
  140. addTask(w, "Image nginx", "Pulling", "details", api.Working)
  141. terminalWidth := 30
  142. w.printWithDimensions(terminalWidth, 24)
  143. lines := extractLines(buf)
  144. for i, line := range lines {
  145. lineLen := lenAnsi(line)
  146. assert.Assert(t, lineLen <= terminalWidth,
  147. "line %d has length %d which exceeds terminal width %d: %q",
  148. i, lineLen, terminalWidth, line)
  149. }
  150. }
  151. func TestPrintWithDimensions_TaskWithProgress(t *testing.T) {
  152. w, buf := newTestWriter()
  153. // Create parent task
  154. parent := &task{
  155. ID: "Image nginx",
  156. parents: make(map[string]struct{}),
  157. startTime: time.Now(),
  158. text: "Pulling",
  159. status: api.Working,
  160. spinner: NewSpinner(),
  161. }
  162. w.tasks["Image nginx"] = parent
  163. w.ids = append(w.ids, "Image nginx")
  164. // Create child tasks to trigger progress display
  165. for i := 0; i < 3; i++ {
  166. child := &task{
  167. ID: "layer" + string(rune('a'+i)),
  168. parents: map[string]struct{}{"Image nginx": {}},
  169. startTime: time.Now(),
  170. text: "Downloading",
  171. status: api.Working,
  172. total: 1000,
  173. current: 500,
  174. percent: 50,
  175. spinner: NewSpinner(),
  176. }
  177. w.tasks[child.ID] = child
  178. w.ids = append(w.ids, child.ID)
  179. }
  180. terminalWidth := 80
  181. w.printWithDimensions(terminalWidth, 24)
  182. lines := extractLines(buf)
  183. for i, line := range lines {
  184. lineLen := lenAnsi(line)
  185. assert.Assert(t, lineLen <= terminalWidth,
  186. "line %d has length %d which exceeds terminal width %d: %q",
  187. i, lineLen, terminalWidth, line)
  188. }
  189. }
  190. func TestAdjustLineWidth_DetailsCorrectlyTruncated(t *testing.T) {
  191. w := &ttyWriter{}
  192. lines := []lineData{
  193. {
  194. taskID: "Image foo",
  195. status: "Pulling",
  196. details: "downloading layer sha256:abc123def456789xyz",
  197. },
  198. }
  199. terminalWidth := 50
  200. timerLen := 5
  201. w.adjustLineWidth(lines, timerLen, terminalWidth)
  202. // Verify the line fits
  203. detailsLen := len(lines[0].details)
  204. if detailsLen > 0 {
  205. detailsLen++ // space before details
  206. }
  207. // widthWithoutDetails = 5 + prefix(0) + taskID(9) + progress(0) + status(7) + timer(5) = 26
  208. lineWidth := 5 + len(lines[0].taskID) + len(lines[0].status) + detailsLen + timerLen
  209. assert.Assert(t, lineWidth <= terminalWidth,
  210. "line width %d should not exceed terminal width %d (taskID=%q, details=%q)",
  211. lineWidth, terminalWidth, lines[0].taskID, lines[0].details)
  212. // Verify details were truncated (not removed entirely)
  213. assert.Assert(t, lines[0].details != "", "details should be truncated, not removed")
  214. assert.Assert(t, strings.HasSuffix(lines[0].details, "..."), "truncated details should end with ...")
  215. }
  216. func TestAdjustLineWidth_TaskIDCorrectlyTruncated(t *testing.T) {
  217. w := &ttyWriter{}
  218. lines := []lineData{
  219. {
  220. taskID: "very-long-image-name-that-exceeds-minimum-length",
  221. status: "Pulling",
  222. details: "",
  223. },
  224. }
  225. terminalWidth := 40
  226. timerLen := 5
  227. w.adjustLineWidth(lines, timerLen, terminalWidth)
  228. lineWidth := 5 + len(lines[0].taskID) + 7 + timerLen
  229. assert.Assert(t, lineWidth <= terminalWidth,
  230. "line width %d should not exceed terminal width %d (taskID=%q)",
  231. lineWidth, terminalWidth, lines[0].taskID)
  232. assert.Assert(t, strings.HasSuffix(lines[0].taskID, "..."), "truncated taskID should end with ...")
  233. }
  234. func TestAdjustLineWidth_NoTruncationNeeded(t *testing.T) {
  235. w := &ttyWriter{}
  236. originalDetails := "short"
  237. originalTaskID := "Image foo"
  238. lines := []lineData{
  239. {
  240. taskID: originalTaskID,
  241. status: "Pulling",
  242. details: originalDetails,
  243. },
  244. }
  245. // Wide terminal, nothing should be truncated
  246. w.adjustLineWidth(lines, 5, 100)
  247. assert.Equal(t, originalTaskID, lines[0].taskID, "taskID should not be modified")
  248. assert.Equal(t, originalDetails, lines[0].details, "details should not be modified")
  249. }
  250. func TestAdjustLineWidth_DetailsRemovedWhenTooShort(t *testing.T) {
  251. w := &ttyWriter{}
  252. lines := []lineData{
  253. {
  254. taskID: "Image foo",
  255. status: "Pulling",
  256. details: "abc", // Very short, can't be meaningfully truncated
  257. },
  258. }
  259. // Terminal so narrow that even minimal details + "..." wouldn't help
  260. w.adjustLineWidth(lines, 5, 28)
  261. assert.Equal(t, "", lines[0].details, "details should be removed entirely when too short to truncate")
  262. }
  263. // stripAnsi removes ANSI escape codes from a string
  264. func stripAnsi(s string) string {
  265. var result strings.Builder
  266. inAnsi := false
  267. for _, r := range s {
  268. if r == '\x1b' {
  269. inAnsi = true
  270. continue
  271. }
  272. if inAnsi {
  273. // ANSI sequences end with a letter (m, h, l, G, etc.)
  274. if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') {
  275. inAnsi = false
  276. }
  277. continue
  278. }
  279. result.WriteRune(r)
  280. }
  281. return result.String()
  282. }
  283. func TestPrintWithDimensions_PulledAndPullingWithLongIDs(t *testing.T) {
  284. w, buf := newTestWriter()
  285. // Add a completed task with long ID
  286. completedTask := &task{
  287. ID: "Image docker.io/library/nginx-long-name",
  288. parents: make(map[string]struct{}),
  289. startTime: time.Now().Add(-2 * time.Second),
  290. endTime: time.Now(),
  291. text: "Pulled",
  292. status: api.Done,
  293. spinner: NewSpinner(),
  294. }
  295. completedTask.spinner.Stop()
  296. w.tasks[completedTask.ID] = completedTask
  297. w.ids = append(w.ids, completedTask.ID)
  298. // Add a pending task with long ID
  299. pendingTask := &task{
  300. ID: "Image docker.io/library/postgres-database",
  301. parents: make(map[string]struct{}),
  302. startTime: time.Now(),
  303. text: "Pulling",
  304. status: api.Working,
  305. spinner: NewSpinner(),
  306. }
  307. w.tasks[pendingTask.ID] = pendingTask
  308. w.ids = append(w.ids, pendingTask.ID)
  309. terminalWidth := 50
  310. w.printWithDimensions(terminalWidth, 24)
  311. // Strip all ANSI codes from output and split by newline
  312. stripped := stripAnsi(buf.String())
  313. lines := strings.Split(stripped, "\n")
  314. // Filter non-empty lines
  315. var nonEmptyLines []string
  316. for _, line := range lines {
  317. if strings.TrimSpace(line) != "" {
  318. nonEmptyLines = append(nonEmptyLines, line)
  319. }
  320. }
  321. // Expected output format (50 runes per task line)
  322. expected := `[+] pull 1/2
  323. ✔ Image docker.io/library/nginx-l... Pulled 2.0s
  324. ⠋ Image docker.io/library/postgre... Pulling 0.0s`
  325. expectedLines := strings.Split(expected, "\n")
  326. // Debug output
  327. t.Logf("Actual output:\n")
  328. for i, line := range nonEmptyLines {
  329. t.Logf(" line %d (%2d runes): %q", i, utf8.RuneCountInString(line), line)
  330. }
  331. // Verify number of lines
  332. assert.Equal(t, len(expectedLines), len(nonEmptyLines), "number of lines should match")
  333. // Verify each line matches expected
  334. for i, line := range nonEmptyLines {
  335. if i < len(expectedLines) {
  336. assert.Equal(t, expectedLines[i], line,
  337. "line %d should match expected", i)
  338. }
  339. }
  340. // Verify task lines fit within terminal width (strict - no tolerance)
  341. for i, line := range nonEmptyLines {
  342. if i > 0 { // Skip header line
  343. runeCount := utf8.RuneCountInString(line)
  344. assert.Assert(t, runeCount <= terminalWidth,
  345. "line %d has %d runes which exceeds terminal width %d: %q",
  346. i, runeCount, terminalWidth, line)
  347. }
  348. }
  349. }
  350. func TestLenAnsi(t *testing.T) {
  351. testCases := []struct {
  352. input string
  353. expected int
  354. }{
  355. {"hello", 5},
  356. {"\x1b[32mhello\x1b[0m", 5},
  357. {"\x1b[1;32mgreen\x1b[0m text", 10},
  358. {"", 0},
  359. {"\x1b[0m", 0},
  360. }
  361. for _, tc := range testCases {
  362. t.Run(tc.input, func(t *testing.T) {
  363. result := lenAnsi(tc.input)
  364. assert.Equal(t, tc.expected, result)
  365. })
  366. }
  367. }