def test_assert_python_ok_raises(self): # I didn't import the sys module so this child will fail. with self.assertRaises(AssertionError) as error_context: script_helper.assert_python_ok('-c', 'sys.exit(0)') error_msg = str(error_context.exception) self.assertIn('command line:', error_msg) self.assertIn('sys.exit(0)', error_msg, msg='unexpected command line')
def test_doctest_main_issue4197(self): test_src = textwrap.dedent("""\ class Test: ">>> 'line 2'" pass import doctest doctest.testmod() """) pattern = 'File "%s", line 2, in %s' with sql_mode.support.temp_dir() as d: script_name = make_script(d, 'script', test_src) rc, out, err = assert_python_ok(script_name) expected = pattern % (script_name, "__main__.Test") if verbose: print ("Expected line", expected) print ("Got stdout:") print (ascii(out)) self.assertIn(expected.encode('utf-8'), out) zip_name, run_name = make_zip_script(d, "test_zip", script_name, '__main__.py') rc, out, err = assert_python_ok(zip_name) expected = pattern % (run_name, "__main__.Test") if verbose: print ("Expected line", expected) print ("Got stdout:") print (ascii(out)) self.assertIn(expected.encode('utf-8'), out)
def test_hash_randomization(self): # Verify that -R enables hash randomization: self.verify_valid_flag('-R') hashes = [] if os.environ.get('PYTHONHASHSEED', 'random') != 'random': env = dict(os.environ) # copy # We need to test that it is enabled by default without # the environment variable enabling it for us. del env['PYTHONHASHSEED'] env['__cleanenv'] = '1' # consumed by assert_python_ok() else: env = {} for i in range(3): code = 'print(hash("spam"))' rc, out, err = assert_python_ok('-c', code, **env) self.assertEqual(rc, 0) hashes.append(out) hashes = sorted(set(hashes)) # uniq # Rare chance of failure due to 3 random seeds honestly being equal. self.assertGreater(len(hashes), 1, msg='3 runs produced an identical random hash ' ' for "spam": {}'.format(hashes)) # Verify that sys.flags contains hash_randomization code = 'import sys; print("random is", sys.flags.hash_randomization)' rc, out, err = assert_python_ok('-c', code) self.assertEqual(rc, 0) self.assertIn(b'random is 1', out)
def test_run_code(self): # Test expected operation of the '-c' switch # Switch needs an argument assert_python_failure('-c') # Check we get an error for an uncaught exception assert_python_failure('-c', 'raise Exception') # All good if execution is successful assert_python_ok('-c', 'pass')
def test_verbose(self): # -v causes imports to write to stderr. If the write to # stderr itself causes an import to happen (for the output # codec), a recursion loop can occur. rc, out, err = assert_python_ok('-v') self.assertNotIn(b'stack overflow', err) rc, out, err = assert_python_ok('-vv') self.assertNotIn(b'stack overflow', err)
def test_unencodable_filename(self): # Issue #11619: The Python parser and the import machinery must not # encode filenames, especially on Windows pyname = script_helper.make_script('', TESTFN_UNENCODABLE, 'pass') self.addCleanup(unlink, pyname) name = pyname[:-3] script_helper.assert_python_ok("-c", "mod = __import__(%a)" % name, __isolated=False)
def test_import_in_del_does_not_crash(self): # Issue 4236 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\ import sys class C: def __del__(self): import importlib sys.argv.insert(0, C()) """)) script_helper.assert_python_ok(testfn)
def test_issue_8766(self): # "import encodings" emits a warning whereas the warnings is not loaded # or not completely loaded (warnings imports indirectly encodings by # importing linecache) yet with support.temp_cwd() as cwd, support.temp_cwd('encodings'): # encodings loaded by initfsencoding() assert_python_ok('-c', 'pass', PYTHONPATH=cwd) # Use -W to load warnings module at startup assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
def test_del___main__(self): # Issue #15001: PyRun_SimpleFileExFlags() did crash because it kept a # borrowed reference to the dict of __main__ module and later modify # the dict whereas the module was destroyed filename = sql_mode.support.TESTFN self.addCleanup(sql_mode.support.unlink, filename) with open(filename, "w") as script: print("import sys", file=script) print("del sys.modules['__main__']", file=script) assert_python_ok(filename)
def test_run_module(self): # Test expected operation of the '-m' switch # Switch needs an argument assert_python_failure('-m') # Check we get an error for a nonexistent module assert_python_failure('-m', 'fnord43520xyz') # Check the runpy module also gives an error for # a nonexistent module assert_python_failure('-m', 'runpy', 'fnord43520xyz') # All good if module is located and run successfully assert_python_ok('-m', 'timeit', '-n', '1')
def f(self, ext=ext, switch=switch): script_helper.assert_python_ok( *(switch + ['-m', 'compileall', '-q', self.pkgdir])) # Verify the __pycache__ directory contents. self.assertTrue(os.path.exists(self.pkgdir_cachedir)) expected = sorted( base.format(sys.implementation.cache_tag, ext) for base in ('__init__.{}.{}', 'bar.{}.{}')) self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected) # Make sure there are no .pyc files in the source directory. self.assertFalse( [fn for fn in os.listdir(self.pkgdir) if fn.endswith(ext)])
def test_tracemalloc(self): self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, 'w') as fp: fp.write( textwrap.dedent(""" def func(): f = open(__file__) # Emit ResourceWarning f = None func() """)) res = assert_python_ok('-Wd', '-X', 'tracemalloc=2', support.TESTFN) stderr = res.err.decode('ascii', 'replace') # normalize newlines stderr = '\n'.join(stderr.splitlines()) stderr = re.sub('<.*>', '<...>', stderr) expected = textwrap.dedent(''' {fname}:5: ResourceWarning: unclosed file <...> f = None Object allocated at (most recent call first): File "{fname}", lineno 3 f = open(__file__) File "{fname}", lineno 7 func() ''') expected = expected.format(fname=support.TESTFN).strip() self.assertEqual(stderr, expected)
def test_late_resource_warning(self): # Issue #21925: Emitting a ResourceWarning late during the Python # shutdown must be logged. expected = b"sys:1: ResourceWarning: unclosed file " # don't import the warnings module # (_warnings will try to import it) code = "f = open(%a)" % __file__ rc, out, err = assert_python_ok("-Wd", "-c", code) self.assertTrue(err.startswith(expected), ascii(err)) # import the warnings module code = "import warnings; f = open(%a)" % __file__ rc, out, err = assert_python_ok("-Wd", "-c", code) self.assertTrue(err.startswith(expected), ascii(err))
def test_unbuffered_output(self): # Test expected operation of the '-u' switch for stream in ('stdout', 'stderr'): # Binary is unbuffered code = ("import os, sys; sys.%s.buffer.write(b'x'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data, b'x', "binary %s not unbuffered" % stream) # Text is line-buffered code = ("import os, sys; sys.%s.write('x\\n'); os._exit(0)" % stream) rc, out, err = assert_python_ok('-u', '-c', code) data = err if stream == 'stderr' else out self.assertEqual(data.strip(), b'x', "text %s not line-buffered" % stream)
def test_empty_PYTHONPATH_issue16309(self): # On Posix, it is documented that setting PATH to the # empty string is equivalent to not setting PATH at all, # which is an exception to the rule that in a string like # "/bin::/usr/bin" the empty string in the middle gets # interpreted as '.' code = """if 1: import sys path = ":".join(sys.path) path = path.encode("ascii", "backslashreplace") sys.stdout.buffer.write(path)""" rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="") rc2, out2, err2 = assert_python_ok('-c', code, __isolated=False) # regarding to Posix specification, outputs should be equal # for empty and unset PYTHONPATH self.assertEqual(out1, out2)
def test_listfuncs_flag_success(self): with open(TESTFN, 'w') as fd: self.addCleanup(unlink, TESTFN) fd.write("a = 1\n") status, stdout, stderr = assert_python_ok('-m', 'trace', '-l', TESTFN) self.assertIn(b'functions called:', stdout)
def test_print_traceback_at_exit(self): # Issue #22599: Ensure that it is possible to use the traceback module # to display an exception at Python exit code = textwrap.dedent(""" import sys import traceback class PrintExceptionAtExit(object): def __init__(self): try: x = 1 / 0 except Exception: self.exc_info = sys.exc_info() # self.exc_info[1] (traceback) contains frames: # explicitly clear the reference to self in the current # frame to break a reference cycle self = None def __del__(self): traceback.print_exception(*self.exc_info) # Keep a reference in the module namespace to call the destructor # when the module is unloaded obj = PrintExceptionAtExit() """) rc, stdout, stderr = assert_python_ok('-c', code) expected = [ b'Traceback (most recent call last):', b' File "<string>", line 8, in __init__', b'ZeroDivisionError: division by zero' ] self.assertEqual(stderr.splitlines(), expected)
def test_checksum_fodder(self): rc, out, err = assert_python_ok(self.script, self.fodder) self.assertEqual(rc, 0) self.assertTrue(out.startswith(self.fodder_md5)) for part in self.fodder.split(os.path.sep): self.assertIn(part.encode(), out) self.assertFalse(err)
def test_dash_l(self): rc, out, err = assert_python_ok(self.script, '-l', self.fodder) self.assertEqual(rc, 0) self.assertIn(self.fodder_md5, out) parts = self.fodder.split(os.path.sep) self.assertIn(parts[-1].encode(), out) self.assertNotIn(parts[-2].encode(), out)
def check_script_output(self, src, expected): with tempfile.TemporaryDirectory() as tmpd: fn = os.path.join(tmpd, 'sql_mode.py') with open(fn, 'wb') as fp: fp.write(src) res = script_helper.assert_python_ok(fn) self.assertEqual(res.out.rstrip(), expected)
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(self.script) with open('messages.pot') as fp: data = fp.read() header = self.get_header(data) creationDate = header['POT-Creation-Date'] # peel off the escaped newline at the end of string if creationDate.endswith('\\n'): creationDate = creationDate[:-len('\\n')] # This will raise if the date format does not exactly match. datetime.strptime(creationDate, '%Y-%m-%d %H:%M%z')
def test_isolatedmode(self): self.verify_valid_flag('-I') self.verify_valid_flag('-IEs') rc, out, err = assert_python_ok( '-I', '-c', 'from sys import flags as f; ' 'print(f.no_user_site, f.ignore_environment, f.isolated)', # dummyvar to prevent extraneous -E dummyvar="") self.assertEqual(out.strip(), b'1 1 1') with sql_mode.support.temp_cwd() as tmpdir: fake = os.path.join(tmpdir, "uuid.py") main = os.path.join(tmpdir, "main.py") with open(fake, "w") as f: f.write("raise RuntimeError('isolated mode test')\n") with open(main, "w") as f: f.write("import uuid\n") f.write("print('ok')\n") self.assertRaises(subprocess.CalledProcessError, subprocess.check_output, [sys.executable, main], cwd=tmpdir, stderr=subprocess.DEVNULL) out = subprocess.check_output([sys.executable, "-I", main], cwd=tmpdir) self.assertEqual(out.strip(), b"ok")
def test_sort_keys_flag(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile) self.assertEqual(rc, 0) self.assertEqual(out.splitlines(), self.expect_without_sort_keys.encode().splitlines()) self.assertEqual(err, b'')
def test_env_var_enabled_at_startup(self): # tracing at startup code = 'import tracemalloc; print(tracemalloc.is_tracing())' ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='1') stdout = stdout.rstrip() self.assertEqual(stdout, b'True')
def test_env_limit(self): # start and set the number of frames code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())' ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='10') stdout = stdout.rstrip() self.assertEqual(stdout, b'10')
def test_init(self): # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not # written into stdout when the readline module is imported and stdout # is redirected to a pipe. rc, stdout, stderr = assert_python_ok('-c', 'import readline', TERM='xterm-256color') self.assertEqual(stdout, b'')
def test_comma_separated_warnings(self): rc, stdout, stderr = assert_python_ok( "-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning") self.assertEqual( stdout, b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
def test_nonascii(self): rc, stdout, stderr = assert_python_ok( "-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONIOENCODING="utf-8", PYTHONWARNINGS="ignore:DeprecaciónWarning") self.assertEqual(stdout, "['ignore:DeprecaciónWarning']".encode('utf-8'))
def test_stderr_none(self): rc, stdout, stderr = assert_python_ok( "-c", "import sys; sys.stderr = None; " "import warnings; warnings.simplefilter('always'); " "warnings.warn('Warning!')") self.assertEqual(stdout, b'') self.assertNotIn(b'Warning!', stderr) self.assertNotIn(b'Error', stderr)
def test_debugmallocstats(self): # Test sys._debugmallocstats() from sql_mode.support.script_helper import assert_python_ok args = ['-c', 'import sys; sys._debugmallocstats()'] ret, out, err = assert_python_ok(*args) self.assertIn(b"free PyDictObjects", err) # The function has no parameter self.assertRaises(TypeError, sys._debugmallocstats, True)