diff --git a/Doc/library/poplib.rst b/Doc/library/poplib.rst index cd3a58016e9c12..6283b23b951f4d 100644 --- a/Doc/library/poplib.rst +++ b/Doc/library/poplib.rst @@ -266,3 +266,75 @@ retrieves and prints all messages:: At the end of the module, there is a test section that contains a more extensive example of usage. + + +.. _poplib-cli: + +Command-line usage +------------------ + +The :mod:`!poplib` module can be executed from the command line. + +.. code-block:: sh + + python -m poplib [-h] [--port PORT] [--timeout TIMEOUT] [-v] [--ssl | --tls] host user password + +The following options are accepted: + +.. program:: poplib + +.. option:: -h, --help + + Show the help message and exit. + + .. versionadded:: next + +.. option:: host + + POP3 host. + +.. option:: user + + POP3 :meth:`user `. + +.. option:: password + + POP3 :meth:`password `. + +.. option:: --port PORT + + POP3 port. + + .. versionadded:: next + +.. option:: --timeout TIMEOUT + + Connection timeout. + + .. versionadded:: next + +.. option:: --ssl + + Use :class:`POP3_SSL` if it is available. + If not, this is a no-op. + Mutually exclusive with :option:`--tls`. + + .. versionadded:: next + +.. option:: --tls + + Use :meth:`~POP3.stls` if it is available. + If not, this is a no-op. + Mutually exclusive with :option:`--ssl`. + + .. versionadded:: next + +.. option:: -v + --verbose + + Set the output :meth:`verbosity `. + Useful for debug purposes. + This option can be passed multiple times like: + ``-vv`` or ``--vebose --verbose``. + + .. versionadded:: next diff --git a/Lib/poplib.py b/Lib/poplib.py index b97274c5c32ee6..1f12e8c8731a6c 100644 --- a/Lib/poplib.py +++ b/Lib/poplib.py @@ -463,17 +463,96 @@ def stls(self, context=None): __all__.append("POP3_SSL") -if __name__ == "__main__": - a = POP3(sys.argv[1]) - print(a.getwelcome()) - a.user(sys.argv[2]) - a.pass_(sys.argv[3]) - a.list() - (numMsgs, totalSize) = a.stat() - for i in range(1, numMsgs + 1): - (header, msg, octets) = a.retr(i) - print("Message %d:" % i) + +# CLI + +def _parse_args(argv=None): + import argparse + + parser = argparse.ArgumentParser() + # Params kept like this for the backward compatibility: + parser.add_argument('host', help='POP3 host') + parser.add_argument('user', help='POP3 user') + parser.add_argument('password', help='POP3 password') + # New ones: + parser.add_argument( + '--port', + type=int, + default=None, + help='port to be used for the connection', + ) + parser.add_argument( + '--timeout', + type=int, + default=None, + help='timeout to be used for the connection', + ) + parser.add_argument( + '-v', + '--verbose', + action='count', + default=0, + help='flag to show the verbose debug output, can be: 0 (default), 1, 2', + ) + group = parser.add_mutually_exclusive_group() + group.add_argument( + '--ssl', + action='store_true', + help='should SSL be used (when SSL is not available, it is a no-op)', + ) + group.add_argument( + '--tls', + action='store_true', + help='should TLS be used (when SSL is not available, it is a no-op)', + ) + + return parser.parse_args(argv) + + +def _build_client(args, ssl_context=None): + kwargs = {} + if args.port is not None: + kwargs['port'] = args.port + if args.timeout is not None: + kwargs['timeout'] = args.timeout + if ssl_context is not None: + kwargs['context'] = ssl_context + + if HAVE_SSL and args.ssl: + assert not args.tls # mutually exclusive + pop3 = POP3_SSL(args.host, **kwargs) + else: + pop3 = POP3(args.host, **kwargs) + pop3.set_debuglevel(args.verbose) + if HAVE_SSL and args.tls: + assert not args.ssl # mutually exclusive + pop3.stls() + return pop3 + + +def _run_main(pop3, args): + print(pop3.getwelcome().decode(pop3.encoding)) + pop3.user(args.user) + pop3.pass_(args.password) + pop3.list() + + num_msgs, _total_size = pop3.stat() + for i in range(1, num_msgs + 1): + _header, msg, _octets = pop3.retr(i) + print(f"Message {i}:") for line in msg: - print(' ' + line) + print(' ', line.decode(pop3.encoding)) print('-----------------------') - a.quit() + + +def _main(argv=None): + args = _parse_args(argv) + pop3 = _build_client(args) + try: + _run_main(pop3, args) + finally: + pop3.quit() + + +if __name__ == "__main__": + _main() diff --git a/Lib/test/test_poplib.py b/Lib/test/test_poplib.py index f08b945c8f57e5..c57d5c4878f51a 100644 --- a/Lib/test/test_poplib.py +++ b/Lib/test/test_poplib.py @@ -8,12 +8,17 @@ import os import errno import threading +import contextlib +import textwrap +import io import unittest from unittest import TestCase, skipUnless from test import support as test_support from test.support import hashlib_helper from test.support import socket_helper +from test.support import os_helper +from test.support import script_helper from test.support import threading_helper from test.support import asynchat from test.support import asyncore @@ -257,22 +262,37 @@ def handle_error(self): raise -class TestPOP3Class(TestCase): +class POP3Server: + server_handler = None + valid_user = 'guido' + valid_pass = 'python' + def assertOK(self, resp): self.assertStartsWith(resp, b"+OK") def setUp(self): self.server = DummyPOP3Server((HOST, PORT)) + # Use default one if not specified: + if self.server_handler is not None: + self.server.handler = self.server_handler self.server.start() - self.client = poplib.POP3(self.server.host, self.server.port, - timeout=test_support.LOOPBACK_TIMEOUT) def tearDown(self): - self.client.close() self.server.stop() # Explicitly clear the attribute to prevent dangling thread self.server = None + +class TestPOP3Class(POP3Server, TestCase): + def setUp(self): + super().setUp() + self.client = poplib.POP3(self.server.host, self.server.port, + timeout=test_support.LOOPBACK_TIMEOUT) + + def tearDown(self): + self.client.close() + super().tearDown() + def test_getwelcome(self): self.assertEqual(self.client.getwelcome(), b'+OK dummy pop3 server ready. ') @@ -451,9 +471,8 @@ class TestPOP3_SSLClass(TestPOP3Class): # repeat previous tests by using poplib.POP3_SSL def setUp(self): - self.server = DummyPOP3Server((HOST, PORT)) - self.server.handler = DummyPOP3_SSLHandler - self.server.start() + self.server_handler = DummyPOP3_SSLHandler + POP3Server.setUp(self) self.client = poplib.POP3_SSL(self.server.host, self.server.port) def test__all__(self): @@ -469,7 +488,7 @@ def test_context(self): context=ctx) self.assertIsInstance(self.client.sock, ssl.SSLSocket) self.assertIs(self.client.sock.context, ctx) - self.assertStartsWith(self.client.noop(), b'+OK') + self.assertOK(self.client.noop()) def test_stls(self): self.assertRaises(poplib.error_proto, self.client.stls) @@ -478,7 +497,7 @@ def test_stls(self): def test_stls_capa(self): capa = self.client.capa() - self.assertFalse('STLS' in capa.keys()) + self.assertNotIn('STLS', capa.keys()) @requires_ssl @@ -486,8 +505,7 @@ class TestPOP3_TLSClass(TestPOP3Class): # repeat previous tests by using poplib.POP3.stls() def setUp(self): - self.server = DummyPOP3Server((HOST, PORT)) - self.server.start() + POP3Server.setUp(self) self.client = poplib.POP3(self.server.host, self.server.port, timeout=test_support.LOOPBACK_TIMEOUT) self.client.stls() @@ -512,7 +530,7 @@ def test_stls(self): def test_stls_capa(self): capa = self.client.capa() - self.assertFalse(b'STLS' in capa.keys()) + self.assertNotIn(b'STLS', capa.keys()) class TestTimeouts(TestCase): @@ -572,6 +590,156 @@ def testTimeoutValue(self): poplib.POP3(HOST, self.port, timeout=0) +def invoke_command_line(*args): + cmd_args = ["-m", "poplib", *args] + + with os_helper.EnvironmentVarGuard() as env: + env["PYTHONUTF8"] = "1" + env["PYTHONIOENCODING"] = "utf-8" + proc = script_helper.spawn_python( + *cmd_args, text=True, env=env, + encoding='utf-8', errors='replace', + ) + + output = script_helper.kill_python(proc) + return_code = proc.returncode + return return_code, os.path.normpath(textwrap.dedent(output).strip()) + + +@contextlib.contextmanager +def pop3_client(text_args, ssl_context=None): + output = io.StringIO() + + args = poplib._parse_args(text_args) + with contextlib.redirect_stdout(output): + client = poplib._build_client(args, ssl_context) + + try: + yield client, args, output + finally: + client.quit() + + +class TestPOP3CommandLine(POP3Server, TestCase): + def test_regular_usage(self): + with pop3_client( + ( + self.server.host, + self.valid_user, + self.valid_pass, + f'--port={self.server.port}', + ), + ) as (client, args, output): + poplib._run_main(client, args) + + output_text = output.getvalue() + self.assertTrue(output_text.startswith('+OK')) + self.assertEqual(output_text.count('From: postmaster@python.org'), 10) + self.assertEqual(output_text.count('Subject: Dummy'), 10) + + def test_verbose_usage(self): + with pop3_client( + ( + self.server.host, + self.valid_user, + self.valid_pass, + f'--port={self.server.port}', + '-vv', + ), + ) as (client, args, output): + poplib._run_main(client, args) + + output_text = output.getvalue() + self.assertTrue(output_text.startswith('+OK')) + self.assertEqual(output_text.count('From: postmaster@python.org'), 20) + self.assertEqual(output_text.count('Subject: Dummy'), 20) + self.assertIn('*stat*', output_text) + + @requires_ssl + def test_regular_tls(self): + with pop3_client( + ( + self.server.host, + self.valid_user, + self.valid_pass, + f'--port={self.server.port}', + f'--timeout={int(test_support.LOOPBACK_TIMEOUT)}', + '--tls', + ), + ) as (client, args, output): + poplib._run_main(client, args) + + output_text = output.getvalue() + self.assertTrue(output_text.startswith('+OK')) + self.assertEqual(output_text.count('From: postmaster@python.org'), 10) + self.assertEqual(output_text.count('Subject: Dummy'), 10) + + @test_support.force_not_colorized + @test_support.requires_subprocess() + def test_help(self): + for help_opt in ['-h', '--help']: + with self.subTest(help_opt=help_opt): + return_code, output = invoke_command_line(help_opt) + self.assertEqual(return_code, 0) + self.assertIn('usage:', output) + self.assertIn('positional arguments:', output) + self.assertIn('options:', output) + + @test_support.force_not_colorized + @test_support.requires_subprocess() + def test_missing_params(self): + return_code, output = invoke_command_line() + self.assertEqual(return_code, 2) + self.assertIn('required: host, user, password', output) + + @test_support.force_not_colorized + @test_support.requires_subprocess() + def test_wrong_params(self): + return_code, output = invoke_command_line( + 'host', 'user', 'passd', '--missing', + ) + self.assertEqual(return_code, 2) + self.assertIn('unrecognized arguments: --missing', output) + + @test_support.force_not_colorized + @test_support.requires_subprocess() + def test_ssl_and_tls(self): + return_code, output = invoke_command_line( + 'host', 'user', 'passd', '--ssl', '--tls', + ) + self.assertEqual(return_code, 2) + self.assertIn('argument --tls: not allowed with argument --ssl', output) + + +class TestPOP3CommandLineSSL(POP3Server, TestCase): + if SUPPORTS_SSL: + server_handler = DummyPOP3_SSLHandler + + @requires_ssl + def test_regular_ssl(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + + with pop3_client( + ( + self.server.host, + self.valid_user, + self.valid_pass, + f'--port={self.server.port}', + f'--timeout={int(test_support.LOOPBACK_TIMEOUT)}', + '--ssl', + ), + ssl_context=ctx, + ) as (client, args, output): + poplib._run_main(client, args) + + output_text = output.getvalue() + self.assertTrue(output_text.startswith('+OK')) + self.assertEqual(output_text.count('From: postmaster@python.org'), 10) + self.assertEqual(output_text.count('Subject: Dummy'), 10) + + def setUpModule(): thread_info = threading_helper.threading_setup() unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info) diff --git a/Misc/NEWS.d/next/Library/2026-11-16-16-27-18.gh-issue-162073.6kEUYg.rst b/Misc/NEWS.d/next/Library/2026-11-16-16-27-18.gh-issue-162073.6kEUYg.rst new file mode 100644 index 00000000000000..468b2d18206ee2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-16-16-27-18.gh-issue-162073.6kEUYg.rst @@ -0,0 +1,3 @@ +Improve and fix CLI for :mod:`poplib`. Now it support ``--help``, +``--port``, ``--timeout``, ``--ssl``, ``--tls``, ``-v`` as options. +Now it also handles missing / incorrect arguments properly.