def test_expat_locator_withinfo(self): result = StringIO() xmlgen = XMLGenerator(result) parser = create_parser() parser.setContentHandler(xmlgen) parser.parse(findfile("test.xml")) self.assertEqual(parser.getSystemId(), findfile("test.xml")) self.assertEqual(parser.getPublicId(), None)
def test_snd_memory(self): with open(support.findfile('pluck-pcm8.wav', subdir='audiodata'), 'rb') as f: audio_data = f.read() safe_PlaySound(audio_data, winsound.SND_MEMORY) audio_data = bytearray(audio_data) safe_PlaySound(audio_data, winsound.SND_MEMORY)
def test_parse_errors(self): cf = self.newconfig() self.parse_error(cf, configparser.ParsingError, "[Foo]\n" "{}val-without-opt-name\n".format(self.delimiters[0])) self.parse_error(cf, configparser.ParsingError, "[Foo]\n" "{}val-without-opt-name\n".format(self.delimiters[1])) e = self.parse_error(cf, configparser.MissingSectionHeaderError, "No Section!\n") self.assertEqual(e.args, ('<???>', 1, "No Section!\n")) if not self.allow_no_value: e = self.parse_error(cf, configparser.ParsingError, "[Foo]\n wrong-indent\n") self.assertEqual(e.args, ('<???>',)) # read_file on a real file tricky = support.findfile("cfgparser.3") if self.delimiters[0] == '=': error = configparser.ParsingError expected = (tricky,) else: error = configparser.MissingSectionHeaderError expected = (tricky, 1, ' # INI with as many tricky parts as possible\n') with open(tricky, encoding='utf-8') as f: e = self.parse_error(cf, error, f) self.assertEqual(e.args, expected)
def test_random_files(self): # Test roundtrip on random python modules. # pass the '-ucpu' option to process the full directory. import glob, random fn = support.findfile("tokenize_tests.txt") tempdir = os.path.dirname(fn) or os.curdir testfiles = glob.glob(os.path.join(tempdir, "test*.py")) # Tokenize is broken on test_pep3131.py because regular expressions are # broken on the obscure unicode identifiers in it. *sigh* # With roundtrip extended to test the 5-tuple mode of untokenize, # 7 more testfiles fail. Remove them also until the failure is diagnosed. testfiles.remove(os.path.join(tempdir, "test_pep3131.py")) for f in ('buffer', 'builtin', 'fileio', 'inspect', 'os', 'platform', 'sys'): testfiles.remove(os.path.join(tempdir, "test_%s.py") % f) if not support.is_resource_enabled("cpu"): testfiles = random.sample(testfiles, 10) for testfile in testfiles: with open(testfile, 'rb') as f: with self.subTest(file=testfile): self.check_roundtrip(f)
def test_cfgparser_dot_3(self): tricky = support.findfile("cfgparser.3") cf = self.newconfig() self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1) self.assertEqual(cf.sections(), ['strange', 'corruption', 'yeah, sections can be ' 'indented as well', 'another one!', 'no values here', 'tricky interpolation', 'more interpolation']) self.assertEqual(cf.getint(self.default_section, 'go', vars={'interpolate': '-1'}), -1) with self.assertRaises(ValueError): # no interpolation will happen cf.getint(self.default_section, 'go', raw=True, vars={'interpolate': '-1'}) self.assertEqual(len(cf.get('strange', 'other').split('\n')), 4) self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10) longname = 'yeah, sections can be indented as well' self.assertFalse(cf.getboolean(longname, 'are they subsections')) self.assertEqual(cf.get(longname, 'lets use some Unicode'), '片仮名') self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and # `go` from DEFAULT with self.assertRaises(configparser.InterpolationMissingOptionError): cf.items('no values here') self.assertEqual(cf.get('tricky interpolation', 'lets'), 'do this') self.assertEqual(cf.get('tricky interpolation', 'lets'), cf.get('tricky interpolation', 'go')) self.assertEqual(cf.get('more interpolation', 'lets'), 'go shopping')
def test_close_opened_files_on_error(self): non_aifc_file = findfile('pluck-pcm8.wav', subdir='audiodata') with check_no_resource_warning(self): with self.assertRaises(aifc.Error): # Try opening a non-AIFC file, with the expectation that # `aifc.open` will fail (without raising a ResourceWarning) f = self.f = aifc.open(non_aifc_file, 'rb')
def test_load_file(self): # Borrow test/cfgparser.1 from test_configparser. config_path = findfile('cfgparser.1') parser = config.IdleConfParser(config_path) parser.Load() self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar') self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo'])
def test_print_sans_lib(self): """Encodes and decodes using utf-8 after in an environment without the standard library Checks that the builtin utf-8 codec is always available: http://bugs.jython.org/issue1458""" subprocess.call([sys.executable, "-J-Dpython.cachedir.skip=true", "-J-Dpython.security.respectJavaAccessibility=false", support.findfile('print_sans_lib.py')])
def test_expat_inpsource_sysid(self): parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) parser.parse(InputSource(findfile("test.xml"))) self.assertEqual(result.getvalue(), xml_test_out)
def test_html_diff(self): # Check SF patch 914575 for generating HTML differences f1a = ((patch914575_from1 + '123\n'*10)*3) t1a = (patch914575_to1 + '123\n'*10)*3 f1b = '456\n'*10 + f1a t1b = '456\n'*10 + t1a f1a = f1a.splitlines() t1a = t1a.splitlines() f1b = f1b.splitlines() t1b = t1b.splitlines() f2 = patch914575_from2.splitlines() t2 = patch914575_to2.splitlines() f3 = patch914575_from3 t3 = patch914575_to3 i = difflib.HtmlDiff() j = difflib.HtmlDiff(tabsize=2) k = difflib.HtmlDiff(wrapcolumn=14) full = i.make_file(f1a,t1a,'from','to',context=False,numlines=5) tables = '\n'.join( [ '<h2>Context (first diff within numlines=5(default))</h2>', i.make_table(f1a,t1a,'from','to',context=True), '<h2>Context (first diff after numlines=5(default))</h2>', i.make_table(f1b,t1b,'from','to',context=True), '<h2>Context (numlines=6)</h2>', i.make_table(f1a,t1a,'from','to',context=True,numlines=6), '<h2>Context (numlines=0)</h2>', i.make_table(f1a,t1a,'from','to',context=True,numlines=0), '<h2>Same Context</h2>', i.make_table(f1a,f1a,'from','to',context=True), '<h2>Same Full</h2>', i.make_table(f1a,f1a,'from','to',context=False), '<h2>Empty Context</h2>', i.make_table([],[],'from','to',context=True), '<h2>Empty Full</h2>', i.make_table([],[],'from','to',context=False), '<h2>tabsize=2</h2>', j.make_table(f2,t2), '<h2>tabsize=default</h2>', i.make_table(f2,t2), '<h2>Context (wrapcolumn=14,numlines=0)</h2>', k.make_table(f3.splitlines(),t3.splitlines(),context=True,numlines=0), '<h2>wrapcolumn=14,splitlines()</h2>', k.make_table(f3.splitlines(),t3.splitlines()), '<h2>wrapcolumn=14,splitlines(True)</h2>', k.make_table(f3.splitlines(True),t3.splitlines(True)), ]) actual = full.replace('</body>','\n%s\n</body>' % tables) # temporarily uncomment next three lines to baseline this test #f = open('test_difflib_expect.html','w') #f.write(actual) #f.close() expect = open(findfile('test_difflib_expect.html')).read() self.assertEqual(actual,expect)
def test_expat_file(self): parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) parser.parse(open(findfile("test.xml"))) self.assertEquals(result.getvalue(), xml_test_out)
def test_data(self): for filename, expected in TEST_FILES: filename = findfile(filename, subdir='imghdrdata') self.assertEqual(imghdr.what(filename), expected) with open(filename, 'rb') as stream: self.assertEqual(imghdr.what(stream), expected) with open(filename, 'rb') as stream: data = stream.read() self.assertEqual(imghdr.what(None, data), expected) self.assertEqual(imghdr.what(None, bytearray(data)), expected)
def test_bug_1727780(self): # verify that version-2-pickles can be loaded # fine, whether they are created on 32-bit or 64-bit # platforms, and that version-3-pickles load fine. files = [("randv2_32.pck", 780), ("randv2_64.pck", 866), ("randv3.pck", 343)] for file, value in files: f = open(support.findfile(file), "rb") r = pickle.load(f) f.close() self.assertEqual(int(r.random() * 1000), value)
def test_string_data(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", BytesWarning) for filename, _ in TEST_FILES: filename = findfile(filename, subdir='imghdrdata') with open(filename, 'rb') as stream: data = stream.read().decode('latin1') with self.assertRaises(TypeError): imghdr.what(io.StringIO(data)) with self.assertRaises(TypeError): imghdr.what(None, data)
def test_expat_inpsource_stream(self): parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) inpsrc = InputSource() inpsrc.setByteStream(open(findfile("test.xml"))) parser.parse(inpsrc) self.assertEqual(result.getvalue(), xml_test_out)
def test_encoding(self): getpreferredencoding = locale.getpreferredencoding self.addCleanup(setattr, locale, 'getpreferredencoding', getpreferredencoding) locale.getpreferredencoding = lambda: 'ascii' filename = support.findfile("mime.types") mimes = mimetypes.MimeTypes([filename]) exts = mimes.guess_all_extensions('application/vnd.geocube+xml', strict=True) self.assertEqual(exts, ['.g3', '.g\xb3'])
def test_all(self): # Run the tester in a sub-process, to make sure there is only one # thread (for reliable signal delivery). tester = support.findfile("eintr_tester.py", subdir="eintrdata") if support.verbose: args = [sys.executable, tester] with subprocess.Popen(args) as proc: exitcode = proc.wait() self.assertEqual(exitcode, 0) else: script_helper.assert_python_ok(tester)
def test_external(self): source = support.findfile('clinic.test') with open(source, 'r', encoding='utf-8') as f: original = f.read() with support.temp_dir() as testdir: testfile = os.path.join(testdir, 'clinic.test.c') with open(testfile, 'w', encoding='utf-8') as f: f.write(original) clinic.parse_file(testfile, force=True) with open(testfile, 'r', encoding='utf-8') as f: result = f.read() self.assertEqual(result, original)
def check_create_from_file(self, ext): testfile = support.findfile("python." + ext, subdir="imghdrdata") image = tkinter.PhotoImage("::img::test", master=self.root, file=testfile) self.assertEqual(str(image), "::img::test") self.assertEqual(image.type(), "photo") self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image["data"], "") self.assertEqual(image["file"], testfile) self.assertIn("::img::test", self.root.image_names()) del image self.assertNotIn("::img::test", self.root.image_names())
def test_syspath_initializer(self): fn = support.findfile('check_for_initializer_in_syspath.py') env = dict(CLASSPATH='tests/data/initializer', PATH=os.environ.get('PATH', '')) if WINDOWS: # TMP is needed to give property java.io.tmpdir a sensible value env['TMP'] = os.environ.get('TMP', '.') # SystemRoot is needed to remote debug the subprocess JVM env['SystemRoot'] = os.environ.get('SystemRoot', '') self.assertEqual(0, subprocess.call([sys.executable, fn], env=env))
def test_all(self): # Run the tester in a sub-process, to make sure there is only one # thread (for reliable signal delivery). tester = support.findfile("eintr_tester.py", subdir="eintrdata") # FIXME: Issue #25122, always run in verbose mode to debug hang on FreeBSD if True: #support.verbose: args = [sys.executable, tester] with subprocess.Popen(args) as proc: exitcode = proc.wait() self.assertEqual(exitcode, 0) else: script_helper.assert_python_ok(tester)
def check_create_from_file(self, ext): testfile = support.findfile('python.' + ext, subdir='imghdrdata') image = tkinter.PhotoImage('::img::test', master=self.root, file=testfile) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'photo') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['data'], '') self.assertEqual(image['file'], testfile) self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names())
def test_reading(self): smbconf = support.findfile("cfgparser.2") # check when we pass a mix of readable and non-readable files: cf = self.newconfig() parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8') self.assertEqual(parsed_files, [smbconf]) sections = ['global', 'homes', 'printers', 'print$', 'pdf-generator', 'tmp', 'Agustin'] self.assertEqual(cf.sections(), sections) self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP") self.assertEqual(cf.getint("global", "max log size"), 50) self.assertEqual(cf.get("global", "hosts allow"), "127.") self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s")
def check_create_from_data(self, ext): testfile = support.findfile("python." + ext, subdir="imghdrdata") with open(testfile, "rb") as f: data = f.read() image = tkinter.PhotoImage("::img::test", master=self.root, data=data) self.assertEqual(str(image), "::img::test") self.assertEqual(image.type(), "photo") self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image["data"], data if self.wantobjects else data.decode("latin1")) self.assertEqual(image["file"], "") self.assertIn("::img::test", self.root.image_names()) del image self.assertNotIn("::img::test", self.root.image_names())
def test_close_opened_files_on_error(self): non_aifc_file = findfile('pluck-pcm8.wav', subdir='audiodata') with check_no_resource_warning(self): with self.assertRaises(aifc.Error): # Try opening a non-AIFC file, with the expectation that # `aifc.open` will fail (without raising a ResourceWarning) self.f = aifc.open(non_aifc_file, 'rb') # Aifc_write.initfp() won't raise in normal case. But some errors # (e.g. MemoryError, KeyboardInterrupt, etc..) can happen. with mock.patch.object(aifc.Aifc_write, 'initfp', side_effect=RuntimeError): with self.assertRaises(RuntimeError): self.fout = aifc.open(TESTFN, 'wb')
def test_data(self): for filename, expected in ( ('sndhdr.8svx', ('8svx', 0, 1, 0, 8)), ('sndhdr.aifc', ('aifc', 44100, 2, 5, 16)), ('sndhdr.aiff', ('aiff', 44100, 2, 5, 16)), ('sndhdr.au', ('au', 44100, 2, 5.0, 16)), ('sndhdr.hcom', ('hcom', 22050.0, 1, -1, 8)), ('sndhdr.sndt', ('sndt', 44100, 1, 5, 8)), ('sndhdr.voc', ('voc', 0, 1, -1, 8)), ('sndhdr.wav', ('wav', 44100, 2, 5, 16)), ): filename = findfile(filename, subdir="sndhdrdata") what = sndhdr.what(filename) self.assertNotEqual(what, None, filename) self.assertSequenceEqual(what, expected)
def test_data(self): for filename, expected in ( ("sndhdr.8svx", ("8svx", 0, 1, 0, 8)), ("sndhdr.aifc", ("aifc", 44100, 2, 5, 16)), ("sndhdr.aiff", ("aiff", 44100, 2, 5, 16)), ("sndhdr.au", ("au", 44100, 2, 5.0, 16)), ("sndhdr.hcom", ("hcom", 22050.0, 1, -1, 8)), ("sndhdr.sndt", ("sndt", 44100, 1, 5, 8)), ("sndhdr.voc", ("voc", 0, 1, -1, 8)), ("sndhdr.wav", ("wav", 44100, 2, -1, 16)), ): filename = findfile(filename, subdir="sndhdrdata") what = sndhdr.what(filename) self.assertNotEqual(what, None, filename) self.assertSequenceEqual(what, expected)
def test_file_buttons(self): """Test buttons that display files.""" dialog = self.dialog button_sources = [(self.dialog.readme, 'README.txt'), (self.dialog.idle_news, 'NEWS.txt'), (self.dialog.idle_credits, 'CREDITS.txt')] for button, filename in button_sources: button.invoke() fn = findfile(filename, subdir='idlelib') get = dialog._current_textview.viewframe.textframe.text.get with open(fn) as f: self.assertEqual(f.readline().strip(), get('1.0', '1.end')) f.readline() self.assertEqual(f.readline().strip(), get('3.0', '3.end')) dialog._current_textview.destroy()
def check_create_from_data(self, ext): testfile = support.findfile('python.' + ext, subdir='imghdrdata') with open(testfile, 'rb') as f: data = f.read() image = tkinter.PhotoImage('::img::test', master=self.root, data=data) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'photo') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['data'], data if self.wantobjects else data.decode('latin1')) self.assertEqual(image['file'], '') self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names())
def test_load_cfg_files(self): conf = self.new_config(_utest=True) # Borrow test/cfgparser.1 from test_configparser. config_path = findfile('cfgparser.1') conf.defaultCfg['foo'] = config.IdleConfParser(config_path) conf.userCfg['foo'] = config.IdleUserConfParser(config_path) # Load all config from path conf.LoadCfgFiles() eq = self.assertEqual # Check defaultCfg is loaded eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo']) # Check userCfg is loaded eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo'])
"""Tests for sys.audit and sys.addaudithook """ import subprocess import sys import unittest from test import support if not hasattr(sys, "addaudithook") or not hasattr(sys, "audit"): raise unittest.SkipTest("test only relevant when sys.audit is available") AUDIT_TESTS_PY = support.findfile("audit-tests.py") class AuditTest(unittest.TestCase): def do_test(self, *args): with subprocess.Popen( [sys.executable, "-X utf8", AUDIT_TESTS_PY, *args], encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) as p: p.wait() sys.stdout.writelines(p.stdout) sys.stderr.writelines(p.stderr) if p.returncode: self.fail("".join(p.stderr)) def run_python(self, *args): events = [] with subprocess.Popen(
filter.startElement("doc", {}) filter.characters("content") filter.ignorableWhitespace(" ") filter.endElement("doc") filter.endDocument() self.assertEqual(result.getvalue(), start + "<doc>content </doc>") # =========================================================================== # # expatreader tests # # =========================================================================== xml_test_out = open(findfile("test.xml.out")).read() class ExpatReaderTest(XmlTestBase): # ===== XMLReader support def test_expat_file(self): parser = create_parser() result = StringIO() xmlgen = XMLGenerator(result) parser.setContentHandler(xmlgen) parser.parse(open(findfile("test.xml"))) self.assertEqual(result.getvalue(), xml_test_out)
def test_pathlike_filename(self): for filename, expected in TEST_FILES: with self.subTest(filename=filename): filename = findfile(filename, subdir='imghdrdata') self.assertEqual(imghdr.what(pathlib.Path(filename)), expected)
def setUp(self): self.f = self.fout = None self.sndfilepath = findfile('Sine-1000Hz-300ms.aif')
import contextlib import os import sys import unittest import warnings from test import support from test.support import os_helper with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) from distutils.core import setup, Extension import distutils.sysconfig MS_WINDOWS = (sys.platform == 'win32') SOURCE = support.findfile('_testcppext.cpp') if not MS_WINDOWS: # C++ compiler flags for GCC and clang CPPFLAGS = [ # Python currently targets C++11 '-std=c++11', # gh-91321: The purpose of _testcppext extension is to check that building # a C++ extension using the Python C API does not emit C++ compiler # warnings '-Werror', # Warn on old-style cast (C cast) like: (PyObject*)op '-Wold-style-cast', # Warn when using NULL rather than _Py_NULL in static inline functions '-Wzero-as-null-pointer-constant', ] else:
# don't try to test this module if we cannot create a parser raise unittest.SkipTest("no XML parsers available") from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \ XMLFilterBase, prepare_input_source from xml.sax.expatreader import create_parser from xml.sax.handler import feature_namespaces from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl from io import BytesIO, StringIO import codecs import gc import os.path import shutil from test import support from test.support import findfile, run_unittest, TESTFN TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata") TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata") try: TEST_XMLFILE.encode("utf-8") TEST_XMLFILE_OUT.encode("utf-8") except UnicodeEncodeError: raise unittest.SkipTest("filename is not encodable to utf8") supports_nonascii_filenames = True if not os.path.supports_unicode_filenames: try: support.TESTFN_UNICODE.encode(support.TESTFN_ENCODING) except (UnicodeError, TypeError): # Either the file system encoding is None, or the file name # cannot be encoded in the file system encoding. supports_nonascii_filenames = False
import unittest from test import support import os import sys import subprocess SYMBOL_FILE = support.findfile('symbol.py') GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), '..', '..', 'Include', 'graminit.h') TEST_PY_FILE = 'symbol_test.py' class TestSymbolGeneration(unittest.TestCase): def _copy_file_without_generated_symbols(self, source_file, dest_file): with open(source_file) as fp: lines = fp.readlines() with open(dest_file, 'w') as fp: fp.writelines(lines[:lines.index("#--start constants--\n") + 1]) fp.writelines(lines[lines.index("#--end constants--\n"):]) def _generate_symbols(self, grammar_file, target_symbol_py_file): proc = subprocess.Popen( [sys.executable, SYMBOL_FILE, grammar_file, target_symbol_py_file], stderr=subprocess.PIPE) stderr = proc.communicate()[1] return proc.returncode, stderr def compare_files(self, file1, file2): with open(file1) as fp: lines1 = fp.readlines() with open(file2) as fp:
import io import unittest import sys import xml.sax from xml.sax.xmlreader import AttributesImpl from xml.dom import pulldom from test.support import findfile tstfile = findfile("test.xml", subdir="xmltestdata") # A handy XML snippet, containing attributes, a namespace prefix, and a # self-closing tag: SMALL_SAMPLE = """<?xml version="1.0"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xdc="http://www.xml.com/books"> <!-- A comment --> <title>Introduction to XSL</title> <hr/> <p><xdc:author xdc:attrib="prefixed attribute" attrib="other attrib">A. Namespace</xdc:author></p> </html>""" class PullDOMTestCase(unittest.TestCase): def test_parse(self): """Minimal test of DOMEventStream.parse()""" # This just tests that parsing from a stream works. Actual parser # semantics are tested using parseString with a more focused XML # fragment.
def test_playback(self): sound_info = read_sound_file(findfile('audiotest.au')) self.play_sound_file(*sound_info)
def test_pickleable(self): filename = findfile('sndhdr.aifc', subdir="sndhdrdata") what = sndhdr.what(filename) for proto in range(pickle.HIGHEST_PROTOCOL + 1): dump = pickle.dumps(what, proto) self.assertEqual(pickle.loads(dump), what)
def test_command_usage(self): """Should display usage on no arguments.""" path = findfile('tabnanny.py') stderr = f"Usage: {path} [-v] file_or_directory ..." self.validate_cmd(stderr=stderr)
def test_skipunknown(self): #Issue 2245 #This file contains chunk types aifc doesn't recognize. self.f = aifc.open(findfile('Sine-1000Hz-300ms.aif'))
def setUpClass(cls): AbstractTkTest.setUpClass.__func__(cls) cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')
import cosmo import keyword import unittest from test import support import filecmp import os import sys import subprocess import shutil import textwrap KEYWORD_FILE = support.findfile('keyword.py') GRAMMAR_FILE = os.path.join(os.path.split(__file__)[0], '..', '..', 'Python', 'graminit.c') TEST_PY_FILE = 'keyword_test.py' GRAMMAR_TEST_FILE = 'graminit_test.c' PY_FILE_WITHOUT_KEYWORDS = 'minimal_keyword.py' NONEXISTENT_FILE = 'not_here.txt' class Test_iskeyword(unittest.TestCase): def test_true_is_a_keyword(self): self.assertTrue(keyword.iskeyword('True')) def test_uppercase_true_is_not_a_keyword(self): self.assertFalse(keyword.iskeyword('TRUE')) def test_none_value_is_not_a_keyword(self): self.assertFalse(keyword.iskeyword(None)) # This is probably an accident of the current implementation, but should be
def abspath(filename): return os.path.abspath(findfile(filename, subdir="dtracedata"))
def setUp(self): stats_file = support.findfile('pstats.pck') self.stats = pstats.Stats(stats_file)
# gh-91321: Build a basic C++ test extension to check that the Python C API is # compatible with C++ and does not emit C++ compiler warnings. import os.path import sys import unittest import subprocess from test import support from test.support import os_helper MS_WINDOWS = (sys.platform == 'win32') SETUP_TESTCPPEXT = support.findfile('setup_testcppext.py') @support.requires_subprocess() class TestCPPExt(unittest.TestCase): # With MSVC, the linker fails with: cannot open file 'python311.lib' # https://github.com/python/cpython/pull/32175#issuecomment-1111175897 @unittest.skipIf(MS_WINDOWS, 'test fails on Windows') def test_build(self): # Build in a temporary directory with os_helper.temp_cwd(): self._test_build() def _test_build(self): venv_dir = 'env' # Create virtual environment to get setuptools cmd = [sys.executable, '-X', 'dev', '-m', 'venv', venv_dir]
def test_general(self): # Run _test_atexit.py in a subprocess since it calls atexit._clear() script = support.findfile("_test_atexit.py") script_helper.run_test_script(script)
def get_sample_script(self): return findfile('gdb_sample.py')
def setUpClass(cls): cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')
def test_snd_filename(self): fn = support.findfile('pluck-pcm8.wav', subdir='audiodata') safe_PlaySound(fn, winsound.SND_FILENAME | winsound.SND_NODEFAULT)
def setUpClass(cls): cls.testfile = findfile('python.png', subdir='imghdrdata') with open(cls.testfile, 'rb') as stream: cls.testdata = stream.read()
import gzip gzip.GzipFile except (ImportError, AttributeError): gzip = None try: import bz2 except ImportError: bz2 = None def md5sum(data): return md5(data).hexdigest() TEMPDIR = os.path.abspath(support.TESTFN) tarname = support.findfile("testtar.tar") gzipname = os.path.join(TEMPDIR, "testtar.tar.gz") bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2") tmpname = os.path.join(TEMPDIR, "tmp.tar") md5_regtype = "65f477c818ad9e15f7feab0c6d37742f" md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6" class ReadTest(unittest.TestCase): tarname = tarname mode = "r:" def setUp(self): self.tar = tarfile.open(self.tarname,
def test_all(self): # Run the tester in a sub-process, to make sure there is only one # thread (for reliable signal delivery). tester = support.findfile("eintr_tester.py", subdir="eintrdata") # use -u to try to get the full output if the test hangs or crash script_helper.assert_python_ok("-u", tester)
def test_pickleable(self): filename = findfile('sndhdr.aifc', subdir="sndhdrdata") what = sndhdr.what(filename) dump = pickle.dumps(what) self.assertEqual(pickle.loads(dump), what)
def path(path): return support.findfile(path)
def testExtractDir(self): zipf = zipfile.ZipFile(findfile("zipdir.zip")) zipf.extractall(TESTFN2) self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a"))) self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b"))) self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
def test_import_star(self): self.assertEqual( subprocess.call( [sys.executable, support.findfile("import_star_from_java.py")]), 0)
def setUpClass(cls): cls.sndfilepath = findfile(cls.sndfilename, subdir='audiodata')
def test_skipunknown(self): self.f = aifc.open(findfile('Sine-1000Hz-300ms.aif'))