Skip to content

Commit ebf9b25

Browse files
committed
finish
1 parent 639644b commit ebf9b25

File tree

2 files changed

+12
-18
lines changed

2 files changed

+12
-18
lines changed

Lib/mimetypes.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -717,29 +717,30 @@ def _parse_args(args):
717717

718718

719719
def _main(args=None):
720-
"""Run the mimetypes command-line interface."""
720+
"""Run the mimetypes command-line interface and return a text to print."""
721721
import sys
722722

723723
args, help_text = _parse_args(args)
724-
if not args.type:
725-
print(help_text)
726-
return
727724

725+
results = []
728726
if args.extension:
729727
for gtype in args.type:
730728
guess = guess_extension(gtype, not args.lenient)
731729
if guess:
732-
print(str(guess))
730+
results.append(str(guess))
733731
else:
734-
print(f"error: unknown type {gtype}", file=sys.stderr)
732+
sys.exit(f"error: unknown type {gtype}")
733+
return '\n'.join(results)
735734
else:
736735
for gtype in args.type:
737736
guess, encoding = guess_type(gtype, not args.lenient)
738737
if guess:
739-
print(f"type: {guess} encoding: {encoding}")
738+
results.append(f"type: {guess} encoding: {encoding}")
740739
else:
741-
print(f"error: media type unknown for {gtype}", file=sys.stderr)
740+
sys.exit(f"error: media type unknown for {gtype}")
741+
return '\n'.join(results)
742+
return help_text
742743

743744

744745
if __name__ == '__main__':
745-
_main()
746+
print(_main())

Lib/test/test_mimetypes.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import contextlib
21
import io
32
import mimetypes
43
import os
@@ -477,22 +476,16 @@ def test_invocation(self):
477476
("-e image/jpeg", ".jpg"),
478477
("-l foo.webp", "type: image/webp encoding: None"),
479478
]:
480-
with self.subTest(command=command):
481-
out = io.StringIO()
482-
with contextlib.redirect_stdout(out):
483-
mimetypes._main(shlex.split(command))
484-
self.assertEqual(out.getvalue().strip(), expected)
479+
self.assertEqual(mimetypes._main(shlex.split(command)), expected)
485480

486481
def test_invocation_error(self):
487482
for command, expected in [
488483
("-e image/jpg", "error: unknown type image/jpg"),
489484
("foo.bar_ext", "error: media type unknown for foo.bar_ext"),
490485
]:
491486
with self.subTest(command=command):
492-
err = io.StringIO()
493-
with contextlib.redirect_stderr(err):
487+
with self.assertRaisesRegex(SystemExit, expected):
494488
mimetypes._main(shlex.split(command))
495-
self.assertIn(expected, err.getvalue().strip())
496489

497490

498491
if __name__ == "__main__":

0 commit comments

Comments
 (0)