Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
78 changes: 75 additions & 3 deletions Lib/test/test_profiling/test_tracing_profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,11 +243,83 @@ def test_bad_descriptor(self):


class TestCommandLine(unittest.TestCase):
def test_sort(self):
rc, out, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
self.assertGreater(rc, 0)
def test_help(self):
for flag in ('-h', '--help'):
with self.subTest(flag=flag):
_, out, _ = assert_python_ok('-m', 'cProfile', flag)
self.assertIn(b'Usage: cProfile.py', out)
self.assertIn(b'-o OUTFILE', out)
self.assertIn(b'-s SORT', out)

def test_no_args(self):
rc, out, _ = assert_python_failure('-m', 'cProfile')
self.assertEqual(rc, 2)
self.assertIn(b'Usage: cProfile.py', out)

def test_unknown_option(self):
rc, _, err = assert_python_failure('-m', 'cProfile', '--unknown')
self.assertEqual(rc, 2)
self.assertIn(b'no such option', err)

def test_invalid_sort(self):
rc, _, err = assert_python_failure('-m', 'cProfile', '-s', 'demo')
self.assertEqual(rc, 2)
self.assertIn(b"option -s: invalid choice: 'demo'", err)

def test_valid_sort(self):
with tempfile.NamedTemporaryFile("w", suffix=".py",
delete_on_close=False) as f:
f.write("def f(): pass\nf()\n")
f.close()
self.addCleanup(support.os_helper.unlink, f.name)
for sort_key in ('calls', 'cumtime', 'tottime', 'name'):
for flag in ('-s', '--sort'):
with self.subTest(sort_key=sort_key, flag=flag):
_, out, _ = assert_python_ok(
'-m', 'cProfile', flag, sort_key, f.name
)
self.assertIn(b'function calls', out)

def test_outfile(self):
with tempfile.NamedTemporaryFile("w", suffix=".py",
delete_on_close=False) as script:
script.write("def f(): pass\nf()\n")
script.close()
self.addCleanup(support.os_helper.unlink, script.name)
outfile = tempfile.NamedTemporaryFile(delete=False)
outfile.close()
self.addCleanup(support.os_helper.unlink, outfile.name)
for flag in ('-o', '--outfile'):
with self.subTest(flag=flag):
assert_python_ok(
'-m', 'cProfile', flag, outfile.name, script.name
)
with open(outfile.name, 'rb') as f:
self.assertGreater(len(f.read()), 0)

def test_profile_script(self):
with tempfile.NamedTemporaryFile("w", suffix=".py",
delete_on_close=False) as f:
f.write("def f(): pass\nf()\n")
f.close()
self.addCleanup(support.os_helper.unlink, f.name)
_, out, _ = assert_python_ok('-m', 'cProfile', f.name)
self.assertIn(b'function calls', out)
self.assertIn(b'Ordered by', out)

def test_profile_module(self):
_, out, _ = assert_python_ok(
'-m', 'cProfile', '-m', 'timeit', '-n', '1', 'pass'
)
self.assertIn(b'function calls', out)

def test_nonexistent_script(self):
rc, _, err = assert_python_failure(
'-m', 'cProfile', 'nonexistent_script.py'
)
self.assertEqual(rc, 1)
self.assertIn(b'No such file or directory', err)

def test_profile_script_importing_main(self):
"""Check that scripts that reference __main__ see their own namespace
when being profiled."""
Expand Down
52 changes: 44 additions & 8 deletions Lib/test/test_tools/test_i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,13 @@ def extract_from_str(self, module_content, *, args=(), strict=True,
res = assert_python_ok('-Xutf8', self.script, *args, filename)
if strict:
self.assertEqual(res.err, b'')
with open('messages.pot', encoding='utf-8') as fp:
data = fp.read()
if Path('messages.pot').exists():
with open('messages.pot', encoding='utf-8') as fp:
data = fp.read()
else:
# No output file is generated when no messages are found
# (gh-133049); there are no msgids to return.
data = ''
if not raw:
data = self.get_msgids(data)
if not with_stderr:
Expand All @@ -122,7 +127,8 @@ def test_header(self):
http://www.gnu.org/software/gettext/manual/gettext.html#Header-Entry
"""
with temp_cwd(None) as cwd:
assert_python_ok('-Xutf8', self.script)
Path('test.py').write_text("_('hello')\n", encoding='utf-8')
assert_python_ok('-Xutf8', self.script, 'test.py')
with open('messages.pot', encoding='utf-8') as fp:
data = fp.read()
header = self.get_header(data)
Expand All @@ -149,7 +155,8 @@ def test_POT_Creation_Date(self):
""" Match the date format from xgettext for POT-Creation-Date """
from datetime import datetime
with temp_cwd(None) as cwd:
assert_python_ok('-Xutf8', self.script)
Path('test.py').write_text("_('hello')\n", encoding='utf-8')
assert_python_ok('-Xutf8', self.script, 'test.py')
with open('messages.pot', encoding='utf-8') as fp:
data = fp.read()
header = self.get_header(data)
Expand All @@ -165,9 +172,10 @@ def test_POT_Creation_Date(self):
def test_output_option(self):
for opt in ('-o', '--output='):
with temp_cwd():
assert_python_ok(self.script, f'{opt}test')
Path('test.py').write_text("_('hello')\n", encoding='utf-8')
assert_python_ok(self.script, f'{opt}test', 'test.py')
self.assertTrue(os.path.exists('test'))
res = assert_python_ok(self.script, f'{opt}-')
res = assert_python_ok(self.script, f'{opt}-', 'test.py')
self.assertIn(b'Project-Id-Version: PACKAGE VERSION', res.out)

def test_funcdocstring(self):
Expand Down Expand Up @@ -386,7 +394,7 @@ async def _(x):
class _(object):
pass
'''))
self.assertEqual(msgids, [''])
self.assertEqual(msgids, [])

def test_pygettext_output(self):
"""Test that the pygettext output exactly matches snapshots."""
Expand Down Expand Up @@ -450,6 +458,34 @@ def test_error_messages(self):
"*** test.py:3: Variable positional arguments are not allowed in gettext calls\n"
)

def test_no_messages_no_output(self):
"""No output file is generated when no messages are found (gh-133049)."""
with temp_cwd(None):
with open('test.py', 'w', encoding='utf-8') as fp:
fp.write('x = 1\n')
res = assert_python_ok('-Xutf8', self.script, 'test.py')
self.assertEqual(res.out, b'')
self.assertEqual(res.err, b'')
self.assertFalse(Path('messages.pot').exists())

def test_no_messages_no_stdout_output(self):
"""No output is written to stdout when no messages are found (gh-133049)."""
with temp_cwd(None):
with open('test.py', 'w', encoding='utf-8') as fp:
fp.write('x = 1\n')
res = assert_python_ok('-Xutf8', self.script, '-o', '-', 'test.py')
self.assertEqual(res.out, b'')
self.assertEqual(res.err, b'')

def test_no_messages_verbose(self):
"""Verbose mode reports that no output file was generated (gh-133049)."""
with temp_cwd(None):
with open('test.py', 'w', encoding='utf-8') as fp:
fp.write('x = 1\n')
res = assert_python_ok('-Xutf8', self.script, '-v', 'test.py')
self.assertIn(b'no output file generated', res.err)
self.assertFalse(Path('messages.pot').exists())

def test_extract_all_comments(self):
"""
Test that the --add-comments option without an
Expand Down Expand Up @@ -584,7 +620,7 @@ def test_multiple_keywords_same_funcname_errors(self):
_(42, y)
'''), args=('--keyword=_:1', '--keyword=_:2'), with_stderr=True,
strict=False)
self.assertEqual(msgids, [''])
self.assertEqual(msgids, [])
# Normalize line endings on Windows
stderr = stderr.decode('utf-8').replace('\r', '')
self.assertEqual(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add tests for the ``cProfile`` command-line interface.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:program:`pygettext` now generates no output when no translatable messages
are found, like :program:`xgettext`.
7 changes: 7 additions & 0 deletions Tools/i18n/pygettext.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,13 @@ class Options:

visitor.visit_file(source, filename)

# xgettext-compatible: no output is generated if there are no messages
if not visitor.messages:
if options.verbose:
print("No module matched or no strings to extract; no output file generated.",
file=sys.stderr)
sys.exit(0)

# write the output
if options.outfile == '-':
fp = sys.stdout
Expand Down
Loading