Skip to content

gh-131178: Add CLI tests for profile module #134103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
gh-131178: Add CLI tests for profile module
  • Loading branch information
ShauryaDusht committed May 16, 2025
commit 07971e10b52bb83ac068b2156ccf322b42cdc06c
4 changes: 2 additions & 2 deletions Lib/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ def f(m, f1=f1):

#****************************************************************************

def main():
def main(args=None):
import os
from optparse import OptionParser

Expand All @@ -570,7 +570,7 @@ def main():
parser.print_usage()
sys.exit(2)

(options, args) = parser.parse_args()
(options, args) = parser.parse_args(args)
sys.argv[:] = args

# The script that we're profiling may chdir, so capture the absolute path
Expand Down
107 changes: 107 additions & 0 deletions Lib/test/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pstats
import unittest
import os
import subprocess
from difflib import unified_diff
from io import StringIO
from test.support.os_helper import TESTFN, unlink, temp_dir, change_cwd
Expand Down Expand Up @@ -130,6 +131,112 @@ def test_output_file_when_changing_directory(self):

self.assertTrue(os.path.exists('out.pstats'))

class ProfileCLITests(unittest.TestCase):
"""Tests for the profile module's command line interface."""

def setUp(self):
# Create a simple Python script to profile
self.script_content = """\
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)

if __name__ == "__main__":
factorial(10)
"""
self.script_file = TESTFN
with open(self.script_file, "w") as f:
f.write(self.script_content)
self.addCleanup(unlink, self.script_file)

def _run_profile_cli(self, *args):
"""Helper to run the profile CLI with given arguments."""
cmd = [sys.executable, '-m', 'profile'] + list(args)
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
stdout, stderr = proc.communicate()
return proc.returncode, stdout, stderr

def test_basic_profile(self):
"""Test basic profiling of a script."""
returncode, stdout, stderr = self._run_profile_cli(self.script_file)
self.assertEqual(returncode, 0)
self.assertIn("function calls", stdout)
self.assertIn("factorial", stdout)

def test_sort_options(self):
"""Test different sort options."""
# List of sort options known to work
sort_options = ['calls', 'cumulative', 'cumtime', 'file',
'filename', 'module', 'ncalls', 'pcalls',
'line', 'stdname', 'time', 'tottime']

# Test each sort option individually
for option in sort_options:
with self.subTest(sort_option=option):
returncode, stdout, stderr = self._run_profile_cli(
'-s', option, self.script_file
)
self.assertEqual(returncode, 0)
self.assertIn("function calls", stdout)

def test_output_file(self):
"""Test writing profile results to a file."""
output_file = TESTFN + '.prof'
self.addCleanup(unlink, output_file)

returncode, stdout, stderr = self._run_profile_cli(
'-o', output_file, self.script_file
)
self.assertEqual(returncode, 0)

# Check that the output file exists and contains profile data
self.assertTrue(os.path.exists(output_file))
stats = pstats.Stats(output_file)
self.assertGreater(stats.total_calls, 0)

def test_invalid_option(self):
"""Test behavior with an invalid option."""
returncode, stdout, stderr = self._run_profile_cli(
'--invalid-option', self.script_file
)
self.assertNotEqual(returncode, 0)
self.assertIn("error", stderr.lower())

def test_no_arguments(self):
"""Test behavior with no arguments."""
returncode, stdout, stderr = self._run_profile_cli()
self.assertNotEqual(returncode, 0)

# Check either stdout or stderr for usage information
combined_output = stdout.lower() + stderr.lower()
self.assertTrue("usage:" in combined_output or
"error:" in combined_output or
"no script filename specified" in combined_output,
"Expected usage information or error message not found")

def test_run_module(self):
"""Test profiling a module with -m option."""
# Create a small module
module_name = "test_profile_module"
module_file = f"{module_name}.py"

with open(module_file, "w") as f:
f.write("print('Module executed')\n")

self.addCleanup(unlink, module_file)

returncode, stdout, stderr = self._run_profile_cli(
'-m', module_name
)
self.assertEqual(returncode, 0)
self.assertIn("Module executed", stdout)
self.assertIn("function calls", stdout)

def regenerate_expected_output(filename, cls):
filename = filename.rstrip('co')
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy