[Python-checkins] [3.6] bpo-23420: Verify the value of '-s' when execute the CLI of cProfile (GH-9925) (GH-9927)

Victor Stinner webhook-mailer at python.org
Wed Oct 17 07:48:55 EDT 2018

commit: 669fa8b6376ee8703ae4383536dfcc0e96e51b78
branch: 3.6
author: Stéphane Wirtel <stephane at wirtel.be>
committer: Victor Stinner <vstinner at redhat.com>
date: 2018-10-17T13:48:52+02:00

[3.6] bpo-23420: Verify the value of '-s' when execute the CLI of cProfile (GH-9925) (GH-9927)

Verify the value for the parameter '-s' of the cProfile CLI. Patch by Robert

Co-authored-by: Robert Kuska <rkuska at gmail.com>
(cherry picked from commit fcd5e84a515e19409840c570730f0728e9fcfc83)

A Misc/NEWS.d/next/Library/2018-10-17-11-00-00.bpo-23420.Lq74Uu.rst
M Lib/cProfile.py
M Lib/test/test_cprofile.py

diff --git a/Lib/cProfile.py b/Lib/cProfile.py
index 6ae8512ddd2e..a6d4476750dc 100755
--- a/Lib/cProfile.py
+++ b/Lib/cProfile.py
@@ -121,7 +121,7 @@ def label(code):
 # ____________________________________________________________
 def main():
-    import os, sys
+    import os, sys, pstats
     from optparse import OptionParser
     usage = "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
     parser = OptionParser(usage=usage)
@@ -130,7 +130,8 @@ def main():
         help="Save stats to <outfile>", default=None)
     parser.add_option('-s', '--sort', dest="sort",
         help="Sort order when printing to stdout, based on pstats.Stats class",
-        default=-1)
+        default=-1,
+        choices=sorted(pstats.Stats.sort_arg_dict_default))
     if not sys.argv[1:]:
diff --git a/Lib/test/test_cprofile.py b/Lib/test/test_cprofile.py
index 53f891733029..0008aaba4a70 100644
--- a/Lib/test/test_cprofile.py
+++ b/Lib/test/test_cprofile.py
@@ -1,7 +1,9 @@
 """Test suite for the cProfile module."""
 import sys
+import unittest
 from test.support import run_unittest, TESTFN, unlink
+from test.support.script_helper import assert_python_failure
 # rip off all interesting stuff from test_profile
 import cProfile
@@ -36,8 +38,15 @@ def test_bad_counter_during_dealloc(self):
+class TestCommandLine(unittest.TestCase):
+    def test_sort(self):
+        rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
+        self.assertGreater(rc, 0)
+        self.assertIn(b"option -s: invalid choice: 'demo'", err)
 def test_main():
-    run_unittest(CProfileTest)
+    run_unittest(CProfileTest, TestCommandLine)
 def main():
     if '-r' not in sys.argv:
diff --git a/Misc/NEWS.d/next/Library/2018-10-17-11-00-00.bpo-23420.Lq74Uu.rst b/Misc/NEWS.d/next/Library/2018-10-17-11-00-00.bpo-23420.Lq74Uu.rst
new file mode 100644
index 000000000000..034e7e53970a
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2018-10-17-11-00-00.bpo-23420.Lq74Uu.rst
@@ -0,0 +1,2 @@
+Verify the value for the parameter '-s' of the cProfile CLI. Patch by Robert

More information about the Python-checkins mailing list