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_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 two lines to baseline this test #with open('test_difflib_expect.html','w') as fp: # fp.write(actual) with open(findfile('test_difflib_expect.html')) as fp: self.assertEqual(actual, fp.read())
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_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_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 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_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 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_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') with open(fn) as f: self.assertEqual( f.readline().strip(), dialog._current_textview.text.get('1.0', '1.end')) f.readline() self.assertEqual( f.readline().strip(), dialog._current_textview.text.get('3.0', '3.end')) dialog._current_textview.destroy()
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) self.assertEqual(what.filetype, expected[0]) self.assertEqual(what.framerate, expected[1]) self.assertEqual(what.nchannels, expected[2]) self.assertEqual(what.nframes, expected[3]) self.assertEqual(what.sampwidth, expected[4])
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 get_sample_script(self): return findfile('gdb_sample.py')
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 abspath(filename): return os.path.abspath(findfile(filename, subdir="dtracedata"))
def setUpClass(cls): cls.sndfilepath = findfile(cls.sndfilename, subdir='audiodata')
import unittest from sql_mode 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:
def test_reindent_file_with_bad_encoding(self): bad_coding_path = findfile('bad_coding.py') rc, out, err = assert_python_ok(self.script, '-r', bad_coding_path) self.assertEqual(out, b'') self.assertNotEqual(err, b'')
def test_snd_filename(self): fn = support.findfile('pluck-pcm8.wav', subdir='audiodata') safe_PlaySound(fn, winsound.SND_FILENAME | winsound.SND_NODEFAULT)
# 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 sql_mode import support from sql_mode.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
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 test_playback(self): sound_info = read_sound_file(findfile('audiotest.au')) self.play_sound_file(*sound_info)
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)
import io import unittest import xml.sax from xml.sax.xmlreader import AttributesImpl from xml.dom import pulldom from sql_mode.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. # Test with a filename:
def setUp(self): stats_file = support.findfile('pstats.pck') self.stats = pstats.Stats(stats_file)
def setUpClass(cls): AbstractTkTest.setUpClass.__func__(cls) cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')
def setUpClass(cls): cls.testfile = findfile('python.png', subdir='imghdrdata') with open(cls.testfile, 'rb') as stream: cls.testdata = stream.read()
import keyword import unittest from sql_mode 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 # preserved for backward compatibility.