Skip to content

Commit fcd5e84

Browse files
matrixiserkuska
authored andcommitted
bpo-23420: Verify the value of '-s' when execute the CLI of cProfile (GH-9925)
Verify the value for the parameter '-s' of the cProfile CLI. Patch by Robert Kuska. Co-authored-by: Robert Kuska <[email protected]>
1 parent 8e73ad3 commit fcd5e84

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

Lib/cProfile.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ def main():
131131
import os
132132
import sys
133133
import runpy
134+
import pstats
134135
from optparse import OptionParser
135136
usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..."
136137
parser = OptionParser(usage=usage)
@@ -139,7 +140,8 @@ def main():
139140
help="Save stats to <outfile>", default=None)
140141
parser.add_option('-s', '--sort', dest="sort",
141142
help="Sort order when printing to stdout, based on pstats.Stats class",
142-
default=-1)
143+
default=-1,
144+
choices=sorted(pstats.Stats.sort_arg_dict_default))
143145
parser.add_option('-m', dest="module", action="store_true",
144146
help="Profile a library module", default=False)
145147

Lib/test/test_cprofile.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import sys
44
from test.support import run_unittest, TESTFN, unlink
5+
import unittest
56

67
# rip off all interesting stuff from test_profile
78
import cProfile
@@ -76,9 +77,14 @@ def test_profile_as_context_manager(self):
7677
# profile shouldn't be set once we leave the with-block.
7778
self.assertIs(sys.getprofile(), None)
7879

80+
class TestCommandLine(unittest.TestCase):
81+
def test_sort(self):
82+
rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
83+
self.assertGreater(rc, 0)
84+
self.assertIn(b"option -s: invalid choice: 'demo'", err)
7985

8086
def test_main():
81-
run_unittest(CProfileTest)
87+
run_unittest(CProfileTest, TestCommandLine)
8288

8389
def main():
8490
if '-r' not in sys.argv:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Verify the value for the parameter '-s' of the cProfile CLI. Patch by Robert
2+
Kuska

0 commit comments

Comments
 (0)