multiCMD 1.64__tar.gz → 1.65__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {multicmd-1.64 → multicmd-1.65}/PKG-INFO +18 -3
  2. {multicmd-1.64 → multicmd-1.65}/README.md +17 -2
  3. {multicmd-1.64 → multicmd-1.65}/multiCMD.egg-info/PKG-INFO +18 -3
  4. {multicmd-1.64 → multicmd-1.65}/multiCMD.py +48 -35
  5. multicmd-1.65/tests/test_helpers.py +423 -0
  6. {multicmd-1.64 → multicmd-1.65}/tests/test_windows.py +18 -0
  7. multicmd-1.64/tests/test_helpers.py +0 -162
  8. {multicmd-1.64 → multicmd-1.65}/LICENSE +0 -0
  9. {multicmd-1.64 → multicmd-1.65}/multiCMD.egg-info/SOURCES.txt +0 -0
  10. {multicmd-1.64 → multicmd-1.65}/multiCMD.egg-info/dependency_links.txt +0 -0
  11. {multicmd-1.64 → multicmd-1.65}/multiCMD.egg-info/entry_points.txt +0 -0
  12. {multicmd-1.64 → multicmd-1.65}/multiCMD.egg-info/top_level.txt +0 -0
  13. {multicmd-1.64 → multicmd-1.65}/scripts/multiCMD +0 -0
  14. {multicmd-1.64 → multicmd-1.65}/setup.cfg +0 -0
  15. {multicmd-1.64 → multicmd-1.65}/setup.py +0 -0
  16. {multicmd-1.64 → multicmd-1.65}/tests/test_api.py +0 -0
  17. {multicmd-1.64 → multicmd-1.65}/tests/test_async_executor.py +0 -0
  18. {multicmd-1.64 → multicmd-1.65}/tests/test_cli.py +0 -0
  19. {multicmd-1.64 → multicmd-1.65}/tests/test_cli_closed_stdout.py +0 -0
  20. {multicmd-1.64 → multicmd-1.65}/tests/test_cli_failed_stdout.py +0 -0
  21. {multicmd-1.64 → multicmd-1.65}/tests/test_cli_input.py +0 -0
  22. {multicmd-1.64 → multicmd-1.65}/tests/test_cli_summary.py +0 -0
  23. {multicmd-1.64 → multicmd-1.65}/tests/test_display.py +0 -0
  24. {multicmd-1.64 → multicmd-1.65}/tests/test_embed.py +0 -0
  25. {multicmd-1.64 → multicmd-1.65}/tests/test_env.py +0 -0
  26. {multicmd-1.64 → multicmd-1.65}/tests/test_expand_ranges.py +0 -0
  27. {multicmd-1.64 → multicmd-1.65}/tests/test_handover.py +0 -0
  28. {multicmd-1.64 → multicmd-1.65}/tests/test_interrupts.py +0 -0
  29. {multicmd-1.64 → multicmd-1.65}/tests/test_packaging.py +0 -0
  30. {multicmd-1.64 → multicmd-1.65}/tests/test_parsing.py +0 -0
  31. {multicmd-1.64 → multicmd-1.65}/tests/test_pass_fds.py +0 -0
  32. {multicmd-1.64 → multicmd-1.65}/tests/test_ping.py +0 -0
  33. {multicmd-1.64 → multicmd-1.65}/tests/test_pool.py +0 -0
  34. {multicmd-1.64 → multicmd-1.65}/tests/test_process_groups.py +0 -0
  35. {multicmd-1.64 → multicmd-1.65}/tests/test_pty.py +0 -0
  36. {multicmd-1.64 → multicmd-1.65}/tests/test_reader.py +0 -0
  37. {multicmd-1.64 → multicmd-1.65}/tests/test_reader_quit.py +0 -0
  38. {multicmd-1.64 → multicmd-1.65}/tests/test_regressions.py +0 -0
  39. {multicmd-1.64 → multicmd-1.65}/tests/test_run_command.py +0 -0
  40. {multicmd-1.64 → multicmd-1.65}/tests/test_run_commands.py +0 -0
  41. {multicmd-1.64 → multicmd-1.65}/tests/test_sudo.py +0 -0
  42. {multicmd-1.64 → multicmd-1.65}/tests/test_supervision.py +0 -0
  43. {multicmd-1.64 → multicmd-1.65}/tests/test_task.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.64
3
+ Version: 1.65
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -559,6 +559,21 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
559
 
560
560
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
561
561
 
562
+ ## Upgrading to 1.65 from 1.64
563
+
564
+ - Nothing needs doing for `mcmd`, which is unchanged. hpcp users upgrade hpcp to 9.92 before or with multiCMD 1.65: hpcp up
565
+ to 9.91 takes the `0` below as a size where 1.64 stopped with a `TypeError`, and 9.92 refuses a size with a unit it cannot
566
+ read before anything is touched.
567
+ - Changed, library: `format_bytes()` given a string with a unit it does not know (`'5 foo'`) returns `0` and writes the
568
+ "Invalid size format" line to stderr, as for a string with no number (1.64: `None`). A program that cannot tell this `0`
569
+ from a real one checks the string itself.
570
+ - Changed, library: `input_with_timeout_and_countdown()` counts an ended stdin (Ctrl-D, `/dev/null`), a closed one or none
571
+ as no answer: it returns `None` when the countdown ends, never sooner (1.64: an exception). It goes on asking meanwhile,
572
+ so Ctrl-C still aborts and a line typed before the end is taken. A program that caught `EOFError` to skip the prompt now
573
+ waits the countdown out.
574
+ - Known, planned for 1.66 ([docs/limitations.md](docs/limitations.md)): Ctrl-D after a half-typed line stops the countdown
575
+ until the line is ended, and `format_bytes()` ignores text after the size (`'5Gb/s'` is 5 G).
576
+
562
577
  ## Upgrading to 1.64 from 1.63
563
578
 
564
579
  - Changed, library: once the reader of stdout quit, a shown command whose output keeps coming stops its call: the call's
@@ -572,9 +587,9 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
572
587
  no longer stopped by another write's failure (docs/limitations.md).
573
588
  - Changed, library: a shown dry run whose line finds the reader gone raises `BrokenPipeError` if it waits, whenever it began
574
589
  (1.63: a dry run made after the reader quit returned).
575
- - hpcp 9.89 and 9.90 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
590
+ - hpcp 9.89 to 9.91 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
576
591
  prints for longer than 1 s is cut, with the `tune2fs` queued after it, and its call raises before the loop devices are
577
- detached, where 1.63 ran it unseen; a later hpcp runs its cleanup quiet.
592
+ detached, where 1.63 ran it unseen; hpcp 9.92 runs its cleanup quiet.
578
593
  - Changed: `input_with_timeout_and_countdown()` writes its prompt and countdown to stderr, after flushing stdout, and
579
594
  `format_bytes()` its error message (1.63: stdout, where a dead one raised `BrokenPipeError` and `> log` hid the prompt).
580
595
  - Fix: a `sys.stdout` the program closed loses the output and every command runs (1.63: `ValueError`, and nothing ran), and
@@ -533,6 +533,21 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
533
533
 
534
534
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
535
535
 
536
+ ## Upgrading to 1.65 from 1.64
537
+
538
+ - Nothing needs doing for `mcmd`, which is unchanged. hpcp users upgrade hpcp to 9.92 before or with multiCMD 1.65: hpcp up
539
+ to 9.91 takes the `0` below as a size where 1.64 stopped with a `TypeError`, and 9.92 refuses a size with a unit it cannot
540
+ read before anything is touched.
541
+ - Changed, library: `format_bytes()` given a string with a unit it does not know (`'5 foo'`) returns `0` and writes the
542
+ "Invalid size format" line to stderr, as for a string with no number (1.64: `None`). A program that cannot tell this `0`
543
+ from a real one checks the string itself.
544
+ - Changed, library: `input_with_timeout_and_countdown()` counts an ended stdin (Ctrl-D, `/dev/null`), a closed one or none
545
+ as no answer: it returns `None` when the countdown ends, never sooner (1.64: an exception). It goes on asking meanwhile,
546
+ so Ctrl-C still aborts and a line typed before the end is taken. A program that caught `EOFError` to skip the prompt now
547
+ waits the countdown out.
548
+ - Known, planned for 1.66 ([docs/limitations.md](docs/limitations.md)): Ctrl-D after a half-typed line stops the countdown
549
+ until the line is ended, and `format_bytes()` ignores text after the size (`'5Gb/s'` is 5 G).
550
+
536
551
  ## Upgrading to 1.64 from 1.63
537
552
 
538
553
  - Changed, library: once the reader of stdout quit, a shown command whose output keeps coming stops its call: the call's
@@ -546,9 +561,9 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
546
561
  no longer stopped by another write's failure (docs/limitations.md).
547
562
  - Changed, library: a shown dry run whose line finds the reader gone raises `BrokenPipeError` if it waits, whenever it began
548
563
  (1.63: a dry run made after the reader quit returned).
549
- - hpcp 9.89 and 9.90 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
564
+ - hpcp 9.89 to 9.91 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
550
565
  prints for longer than 1 s is cut, with the `tune2fs` queued after it, and its call raises before the loop devices are
551
- detached, where 1.63 ran it unseen; a later hpcp runs its cleanup quiet.
566
+ detached, where 1.63 ran it unseen; hpcp 9.92 runs its cleanup quiet.
552
567
  - Changed: `input_with_timeout_and_countdown()` writes its prompt and countdown to stderr, after flushing stdout, and
553
568
  `format_bytes()` its error message (1.63: stdout, where a dead one raised `BrokenPipeError` and `> log` hid the prompt).
554
569
  - Fix: a `sys.stdout` the program closed loses the output and every command runs (1.63: `ValueError`, and nothing ran), and
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.64
3
+ Version: 1.65
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -559,6 +559,21 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
559
 
560
560
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
561
561
 
562
+ ## Upgrading to 1.65 from 1.64
563
+
564
+ - Nothing needs doing for `mcmd`, which is unchanged. hpcp users upgrade hpcp to 9.92 before or with multiCMD 1.65: hpcp up
565
+ to 9.91 takes the `0` below as a size where 1.64 stopped with a `TypeError`, and 9.92 refuses a size with a unit it cannot
566
+ read before anything is touched.
567
+ - Changed, library: `format_bytes()` given a string with a unit it does not know (`'5 foo'`) returns `0` and writes the
568
+ "Invalid size format" line to stderr, as for a string with no number (1.64: `None`). A program that cannot tell this `0`
569
+ from a real one checks the string itself.
570
+ - Changed, library: `input_with_timeout_and_countdown()` counts an ended stdin (Ctrl-D, `/dev/null`), a closed one or none
571
+ as no answer: it returns `None` when the countdown ends, never sooner (1.64: an exception). It goes on asking meanwhile,
572
+ so Ctrl-C still aborts and a line typed before the end is taken. A program that caught `EOFError` to skip the prompt now
573
+ waits the countdown out.
574
+ - Known, planned for 1.66 ([docs/limitations.md](docs/limitations.md)): Ctrl-D after a half-typed line stops the countdown
575
+ until the line is ended, and `format_bytes()` ignores text after the size (`'5Gb/s'` is 5 G).
576
+
562
577
  ## Upgrading to 1.64 from 1.63
563
578
 
564
579
  - Changed, library: once the reader of stdout quit, a shown command whose output keeps coming stops its call: the call's
@@ -572,9 +587,9 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
572
587
  no longer stopped by another write's failure (docs/limitations.md).
573
588
  - Changed, library: a shown dry run whose line finds the reader gone raises `BrokenPipeError` if it waits, whenever it began
574
589
  (1.63: a dry run made after the reader quit returned).
575
- - hpcp 9.89 and 9.90 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
590
+ - hpcp 9.89 to 9.91 cloning a disk (`-dd`) with 1.64 installed beside them: when the reader quits, a delayed `e2fsck` that
576
591
  prints for longer than 1 s is cut, with the `tune2fs` queued after it, and its call raises before the loop devices are
577
- detached, where 1.63 ran it unseen; a later hpcp runs its cleanup quiet.
592
+ detached, where 1.63 ran it unseen; hpcp 9.92 runs its cleanup quiet.
578
593
  - Changed: `input_with_timeout_and_countdown()` writes its prompt and countdown to stderr, after flushing stdout, and
579
594
  `format_bytes()` its error message (1.63: stdout, where a dead one raised `BrokenPipeError` and `> log` hid the prompt).
580
595
  - Fix: a `sys.stdout` the program closed loses the output and every command runs (1.63: `ValueError`, and nothing ran), and
@@ -29,7 +29,7 @@ import traceback
29
29
  from pprint import pformat
30
30
 
31
31
  #%% global vars
32
- version = '1.64'
32
+ version = '1.65'
33
33
  __version__ = version
34
34
  COMMIT_DATE = '2026-11-13'
35
35
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
@@ -3258,7 +3258,8 @@ def input_with_timeout_and_countdown(timeout, prompt='Please enter your selectio
3258
3258
  prompt: The prompt to display to the user
3259
3259
 
3260
3260
  @returns:
3261
- str: The input from the user or None if no input was received
3261
+ str: The input from the user or None if no input was received: the timeout ran out. A stdin that has ended, is closed
3262
+ or is missing ( Ctrl-D, /dev/null ) counts as no answer: the countdown goes on asking, and takes a line typed before its end
3262
3263
 
3263
3264
  """
3264
3265
  # the question the caller printed goes out first; the prompt and its countdown are for the person at the terminal, not for
@@ -3270,14 +3271,28 @@ def input_with_timeout_and_countdown(timeout, prompt='Please enter your selectio
3270
3271
  import msvcrt
3271
3272
  except ImportError:
3272
3273
  msvcrt = None
3273
- # Loop until the timeout
3274
- for remaining in range(timeout, 0, -1):
3274
+ # a stdin with no answer ( none, closed, or at its end: Ctrl-D, /dev/null, a pipe that ended ) is no reason to stop the
3275
+ # countdown early: the default applies when it ends, and a Ctrl-C still aborts. It is asked again every second, as the
3276
+ # countdown is still asking: a terminal can answer after a Ctrl-D ( one select() and one input() a second: no busy loop )
3277
+ no_stdin = sys.stdin is None or getattr(sys.stdin, 'closed', False)
3278
+ # stdin is asked at the start of each second and once more at the end, so a line typed in the last second counts too
3279
+ for remaining in range(timeout, -1, -1):
3275
3280
  # If there is an input, return it
3276
- if msvcrt is not None:
3277
- if msvcrt.kbhit():
3278
- return input().strip()
3279
- elif sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
3280
- return input().strip()
3281
+ if not no_stdin:
3282
+ try:
3283
+ if msvcrt is not None:
3284
+ if msvcrt.kbhit():
3285
+ return input().strip()
3286
+ elif sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
3287
+ return input().strip()
3288
+ except io.UnsupportedOperation:
3289
+ # a stdin select() cannot watch ( no descriptor: a StringIO ) was not asked: that is not "no answer", as in 1.64
3290
+ raise
3291
+ except (EOFError, OSError):
3292
+ # no answer this second. EOFError: at its end, or a Ctrl-D; OSError: its descriptor closed, or its terminal gone
3293
+ pass
3294
+ if remaining == 0:
3295
+ break
3281
3296
  # Print the remaining time
3282
3297
  _write_error(f"\r{prompt} [{remaining}s]: ", end='')
3283
3298
  # Wait a second
@@ -3612,23 +3627,6 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3612
3627
  return size
3613
3628
  elif isinstance(size, str):
3614
3629
  match = re.match(r"(\d+(\.\d+)?)\s*([a-zA-Z]*)", size)
3615
- if not match:
3616
- if to_str:
3617
- return size
3618
- _write_error("Invalid size format. Expected format: 'number [unit]', e.g., '1.5 GiB' or '1.5GiB'\n" f"Got: {size}")
3619
- return 0
3620
- number, _, unit = match.groups()
3621
- number = float(number)
3622
- unit = unit.strip().lower().rstrip("b")
3623
- if unit.endswith("i"):
3624
- use_1024_bytes = True
3625
- elif use_1024_bytes is None:
3626
- use_1024_bytes = False
3627
- unit = unit.rstrip("i")
3628
- if use_1024_bytes:
3629
- power = 2**10
3630
- else:
3631
- power = 10**3
3632
3630
  unit_labels = {
3633
3631
  "": 0,
3634
3632
  "k": 1,
@@ -3640,18 +3638,33 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3640
3638
  "z": 7,
3641
3639
  "y": 8,
3642
3640
  }
3643
- if unit not in unit_labels:
3641
+ if match:
3642
+ number, _, unit = match.groups()
3643
+ number = float(number)
3644
+ unit = unit.strip().lower().rstrip("b")
3645
+ if unit.endswith("i"):
3646
+ use_1024_bytes = True
3647
+ elif use_1024_bytes is None:
3648
+ use_1024_bytes = False
3649
+ unit = unit.rstrip("i")
3650
+ # no number, or a unit that is none of these: not a size ( 1.64 returned None for the unit )
3651
+ if not match or unit not in unit_labels:
3644
3652
  if to_str:
3645
3653
  return size
3654
+ _write_error("Invalid size format. Expected format: 'number [unit]', e.g., '1.5 GiB' or '1.5GiB'\n" f"Got: {size}")
3655
+ return 0
3656
+ if use_1024_bytes:
3657
+ power = 2**10
3646
3658
  else:
3647
- if to_str:
3648
- return format_bytes(
3649
- size=int(number * (power**unit_labels[unit])),
3650
- use_1024_bytes=use_1024_bytes,
3651
- to_str=True,
3652
- str_format=str_format,
3653
- )
3654
- return int(number * (power**unit_labels[unit]))
3659
+ power = 10**3
3660
+ if to_str:
3661
+ return format_bytes(
3662
+ size=int(number * (power**unit_labels[unit])),
3663
+ use_1024_bytes=use_1024_bytes,
3664
+ to_str=True,
3665
+ str_format=str_format,
3666
+ )
3667
+ return int(number * (power**unit_labels[unit]))
3655
3668
  else:
3656
3669
  try:
3657
3670
  return int(size)
@@ -0,0 +1,423 @@
1
+ import builtins
2
+ import io
3
+ import os
4
+ import re
5
+ import select
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ import multiCMD
14
+ from multiCMD import (
15
+ _genrate_progress_bar,
16
+ format_bytes,
17
+ get_terminal_size,
18
+ input_with_timeout_and_countdown,
19
+ int_to_color,
20
+ parseTable,
21
+ pretty_format_table,
22
+ print_progress_bar,
23
+ slugify,
24
+ )
25
+
26
+
27
+ def test_pretty_format_table_basic_and_remove_empty():
28
+ data = [["a", ""], ["b", ""]]
29
+ header = ["h1", "h2"]
30
+ out = pretty_format_table(data, header=header, remove_empty_columns=True)
31
+ assert out == "h1\n--\na \nb \n"
32
+
33
+
34
+ def test_pretty_format_table_pads_wide_characters_by_display_width():
35
+ # East Asian wide characters take two terminal columns, a combining mark none.
36
+ out = pretty_format_table([["name", "v"], ["中文", "1"], ["abcd", "2"], ["e\u0301", "3"]], full=True)
37
+ assert out == "name | v\n-----+--\n中文 | 1\nabcd | 2\ne\u0301 | 3\n"
38
+
39
+
40
+ def test_pretty_format_table_truncates_wide_characters_to_the_terminal(monkeypatch):
41
+ monkeypatch.setattr(multiCMD, "get_terminal_size", lambda: (12, 24))
42
+ out = pretty_format_table([["k", "v"], ["a", "中文中文中文"]])
43
+ assert out == "k|v \n-+----------\na|中文中文..\n"
44
+
45
+
46
+ def test_pretty_format_table_narrows_a_wide_header_by_display_width(monkeypatch):
47
+ monkeypatch.setattr(multiCMD, "get_terminal_size", lambda: (10, 24))
48
+ out = pretty_format_table([["名前", "v"], ["aaaaaaaaaa", "1"]])
49
+ assert out == "名前 |v\n--------+-\naaaaaa..|1\n"
50
+
51
+
52
+ def test_parse_table():
53
+ text = "col1 col2\nfoo bar\n"
54
+ table = parseTable(text)
55
+ assert table == [["col1", "col2"], ["foo", "bar"]]
56
+
57
+
58
+ def test_slugify_ascii_and_unicode():
59
+ assert slugify("Hello World!") == "hello-world"
60
+ assert slugify("café", allow_unicode=True) == "café" # runtime: preserves unicode
61
+ assert slugify("café", allow_unicode=False) == "cafe"
62
+
63
+
64
+ def test_format_bytes_roundtrip():
65
+ assert format_bytes(1024, use_1024_bytes=True, to_str=True) == "1.00 Ki"
66
+ assert format_bytes("1 KiB", to_int=True) == 1024
67
+
68
+
69
+ @pytest.mark.parametrize("size", ["5 foo", "5foo", "5 fooi", "5 KiBx", "1.5 gigs", "5 bytes"])
70
+ @pytest.mark.parametrize("kwargs", [{"to_int": True}, {}, {"use_1024_bytes": True}, {"to_int": True, "use_1024_bytes": False}],
71
+ ids=["to_int", "no flags", "1024", "to_int 1000"])
72
+ def test_format_bytes_a_unit_it_does_not_know_is_an_invalid_size(capsys, size, kwargs):
73
+ # 1.64 returned None, silently, and int() of it raised TypeError; a size it cannot read at all already gave 0 and a line
74
+ got = format_bytes(size, **kwargs)
75
+ assert got == 0 and isinstance(got, int)
76
+ out, err = capsys.readouterr()
77
+ assert out == ""
78
+ assert "Invalid size format" in err and "Got: " + size in err
79
+
80
+
81
+ @pytest.mark.parametrize("kwargs", [{"to_str": True}, {"to_str": True, "to_int": True}], ids=["to_str", "to_str to_int"])
82
+ def test_format_bytes_to_str_hands_back_a_size_it_does_not_know_the_unit_of(capsys, kwargs):
83
+ # unchanged: the string asked to be shown comes back as it came, with nothing said
84
+ assert format_bytes("5 foo", **kwargs) == "5 foo"
85
+ assert capsys.readouterr() == ("", "")
86
+
87
+
88
+ @pytest.mark.parametrize("size, kwargs, expected", [
89
+ ("5", {}, 5), ("5 B", {"to_int": True}, 5), ("2.5 kb", {"to_int": True}, 2500), ("2.5 KiB", {}, 2560),
90
+ ("1 M", {"use_1024_bytes": True}, 1048576), ("3gib", {"to_int": True}, 3 * 1024 ** 3), ("1 T", {}, 10 ** 12),
91
+ (7, {"to_int": True}, 7), (7.9, {"to_int": True}, 7)], ids=str)
92
+ def test_format_bytes_reads_every_unit_it_knows(capsys, size, kwargs, expected):
93
+ assert format_bytes(size, **kwargs) == expected
94
+ assert capsys.readouterr() == ("", "")
95
+
96
+
97
+ def test_int_to_color_deterministic_and_in_range():
98
+ assert int_to_color(0x123456) == (36, 103, 171)
99
+ assert int_to_color(0) == (160, 160, 160)
100
+ assert int_to_color(0xFFFFFF) == (220, 220, 220)
101
+
102
+
103
+ def test_progress_bar_helpers(capsys, monkeypatch):
104
+ expected_bar = (
105
+ "P██████████████████████████████████▁__________________________________|50.0% S"
106
+ )
107
+ assert _genrate_progress_bar(5, 10, prefix="P", suffix="S", columns=80) == expected_bar
108
+
109
+ monkeypatch.setattr(
110
+ "multiCMD.get_terminal_size", lambda: (80, 24)
111
+ )
112
+ print_progress_bar(5, 10, prefix="Progress:", suffix="Complete")
113
+ captured = capsys.readouterr()
114
+ assert captured.out == (
115
+ "\rProgress: |████████████████████████▄_________________________|50.0% | Complete"
116
+ )
117
+
118
+
119
+ def ascii_stdout(monkeypatch, encoding='ascii', errors='surrogateescape'):
120
+ # Python 3.6 in a C locale ( hpcp's library calls ): an ASCII stdout that takes undecodable file names
121
+ out = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors=errors)
122
+ monkeypatch.setattr(sys, 'stdout', out)
123
+ monkeypatch.setattr("multiCMD.get_terminal_size", lambda: (80, 24))
124
+ return out
125
+
126
+
127
+ def test_progress_bar_on_a_stdout_that_cannot_write_its_blocks(monkeypatch):
128
+ # 1.61 raised UnicodeEncodeError out of the call, from its fallback, which printed the same bar again
129
+ out = ascii_stdout(monkeypatch)
130
+ print_progress_bar(5, 10, prefix="Progress:", suffix="Complete")
131
+ print_progress_bar(10, 10, prefix="Progress:", suffix="Complete")
132
+ out.flush()
133
+ assert out.buffer.getvalue().decode('ascii') == (
134
+ "\rProgress: |" + "#" * 24 + "=" + "_" * 25 + "|50.0% | Complete"
135
+ "\rProgress: |" + "#" * 48 + "|100.0% | Complete\n"
136
+ )
137
+
138
+
139
+ def test_progress_bar_with_a_name_its_stdout_cannot_write(monkeypatch):
140
+ # a file name with a byte that is not UTF-8 ( decoded with surrogateescape ) on a UTF-8 stdout, which is strict
141
+ out = ascii_stdout(monkeypatch, 'utf-8', 'strict')
142
+ print_progress_bar(3, 0, prefix='dir/caf\udce9', suffix='s')
143
+ out.flush()
144
+ assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(80)
145
+
146
+
147
+ def test_progress_bar_in_a_c_locale_python():
148
+ # the real stdout of a Python whose locale has no encoding for the bar ( on 3.7+ only PYTHONIOENCODING makes it ASCII )
149
+ code = ('import sys; sys.path.insert(0, %r); import multiCMD; multiCMD.print_progress_bar(5, 10, "p", "s")'
150
+ % str(Path(multiCMD.__file__).parent))
151
+ env = dict(os.environ, LC_ALL='C', LANG='C', PYTHONIOENCODING='ascii')
152
+ proc = subprocess.run([sys.executable, '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, timeout=30)
153
+ assert proc.returncode == 0, proc.stderr
154
+ assert proc.stderr == b''
155
+ assert b'#' in proc.stdout and b'|50.0% | s' in proc.stdout
156
+
157
+
158
+ def test_get_terminal_size_tuple():
159
+ cols, rows = get_terminal_size()
160
+ assert cols > 0 and rows > 0
161
+
162
+
163
+ @pytest.mark.skipif(os.name != "posix", reason="needs a pseudo-terminal")
164
+ def test_get_terminal_size_reads_columns_from_stdin_when_stdout_is_piped():
165
+ # `cmd | less` on a 200x40 terminal: os.get_terminal_size() fails on the pipe, so the
166
+ # TIOCGWINSZ fallback reads stdin, whose winsize struct holds the rows before the columns.
167
+ import fcntl
168
+ import pty
169
+ import struct
170
+ import termios
171
+ master, slave = pty.openpty()
172
+ try:
173
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 200, 0, 0))
174
+ out = subprocess.run(
175
+ [sys.executable, "-c", "import multiCMD; print(*multiCMD.get_terminal_size()[:2])"],
176
+ stdin=slave, stdout=subprocess.PIPE, cwd=str(Path(__file__).resolve().parents[1]),
177
+ universal_newlines=True, check=True,
178
+ ).stdout
179
+ finally:
180
+ os.close(slave)
181
+ os.close(master)
182
+ assert out.split() == ["200", "40"]
183
+
184
+
185
+ def test_input_with_timeout_and_countdown(monkeypatch):
186
+ monkeypatch.setattr(builtins, "input", lambda prompt="": "user input")
187
+ monkeypatch.setattr(
188
+ select, "select", lambda r, w, x, timeout=None: ([sys.stdin], [], [])
189
+ )
190
+ assert input_with_timeout_and_countdown(5) == "user input"
191
+ monkeypatch.setattr(select, "select", lambda r, w, x, timeout=None: ([], [], []))
192
+ assert input_with_timeout_and_countdown(1) is None
193
+
194
+
195
+ def test_countdown_at_the_end_of_stdin_asks_again_each_second_and_runs_out(monkeypatch, capsys):
196
+ # select() calls a stdin at its end readable for ever, and input() raises EOFError there ( 1.64 let it out ). Ctrl-D counts
197
+ # as no answer: the countdown goes on to its end, so the default applies then and a Ctrl-C can still abort, and stdin is
198
+ # asked again once a second and once more at the end, as a terminal can still answer after a Ctrl-D ( the second 1.65 build
199
+ # stopped asking )
200
+ asked, slept = [], []
201
+ monkeypatch.setitem(sys.modules, "msvcrt", None) # the select() path, on any platform
202
+ def at_its_end(prompt=""):
203
+ asked.append("input")
204
+ raise EOFError
205
+ def readable(r, w, x, timeout=None):
206
+ asked.append("select")
207
+ return ([sys.stdin], [], [])
208
+ monkeypatch.setattr(builtins, "input", at_its_end)
209
+ monkeypatch.setattr(select, "select", readable)
210
+ monkeypatch.setattr(multiCMD.time, "sleep", slept.append)
211
+ assert input_with_timeout_and_countdown(3, "Answer") is None
212
+ assert asked == ["select", "input"] * 4
213
+ assert slept == [1, 1, 1]
214
+ err = capsys.readouterr().err
215
+ assert "Answer [3s]: " in err and "Answer [2s]: " in err and "Answer [1s]: " in err
216
+
217
+
218
+ def test_countdown_at_the_end_of_stdin_lets_a_ctrl_c_abort_it(monkeypatch):
219
+ def at_its_end(prompt=""):
220
+ raise EOFError
221
+ def interrupted(seconds):
222
+ raise KeyboardInterrupt
223
+ monkeypatch.setattr(builtins, "input", at_its_end)
224
+ monkeypatch.setattr(select, "select", lambda r, w, x, timeout=None: ([sys.stdin], [], []))
225
+ monkeypatch.setattr(multiCMD.time, "sleep", interrupted)
226
+ with pytest.raises(KeyboardInterrupt):
227
+ input_with_timeout_and_countdown(60)
228
+
229
+
230
+ def test_countdown_takes_an_answer_typed_in_its_last_second(monkeypatch):
231
+ # stdin is asked once more when the countdown ends: a line typed after the last second began is the answer ( 1.64 and the
232
+ # first three 1.65 builds returned None )
233
+ asked, slept = [], []
234
+ monkeypatch.setitem(sys.modules, "msvcrt", None) # the select() path, on any platform
235
+ def readable_at_the_end(r, w, x, timeout=None):
236
+ asked.append("select")
237
+ return ([sys.stdin], [], []) if len(slept) == 3 else ([], [], [])
238
+ monkeypatch.setattr(select, "select", readable_at_the_end)
239
+ monkeypatch.setattr(builtins, "input", lambda prompt="": " n ")
240
+ monkeypatch.setattr(multiCMD.time, "sleep", slept.append)
241
+ assert input_with_timeout_and_countdown(3, "Answer") == "n"
242
+ assert asked == ["select"] * 4 and slept == [1, 1, 1]
243
+
244
+
245
+ def test_countdown_says_so_when_select_cannot_watch_stdin(monkeypatch):
246
+ # a stdin with no descriptor ( a StringIO ) was not asked: not "no answer", and its line is not dropped in silence ( as 1.64 )
247
+ monkeypatch.setitem(sys.modules, "msvcrt", None)
248
+ monkeypatch.setattr(sys, "stdin", io.StringIO("yes\n"))
249
+ monkeypatch.setattr(multiCMD.time, "sleep", lambda seconds: None)
250
+ with pytest.raises(io.UnsupportedOperation):
251
+ input_with_timeout_and_countdown(3)
252
+
253
+
254
+ posix_only = pytest.mark.skipif(os.name != "posix", reason="POSIX only")
255
+
256
+ # the countdown ( of 1 s unless said ), in a program of its own: what it returned, and how long it took
257
+ ASK = (
258
+ "import os, sys, time, multiCMD\n"
259
+ "%s"
260
+ "t = time.monotonic()\n"
261
+ "got = multiCMD.input_with_timeout_and_countdown(%d, 'Answer')\n"
262
+ "sys.stdout.write('GOT %%r %%.2f\\n' %% (got, time.monotonic() - t))\n"
263
+ "sys.stdout.flush()\n"
264
+ "os._exit(0)\n")
265
+
266
+
267
+ def ask(tmp_path, before="", stdin=subprocess.DEVNULL, shell_prefix=None, feed=None, timeout=1):
268
+ # runs the countdown in a program of its own, with real descriptors; returns its exit status, what it said on stdout (the
269
+ # answer and the seconds it took) and what it wrote on stderr
270
+ program = tmp_path / "ask.py"
271
+ program.write_text(ASK % (before, timeout))
272
+ argv = [sys.executable, str(program)]
273
+ if shell_prefix:
274
+ argv = ["sh", "-c", 'exec "$0" "$@" ' + shell_prefix] + argv
275
+ proc = subprocess.Popen(argv, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
276
+ env=dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1])))
277
+ try:
278
+ if feed is not None:
279
+ feed(proc)
280
+ out, err = proc.communicate(timeout=30)
281
+ finally:
282
+ if proc.poll() is None:
283
+ proc.kill()
284
+ proc.wait()
285
+ return proc.returncode, out.decode(), err.decode()
286
+
287
+
288
+ def answered_none_after_the_timeout(got):
289
+ # None, and not sooner than the countdown of 1 s ( never at once ); the upper bound only catches a wait that is not the countdown
290
+ status, out, err = got
291
+ words = out.split()
292
+ assert status == 0 and words[:2] == ["GOT", "None"], got
293
+ assert 1.0 <= float(words[2]) < 6.0, got
294
+ assert "Answer [1s]: " in err, got
295
+ return True
296
+
297
+
298
+ @posix_only
299
+ def test_countdown_at_the_end_of_stdin_runs_out_for_dev_null(tmp_path):
300
+ assert answered_none_after_the_timeout(ask(tmp_path))
301
+
302
+
303
+ @posix_only
304
+ def test_countdown_at_the_end_of_stdin_runs_out_for_a_pipe_that_ended(tmp_path):
305
+ read_end, write_end = os.pipe()
306
+ os.close(write_end)
307
+ try:
308
+ assert answered_none_after_the_timeout(ask(tmp_path, stdin=read_end))
309
+ finally:
310
+ os.close(read_end)
311
+
312
+
313
+ @posix_only
314
+ def test_countdown_with_a_closed_stdin_runs_out(tmp_path):
315
+ # `prog <&-`: Python has no sys.stdin at all
316
+ assert answered_none_after_the_timeout(ask(tmp_path, shell_prefix="<&-"))
317
+
318
+
319
+ @posix_only
320
+ @pytest.mark.parametrize("before", ["sys.stdin.close()\n", "os.close(0)\n"], ids=["sys.stdin closed", "descriptor 0 closed"])
321
+ def test_countdown_whose_stdin_the_program_closed_runs_out(tmp_path, before):
322
+ # a pipe that stays open, so that nothing but the close ends it
323
+ read_end, write_end = os.pipe()
324
+ try:
325
+ assert answered_none_after_the_timeout(ask(tmp_path, before=before, stdin=read_end))
326
+ finally:
327
+ os.close(read_end)
328
+ os.close(write_end)
329
+
330
+
331
+ @posix_only
332
+ def test_countdown_runs_out_after_ctrl_d_at_a_terminal(tmp_path):
333
+ import pty
334
+ master, slave = pty.openpty()
335
+ try:
336
+ # Ctrl-D ( the terminal's EOF character ) typed at the prompt
337
+ got = ask(tmp_path, stdin=slave, feed=lambda proc: os.write(master, b"\x04"))
338
+ finally:
339
+ os.close(slave)
340
+ os.close(master)
341
+ assert answered_none_after_the_timeout(got)
342
+
343
+
344
+ @posix_only
345
+ def test_countdown_takes_an_answer_typed_after_ctrl_d_at_a_terminal(tmp_path):
346
+ # a terminal's Ctrl-D ends nothing: the countdown is still asking, and "n" typed after it is the answer, at the next second,
347
+ # not the default at the end ( the second 1.65 build stopped reading: None after the 3 s, and the "n" left for the shell )
348
+ import pty
349
+ master, slave = pty.openpty()
350
+ try:
351
+ status, out, err = ask(tmp_path, stdin=slave, timeout=3, feed=lambda proc: os.write(master, b"\x04n\n"))
352
+ finally:
353
+ os.close(slave)
354
+ os.close(master)
355
+ assert status == 0 and out.split()[:2] == ["GOT", "'n'"], (status, out, err)
356
+ assert 1.0 <= float(out.split()[2]) < 3.0, out
357
+
358
+
359
+ def read_until(fd, marker, seconds=20):
360
+ # reads fd until marker has come ( the countdown has printed its last second ), or until it stays quiet once marker is None
361
+ seen, deadline = b"", time.monotonic() + seconds
362
+ while time.monotonic() < deadline and (marker is None or marker not in seen):
363
+ if select.select([fd], [], [], 0.2)[0]:
364
+ seen += os.read(fd, 4096)
365
+ elif marker is None:
366
+ break
367
+ assert marker is None or marker in seen, seen
368
+ return seen
369
+
370
+
371
+ @posix_only
372
+ def test_countdown_takes_a_line_sent_in_its_last_second(tmp_path):
373
+ # a pipe that stays open: "n" sent once the last second has begun is the answer, at the end ( 1.64 and 981bbc2: None )
374
+ read_end, write_end = os.pipe()
375
+ def in_the_last_second(proc):
376
+ read_until(proc.stderr.fileno(), b"Answer [1s]: ")
377
+ os.write(write_end, b"n\n")
378
+ try:
379
+ status, out, err = ask(tmp_path, stdin=read_end, timeout=2, feed=in_the_last_second)
380
+ finally:
381
+ os.close(read_end)
382
+ os.close(write_end)
383
+ assert status == 0 and out.split()[:2] == ["GOT", "'n'"], (status, out, err)
384
+ assert 1.0 <= float(out.split()[2]) < 6.0, out
385
+
386
+
387
+ @posix_only
388
+ def test_countdown_at_a_terminal_takes_an_answer_typed_after_ctrl_d_in_its_last_second(tmp_path):
389
+ # stdin, stdout and stderr all on the terminal, as at a shell, where input() reads through C stdio: Ctrl-D, then "n" typed
390
+ # once the last second has begun, is the answer
391
+ import pty
392
+ master, slave = pty.openpty()
393
+ program = tmp_path / "ask.py"
394
+ program.write_text(ASK % ("", 2))
395
+ proc = subprocess.Popen([sys.executable, str(program)], stdin=slave, stdout=slave, stderr=slave,
396
+ env=dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1])))
397
+ try:
398
+ os.write(master, b"\x04")
399
+ read_until(master, b"Answer [1s]: ")
400
+ os.write(master, b"n\n")
401
+ proc.wait(30)
402
+ # its answer line is on the terminal: the program has ended, so what it wrote is all there to read
403
+ got = re.search(rb"GOT (\S+) ([0-9.]+)", read_until(master, None))
404
+ finally:
405
+ if proc.poll() is None:
406
+ proc.kill()
407
+ proc.wait()
408
+ os.close(slave)
409
+ os.close(master)
410
+ assert got and got.group(1) == b"'n'", got
411
+ assert 1.0 <= float(got.group(2)) < 6.0, got
412
+
413
+
414
+ @posix_only
415
+ def test_countdown_still_returns_what_was_typed_at_once(tmp_path):
416
+ read_end, write_end = os.pipe()
417
+ try:
418
+ os.write(write_end, b" yes \n")
419
+ status, out, err = ask(tmp_path, stdin=read_end)
420
+ finally:
421
+ os.close(read_end)
422
+ os.close(write_end)
423
+ assert status == 0 and out.split()[:2] == ["GOT", "'yes'"] and float(out.split()[2]) < 1.0
@@ -79,6 +79,24 @@ def test_input_countdown_uses_msvcrt_when_present(monkeypatch):
79
79
  assert multiCMD.input_with_timeout_and_countdown(3, 'pick') == 'yes'
80
80
 
81
81
 
82
+ def test_input_countdown_runs_out_at_the_end_of_stdin_when_msvcrt_says_a_key_is_waiting(monkeypatch):
83
+ # Ctrl-Z at a console, or a stdin that ended: input() raises EOFError ( 1.64 let it out ); no answer, so the countdown runs
84
+ # out, and the console is asked again each second and once more at the end
85
+ asked, slept = [], []
86
+ def at_its_end():
87
+ asked.append('input')
88
+ raise EOFError
89
+ def key_waiting():
90
+ asked.append('kbhit')
91
+ return True
92
+ monkeypatch.setitem(sys.modules, 'msvcrt', types.SimpleNamespace(kbhit=key_waiting))
93
+ monkeypatch.setattr(builtins, 'input', at_its_end)
94
+ monkeypatch.setattr(multiCMD.time, 'sleep', slept.append)
95
+ assert multiCMD.input_with_timeout_and_countdown(3, 'pick') is None
96
+ assert asked == ['kbhit', 'input'] * 4
97
+ assert slept == [1, 1, 1]
98
+
99
+
82
100
  def test_posix_only_modules_are_imported_lazily():
83
101
  tree = ast.parse((PACKAGE_ROOT / 'multiCMD.py').read_text())
84
102
  top_level = set()
@@ -1,162 +0,0 @@
1
- import builtins
2
- import io
3
- import os
4
- import select
5
- import subprocess
6
- import sys
7
- from pathlib import Path
8
-
9
- import pytest
10
-
11
- import multiCMD
12
- from multiCMD import (
13
- _genrate_progress_bar,
14
- format_bytes,
15
- get_terminal_size,
16
- input_with_timeout_and_countdown,
17
- int_to_color,
18
- parseTable,
19
- pretty_format_table,
20
- print_progress_bar,
21
- slugify,
22
- )
23
-
24
-
25
- def test_pretty_format_table_basic_and_remove_empty():
26
- data = [["a", ""], ["b", ""]]
27
- header = ["h1", "h2"]
28
- out = pretty_format_table(data, header=header, remove_empty_columns=True)
29
- assert out == "h1\n--\na \nb \n"
30
-
31
-
32
- def test_pretty_format_table_pads_wide_characters_by_display_width():
33
- # East Asian wide characters take two terminal columns, a combining mark none.
34
- out = pretty_format_table([["name", "v"], ["中文", "1"], ["abcd", "2"], ["e\u0301", "3"]], full=True)
35
- assert out == "name | v\n-----+--\n中文 | 1\nabcd | 2\ne\u0301 | 3\n"
36
-
37
-
38
- def test_pretty_format_table_truncates_wide_characters_to_the_terminal(monkeypatch):
39
- monkeypatch.setattr(multiCMD, "get_terminal_size", lambda: (12, 24))
40
- out = pretty_format_table([["k", "v"], ["a", "中文中文中文"]])
41
- assert out == "k|v \n-+----------\na|中文中文..\n"
42
-
43
-
44
- def test_pretty_format_table_narrows_a_wide_header_by_display_width(monkeypatch):
45
- monkeypatch.setattr(multiCMD, "get_terminal_size", lambda: (10, 24))
46
- out = pretty_format_table([["名前", "v"], ["aaaaaaaaaa", "1"]])
47
- assert out == "名前 |v\n--------+-\naaaaaa..|1\n"
48
-
49
-
50
- def test_parse_table():
51
- text = "col1 col2\nfoo bar\n"
52
- table = parseTable(text)
53
- assert table == [["col1", "col2"], ["foo", "bar"]]
54
-
55
-
56
- def test_slugify_ascii_and_unicode():
57
- assert slugify("Hello World!") == "hello-world"
58
- assert slugify("café", allow_unicode=True) == "café" # runtime: preserves unicode
59
- assert slugify("café", allow_unicode=False) == "cafe"
60
-
61
-
62
- def test_format_bytes_roundtrip():
63
- assert format_bytes(1024, use_1024_bytes=True, to_str=True) == "1.00 Ki"
64
- assert format_bytes("1 KiB", to_int=True) == 1024
65
-
66
-
67
- def test_int_to_color_deterministic_and_in_range():
68
- assert int_to_color(0x123456) == (36, 103, 171)
69
- assert int_to_color(0) == (160, 160, 160)
70
- assert int_to_color(0xFFFFFF) == (220, 220, 220)
71
-
72
-
73
- def test_progress_bar_helpers(capsys, monkeypatch):
74
- expected_bar = (
75
- "P██████████████████████████████████▁__________________________________|50.0% S"
76
- )
77
- assert _genrate_progress_bar(5, 10, prefix="P", suffix="S", columns=80) == expected_bar
78
-
79
- monkeypatch.setattr(
80
- "multiCMD.get_terminal_size", lambda: (80, 24)
81
- )
82
- print_progress_bar(5, 10, prefix="Progress:", suffix="Complete")
83
- captured = capsys.readouterr()
84
- assert captured.out == (
85
- "\rProgress: |████████████████████████▄_________________________|50.0% | Complete"
86
- )
87
-
88
-
89
- def ascii_stdout(monkeypatch, encoding='ascii', errors='surrogateescape'):
90
- # Python 3.6 in a C locale ( hpcp's library calls ): an ASCII stdout that takes undecodable file names
91
- out = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors=errors)
92
- monkeypatch.setattr(sys, 'stdout', out)
93
- monkeypatch.setattr("multiCMD.get_terminal_size", lambda: (80, 24))
94
- return out
95
-
96
-
97
- def test_progress_bar_on_a_stdout_that_cannot_write_its_blocks(monkeypatch):
98
- # 1.61 raised UnicodeEncodeError out of the call, from its fallback, which printed the same bar again
99
- out = ascii_stdout(monkeypatch)
100
- print_progress_bar(5, 10, prefix="Progress:", suffix="Complete")
101
- print_progress_bar(10, 10, prefix="Progress:", suffix="Complete")
102
- out.flush()
103
- assert out.buffer.getvalue().decode('ascii') == (
104
- "\rProgress: |" + "#" * 24 + "=" + "_" * 25 + "|50.0% | Complete"
105
- "\rProgress: |" + "#" * 48 + "|100.0% | Complete\n"
106
- )
107
-
108
-
109
- def test_progress_bar_with_a_name_its_stdout_cannot_write(monkeypatch):
110
- # a file name with a byte that is not UTF-8 ( decoded with surrogateescape ) on a UTF-8 stdout, which is strict
111
- out = ascii_stdout(monkeypatch, 'utf-8', 'strict')
112
- print_progress_bar(3, 0, prefix='dir/caf\udce9', suffix='s')
113
- out.flush()
114
- assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(80)
115
-
116
-
117
- def test_progress_bar_in_a_c_locale_python():
118
- # the real stdout of a Python whose locale has no encoding for the bar ( on 3.7+ only PYTHONIOENCODING makes it ASCII )
119
- code = ('import sys; sys.path.insert(0, %r); import multiCMD; multiCMD.print_progress_bar(5, 10, "p", "s")'
120
- % str(Path(multiCMD.__file__).parent))
121
- env = dict(os.environ, LC_ALL='C', LANG='C', PYTHONIOENCODING='ascii')
122
- proc = subprocess.run([sys.executable, '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, timeout=30)
123
- assert proc.returncode == 0, proc.stderr
124
- assert proc.stderr == b''
125
- assert b'#' in proc.stdout and b'|50.0% | s' in proc.stdout
126
-
127
-
128
- def test_get_terminal_size_tuple():
129
- cols, rows = get_terminal_size()
130
- assert cols > 0 and rows > 0
131
-
132
-
133
- @pytest.mark.skipif(os.name != "posix", reason="needs a pseudo-terminal")
134
- def test_get_terminal_size_reads_columns_from_stdin_when_stdout_is_piped():
135
- # `cmd | less` on a 200x40 terminal: os.get_terminal_size() fails on the pipe, so the
136
- # TIOCGWINSZ fallback reads stdin, whose winsize struct holds the rows before the columns.
137
- import fcntl
138
- import pty
139
- import struct
140
- import termios
141
- master, slave = pty.openpty()
142
- try:
143
- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 200, 0, 0))
144
- out = subprocess.run(
145
- [sys.executable, "-c", "import multiCMD; print(*multiCMD.get_terminal_size()[:2])"],
146
- stdin=slave, stdout=subprocess.PIPE, cwd=str(Path(__file__).resolve().parents[1]),
147
- universal_newlines=True, check=True,
148
- ).stdout
149
- finally:
150
- os.close(slave)
151
- os.close(master)
152
- assert out.split() == ["200", "40"]
153
-
154
-
155
- def test_input_with_timeout_and_countdown(monkeypatch):
156
- monkeypatch.setattr(builtins, "input", lambda prompt="": "user input")
157
- monkeypatch.setattr(
158
- select, "select", lambda r, w, x, timeout=None: ([sys.stdin], [], [])
159
- )
160
- assert input_with_timeout_and_countdown(5) == "user input"
161
- monkeypatch.setattr(select, "select", lambda r, w, x, timeout=None: ([], [], []))
162
- assert input_with_timeout_and_countdown(1) is None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes