def testThreads(self): # BufferedWriter should not raise exceptions or crash # when called from multiple threads. try: # We use a real file object because it allows us to # exercise situations where the GIL is released before # writing the buffer to the raw streams. This is in addition # to concurrency issues due to switching threads in the middle # of Python code. with io.open(test_support.TESTFN, "wb", buffering=0) as raw: bufio = io.BufferedWriter(raw, 8) errors = [] def f(): try: # Write enough bytes to flush the buffer s = b"a" * 19 for i in range(50): bufio.write(s) except Exception as e: errors.append(e) raise threads = [threading.Thread(target=f) for x in range(20)] for t in threads: t.start() time.sleep(0.02) # yield for t in threads: t.join() self.assertFalse(errors, "the following exceptions were caught: %r" % errors) finally: test_support.unlink(test_support.TESTFN)
def test_realpath_resolve_before_normalizing(self): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' # in the following hierarchy: # a/k/y # # and a symbolic link 'link-y' pointing to 'y' in directory 'a', # then realpath("link-y/..") should return 'k', not 'a'. try: os.mkdir(ABSTFN) os.mkdir(ABSTFN + "/k") os.mkdir(ABSTFN + "/k/y") os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y") # Absolute path. self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k") # Relative path. with support.change_cwd(dirname(ABSTFN)): self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k") finally: test_support.unlink(ABSTFN + "/link-y") safe_rmdir(ABSTFN + "/k/y") safe_rmdir(ABSTFN + "/k") safe_rmdir(ABSTFN)
def test_realpath_basic(self): # Basic operation. try: os.symlink(ABSTFN+"1", ABSTFN) self.assertEqual(realpath(ABSTFN), ABSTFN+"1") finally: test_support.unlink(ABSTFN)
def test_tofromfile(self): a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) self.assertRaises(TypeError, a.tofile, cStringIO.StringIO()) test_support.unlink(test_support.TESTFN) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) f.close() b = array.array(self.typecode) f = open(test_support.TESTFN, 'rb') self.assertRaises(TypeError, b.fromfile) self.assertRaises( TypeError, b.fromfile, cStringIO.StringIO(), len(self.example) ) b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) self.assertRaises(EOFError, b.fromfile, f, 1) f.close() finally: if not f.closed: f.close() test_support.unlink(test_support.TESTFN)
def try_one(self, s): # Write s + "\n" + s to file, then open it and ensure that successive # .readline()s deliver what we wrote. # Ensure we can open TESTFN for writing. support.unlink(support.TESTFN) # Since C doesn't guarantee we can write/read arbitrary bytes in text # files, use binary mode. f = self.open(support.TESTFN, "wb") try: # write once with \n and once without f.write(s) f.write(b"\n") f.write(s) f.close() f = open(support.TESTFN, "rb") line = f.readline() self.assertEqual(line, s + b"\n") line = f.readline() self.assertEqual(line, s) line = f.readline() self.assertTrue(not line) # Must be at EOF f.close() finally: support.unlink(support.TESTFN)
def remove_files(name): for f in (name + os.extsep + "py", name + os.extsep + "pyc", name + os.extsep + "pyo", name + os.extsep + "pyw", name + "$py.class"): unlink(f)
def test_execfile(self): globals = {'a': 1, 'b': 2} locals = {'b': 200, 'c': 300} class M: "Test mapping interface versus possible calls from execfile()." def __init__(self): self.z = 10 def __getitem__(self, key): if key == 'z': return self.z raise KeyError def __setitem__(self, key, value): if key == 'z': self.z = value return raise KeyError locals = M() locals['z'] = 0 execfile(TESTFN, globals, locals) self.assertEqual(locals['z'], 2) self.assertRaises(TypeError, execfile) self.assertRaises(TypeError, execfile, TESTFN, {}, ()) unlink(TESTFN)
def test_encode(self): fin = fout = None try: test_support.unlink(self.tmpin) fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def test_builtin_list(self): self.assertEqual(list(SequenceClass(5)), range(5)) self.assertEqual(list(SequenceClass(0)), []) self.assertEqual(list(()), []) self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1)) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(list(d), d.keys()) self.assertRaises(TypeError, list, list) self.assertRaises(TypeError, list, 42) f = open(TESTFN, "w") try: for i in range(5): f.write("%d\n" % i) finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"]) f.seek(0, 0) self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"]) finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_rewrite_pyc_with_read_only_source(self): # Issue 6074: a long time ago on posix, and more recently on Windows, # a read only source file resulted in a read only pyc file, which # led to problems with updating it later sys.path.insert(0, os.curdir) fname = TESTFN + os.extsep + "py" try: # Write a Python file, make it read-only and import it with open(fname, 'w') as f: f.write("x = 'original'\n") # Tweak the mtime of the source to ensure pyc gets updated later s = os.stat(fname) os.utime(fname, (s.st_atime, s.st_mtime-100000000)) os.chmod(fname, 0400) m1 = __import__(TESTFN) self.assertEqual(m1.x, 'original') # Change the file and then reimport it os.chmod(fname, 0600) with open(fname, 'w') as f: f.write("x = 'rewritten'\n") unload(TESTFN) m2 = __import__(TESTFN) self.assertEqual(m2.x, 'rewritten') # Now delete the source file and check the pyc was rewritten if check_impl_detail(pypy=False): unlink(fname) unload(TESTFN) m3 = __import__(TESTFN) self.assertEqual(m3.x, 'rewritten') finally: chmod_files(TESTFN) remove_files(TESTFN) unload(TESTFN) del sys.path[0]
def test_builtin_max_min(self): self.assertEqual(max(SequenceClass(5)), 4) self.assertEqual(min(SequenceClass(5)), 0) self.assertEqual(max(8, -1), 8) self.assertEqual(min(8, -1), -1) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(max(d), "two") self.assertEqual(min(d), "one") self.assertEqual(max(d.itervalues()), 3) self.assertEqual(min(iter(d.itervalues())), 1) f = open(TESTFN, "w") try: f.write("medium line\n") f.write("xtra large line\n") f.write("itty-bitty line\n") finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(min(f), "itty-bitty line\n") f.seek(0, 0) self.assertEqual(max(f), "xtra large line\n") finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_builtin_tuple(self): self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4)) self.assertEqual(tuple(SequenceClass(0)), ()) self.assertEqual(tuple([]), ()) self.assertEqual(tuple(()), ()) self.assertEqual(tuple("abc"), ("a", "b", "c")) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(tuple(d), tuple(d.keys())) self.assertRaises(TypeError, tuple, list) self.assertRaises(TypeError, tuple, 42) f = open(TESTFN, "w") try: for i in range(5): f.write("%d\n" % i) finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n")) f.seek(0, 0) self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n")) finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_countOf(self): from operator import countOf self.assertEqual(countOf([1,2,2,3,2,5], 2), 3) self.assertEqual(countOf((1,2,2,3,2,5), 2), 3) self.assertEqual(countOf("122325", "2"), 3) self.assertEqual(countOf("122325", "6"), 0) self.assertRaises(TypeError, countOf, 42, 1) self.assertRaises(TypeError, countOf, countOf, countOf) d = {"one": 3, "two": 3, "three": 3, 1j: 2j} for k in d: self.assertEqual(countOf(d, k), 1) self.assertEqual(countOf(d.itervalues(), 3), 3) self.assertEqual(countOf(d.itervalues(), 2j), 1) self.assertEqual(countOf(d.itervalues(), 1j), 0) f = open(TESTFN, "w") try: f.write("a\n" "b\n" "c\n" "b\n") finally: f.close() f = open(TESTFN, "r") try: for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0): f.seek(0, 0) self.assertEqual(countOf(f, letter + "\n"), count) finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_builtin_map(self): self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items()) dkeys = d.keys() expected = [(i < len(d) and dkeys[i] or None, i, i < len(d) and dkeys[i] or None) for i in range(5)] # Deprecated map(None, ...) with check_py3k_warnings(): self.assertEqual(map(None, SequenceClass(5)), range(5)) self.assertEqual(map(None, d), d.keys()) self.assertEqual(map(None, d, SequenceClass(5), iter(d.iterkeys())), expected) f = open(TESTFN, "w") try: for i in range(10): f.write("xy" * i + "\n") # line i has len 2*i+1 finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(map(len, f), range(1, 21, 2)) finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_add_EvalPyFilter_withCode(self): pyCodeFile = 'pyCode.py' pyCode = """# Will filter all messages having 'hello world' in their content if routable.pdu.params['short_message'] == 'hello world': result = True else: result = False """ # Create an pyCode file with open(pyCodeFile, 'w') as f: f.write(pyCode) ftype = 'EvalPyFilter' _str_ = ['%s:' % ftype] _str_.extend([y for y in (re.escape(x.strip()) for x in pyCode.splitlines()) if y]) _repr_ = '<Ev \(pyCode=%s ..\)>' % (pyCode[:10].replace('\n', '')) # Add filter extraCommands = [{'command': 'fid filter_id'}, {'command': 'type %s' % ftype}, {'command': 'pyCode %s' % pyCodeFile},] self.add_filter(r'jcli : ', extraCommands) # Make asserts expectedList = _str_ self._test('jcli : ', [{'command': 'filter -s filter_id', 'expect': expectedList}]) expectedList = ['#Filter id Type Routes Description', '#filter_id %s MO MT %s' % (ftype, _repr_), 'Total Filters: 1'] self._test('jcli : ', [{'command': 'filter -l', 'expect': expectedList}]) # Delete pyCode file unlink(pyCodeFile)
def test_EvalPyFilter(self): pyCodeFile = 'pyCode.py' # Create an empty pyCode file open(pyCodeFile, 'w') ftype = 'EvalPyFilter' _str_ = ['%s:' % ftype, ''] _repr_ = '<Ev \(pyCode= ..\)>' # Add filter extraCommands = [{'command': 'fid filter_id'}, {'command': 'type %s' % ftype}, {'command': 'pyCode %s' % pyCodeFile},] self.add_filter(r'jcli : ', extraCommands) # Persist & load self._test('jcli : ', [{'command': 'persist'}, {'command': 'filter -r filter_id'}, {'command': 'load'}]) # Make asserts expectedList = _str_ self._test('jcli : ', [{'command': 'filter -s filter_id', 'expect': expectedList}]) expectedList = ['#Filter id Type Routes Description', '#filter_id %s MO MT %s' % (ftype, _repr_), 'Total Filters: 1'] self._test('jcli : ', [{'command': 'filter -l', 'expect': expectedList}]) # Delete pyCode file unlink(pyCodeFile)
def _testBogusZipFile(self): test_support.unlink(TESTMOD) fp = open(TESTMOD, 'w+') fp.write(struct.pack('=I', 0x06054B50)) fp.write('a' * 18) fp.close() z = zipimport.zipimporter(TESTMOD) try: self.assertRaises(TypeError, z.find_module, None) self.assertRaises(TypeError, z.load_module, None) self.assertRaises(TypeError, z.is_package, None) self.assertRaises(TypeError, z.get_code, None) self.assertRaises(TypeError, z.get_data, None) self.assertRaises(TypeError, z.get_source, None) error = zipimport.ZipImportError self.assertEqual(z.find_module('abc'), None) self.assertRaises(error, z.load_module, 'abc') self.assertRaises(error, z.get_code, 'abc') self.assertRaises(IOError, z.get_data, 'abc') self.assertRaises(error, z.get_source, 'abc') self.assertRaises(error, z.is_package, 'abc') finally: zipimport._zip_directory_cache.clear()
def suite(): try: # this is special, it used to segfault the interpreter import bsddb.test.test_1413192 except: for f in ['__db.001', '__db.002', '__db.003', 'log.0000000001']: unlink(f) test_modules = [ 'test_associate', 'test_basics', 'test_compat', 'test_dbobj', 'test_dbshelve', 'test_dbtables', 'test_env_close', 'test_get_none', 'test_join', 'test_lock', 'test_misc', 'test_queue', 'test_recno', 'test_thread', 'test_sequence', 'test_cursor_pget_bug', ] alltests = unittest.TestSuite() for name in test_modules: module = __import__("bsddb.test."+name, globals(), locals(), name) #print module,name alltests.addTest(module.test_suite()) return alltests
def tearDown(self): for db in self._db: db.close() self._db = [] if not self._in_mem: for f in glob.glob(self.fn+"*"): test_support.unlink(f)
def test_tofromfile(self): if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=313708"): return a = array.array(self.typecode, 2*self.example) self.assertRaises(TypeError, a.tofile) self.assertRaises(TypeError, a.tofile, cStringIO.StringIO()) test_support.unlink(test_support.TESTFN) f = open(test_support.TESTFN, 'wb') try: a.tofile(f) f.close() b = array.array(self.typecode) f = open(test_support.TESTFN, 'rb') self.assertRaises(TypeError, b.fromfile) self.assertRaises( TypeError, b.fromfile, cStringIO.StringIO(), len(self.example) ) b.fromfile(f, len(self.example)) self.assertEqual(b, array.array(self.typecode, self.example)) self.assertNotEqual(a, b) b.fromfile(f, len(self.example)) self.assertEqual(a, b) self.assertRaises(EOFError, b.fromfile, f, 1) f.close() finally: if not f.closed: f.close() test_support.unlink(test_support.TESTFN)
def test_write_long_to_file(self): for v in range(marshal.version + 1): _testcapi.pymarshal_write_long_to_file(0x12345678, test_support.TESTFN, v) with open(test_support.TESTFN, 'rb') as f: data = f.read() test_support.unlink(test_support.TESTFN) self.assertEqual(data, b'\x78\x56\x34\x12')
def test_read_short_from_file(self): with open(test_support.TESTFN, "wb") as f: f.write(b"\x34\x12xxxx") r, p = _testcapi.pymarshal_read_short_from_file(test_support.TESTFN) test_support.unlink(test_support.TESTFN) self.assertEqual(r, 0x1234) self.assertEqual(p, 2)
def test_read_long_from_file(self): with open(test_support.TESTFN, 'wb') as f: f.write(b'\x78\x56\x34\x12xxxx') r, p = _testcapi.pymarshal_read_long_from_file(test_support.TESTFN) test_support.unlink(test_support.TESTFN) self.assertEqual(r, 0x12345678) self.assertEqual(p, 4)
def test_input_and_raw_input(self): self.write_testfile() fp = open(TESTFN, 'r') savestdin = sys.stdin savestdout = sys.stdout # Eats the echo try: sys.stdin = fp sys.stdout = BitBucket() self.assertEqual(input(), 2) self.assertEqual(input('testing\n'), 2) self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') self.assertEqual(raw_input('testing\n'), 'Dear John') sys.stdin = cStringIO.StringIO("NULL\0") self.assertRaises(TypeError, input, 42, 42) sys.stdin = cStringIO.StringIO(" 'whitespace'") self.assertEqual(input(), 'whitespace') sys.stdin = cStringIO.StringIO() self.assertRaises(EOFError, input) del sys.stdout self.assertRaises(RuntimeError, input, 'prompt') del sys.stdin self.assertRaises(RuntimeError, input, 'prompt') finally: sys.stdin = savestdin sys.stdout = savestdout fp.close() unlink(TESTFN)
def test_parse_file(self): # Try parsing a file out = self.Outputter() parser = expat.ParserCreate(namespace_separator='!') parser.returns_unicode = 1 for name in self.handler_names: setattr(parser, name, getattr(out, name)) file = StringIO.StringIO(data) parser.ParseFile(file) op = out.out # https://github.com/IronLanguages/ironpython2/issues/464 if sys.platform == 'cli': self.assertEqual(op[0], 'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'') self.assertEqual(op[1], "Comment: ' comment data '") #self.assertEqual(op[2], "Notation declared: ('notation', None, 'notation.jpeg', None)") #self.assertEqual(op[3], "Unparsed entity decl: ('unparsed_entity', None, 'entity.file', None, 'notation')") self.assertEqual(op[2], "Start element: 'root' {'attr1': 'value1', 'attr2': u'value2\\u1f40'}") self.assertEqual(op[3], "NS decl: 'myns' 'http://www.python.org/namespace'") self.assertEqual(op[4], "Start element: 'http://www.python.org/namespace!subelement' {}") self.assertEqual(op[5], "Character data: 'Contents of subelements'") self.assertEqual(op[6], "End element: 'http://www.python.org/namespace!subelement'") self.assertEqual(op[7], "End of NS decl: 'myns'") self.assertEqual(op[8], "Start element: 'sub2' {}") self.assertEqual(op[9], 'Start of CDATA section') self.assertEqual(op[10], "Character data: 'contents of CDATA section'") self.assertEqual(op[11], 'End of CDATA section') self.assertEqual(op[12], "End element: 'sub2'") #self.assertEqual(op[13], "External entity ref: (None, 'entity.file', None)") self.assertEqual(op[13], "End element: 'root'") else: self.assertEqual(op[0], 'PI: u\'xml-stylesheet\' u\'href="stylesheet.css"\'') self.assertEqual(op[1], "Comment: u' comment data '") self.assertEqual(op[2], "Notation declared: (u'notation', None, u'notation.jpeg', None)") self.assertEqual(op[3], "Unparsed entity decl: (u'unparsed_entity', None, u'entity.file', None, u'notation')") self.assertEqual(op[4], "Start element: u'root' {u'attr1': u'value1', u'attr2': u'value2\\u1f40'}") self.assertEqual(op[5], "NS decl: u'myns' u'http://www.python.org/namespace'") self.assertEqual(op[6], "Start element: u'http://www.python.org/namespace!subelement' {}") self.assertEqual(op[7], "Character data: u'Contents of subelements'") self.assertEqual(op[8], "End element: u'http://www.python.org/namespace!subelement'") self.assertEqual(op[9], "End of NS decl: u'myns'") self.assertEqual(op[10], "Start element: u'sub2' {}") self.assertEqual(op[11], 'Start of CDATA section') self.assertEqual(op[12], "Character data: u'contents of CDATA section'") self.assertEqual(op[13], 'End of CDATA section') self.assertEqual(op[14], "End element: u'sub2'") self.assertEqual(op[15], "External entity ref: (None, u'entity.file', None)") self.assertEqual(op[16], "End element: u'root'") # Issue 4877: expat.ParseFile causes segfault on a closed file. fp = open(test_support.TESTFN, 'wb') try: fp.close() parser = expat.ParserCreate() with self.assertRaises(ValueError): parser.ParseFile(fp) finally: test_support.unlink(test_support.TESTFN)
def test_no_ending_newline(self): try: with open(support.TESTFN, "w") as fp: fp.write(SOURCE_3) lines = linecache.getlines(support.TESTFN) self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) finally: support.unlink(support.TESTFN)
def test_write_object_to_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000) for v in range(marshal.version + 1): _testcapi.pymarshal_write_object_to_file(obj, test_support.TESTFN, v) with open(test_support.TESTFN, 'rb') as f: data = f.read() test_support.unlink(test_support.TESTFN) self.assertEqual(marshal.loads(data), obj)
def tearDown(self): sys.path[:] = self.sys_path if self.orig_module is not None: sys.modules[self.module_name] = self.orig_module else: unload(self.module_name) unlink(self.file_name) unlink(self.compiled_name) rmtree(self.dir_name)
def test_main(): try: test_support.run_unittest( UncompressedZipImportTestCase, CompressedZipImportTestCase, BadFileZipImportTestCase, ) finally: test_support.unlink(TESTMOD)
def test_read_last_object_from_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) for v in range(marshal.version + 1): data = marshal.dumps(obj, v) with open(test_support.TESTFN, 'wb') as f: f.write(data + b'xxxx') r, p = _testcapi.pymarshal_read_last_object_from_file(test_support.TESTFN) test_support.unlink(test_support.TESTFN) self.assertEqual(r, obj)
def tearDown(self): if self.f and not self.f.closed: self.f.close() unlink(TESTFN)
a = random.randrange(1000) b = random.randrange(1000) print >> f, "a =", a print >> f, "b =", b try: mod = __import__(TESTFN) except ImportError, err: self.fail("import from %s failed: %s" % (ext, err)) else: self.assertEqual(mod.a, a, "module loaded (%s) but contents invalid" % mod) self.assertEqual(mod.b, b, "module loaded (%s) but contents invalid" % mod) finally: unlink(source) try: if not sys.dont_write_bytecode: imp.reload(mod) except ImportError, err: self.fail("import from .pyc/.pyo failed: %s" % err) finally: unlink(pyc) unlink(pyo) unload(TESTFN) sys.path.insert(0, os.curdir) try: test_with_extension(os.extsep + "py") if sys.platform.startswith("win"):
def remove_files(name): for f in _files(name): unlink(f)
def test_copy(self): test_support.unlink(TESTFN2) macostools.copy(test_support.TESTFN, TESTFN2) self.assertEqual(self.compareData(), '')
def test_mkalias(self): test_support.unlink(TESTFN2) macostools.mkalias(test_support.TESTFN, TESTFN2) fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN))
def test_EvalPyFilter_withCode(self): pyCodeFile = 'pyCode.py' pyCode = """# Will filter all messages having 'hello world' in their content if routable.pdu.params['short_message'] == 'hello world': result = True else: result = False """ # Create an pyCode file with open(pyCodeFile, 'w') as f: f.write(pyCode) ftype = 'EvalPyFilter' _str_ = ['%s:' % ftype] _str_.extend([ y for y in (re.escape(x.strip()) for x in pyCode.splitlines()) if y ]) _repr_ = '<%s \(pyCode=%s ..\)>' % (ftype, pyCode[:10].replace( '\n', '')) # Add filter extraCommands = [ { 'command': 'fid filter_id' }, { 'command': 'type %s' % ftype }, { 'command': 'pyCode %s' % pyCodeFile }, ] self.add_filter(r'jcli : ', extraCommands) # Persist & load self._test('jcli : ', [{ 'command': 'persist' }, { 'command': 'filter -r filter_id' }, { 'command': 'load' }]) # Make asserts expectedList = _str_ self._test('jcli : ', [{ 'command': 'filter -s filter_id', 'expect': expectedList }]) expectedList = [ '#Filter id Type Routes Description', '#filter_id %s MO MT %s' % (ftype, _repr_), 'Total Filters: 1' ] self._test('jcli : ', [{ 'command': 'filter -l', 'expect': expectedList }]) # Delete pyCode file unlink(pyCodeFile)
def tearDown(self): if self.f is not None: self.f.close() if self.fout is not None: self.fout.close() unlink(TESTFN)
def tearDown(self): support.unlink(self.file)
def close(self, f): f.close() test_support.unlink(test_support.TESTFN)
def tearDown(self): for f in (TESTFN, TESTFN2): unlink(f)
def tearDown(self): for sep, fn in self.arcfiles.items(): os.remove(fn) support.unlink(TESTFN) support.unlink(TESTFN2)
def tearDown(self): support.unlink(TESTFN) support.unlink(TESTFN2)
def tearDown(self): test_support.unlink(self.filename)
def tearDown(self): unlink(TESTFN)
def tearDown(self): if self.g is not None: self.g.close() unlink(filename)
def testRaising(self): self.raise_catch(AttributeError, "AttributeError") self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") self.raise_catch(EOFError, "EOFError") fp = open(TESTFN, 'w') fp.close() fp = open(TESTFN, 'r') savestdin = sys.stdin try: try: sys.stdin = fp x = raw_input() except EOFError: pass finally: sys.stdin = savestdin fp.close() unlink(TESTFN) self.raise_catch(IOError, "IOError") self.assertRaises(IOError, open, 'this file does not exist', 'r') self.raise_catch(ImportError, "ImportError") self.assertRaises(ImportError, __import__, "undefined_module") self.raise_catch(IndexError, "IndexError") x = [] self.assertRaises(IndexError, x.__getitem__, 10) self.raise_catch(KeyError, "KeyError") x = {} self.assertRaises(KeyError, x.__getitem__, 'key') self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") self.raise_catch(MemoryError, "MemoryError") self.raise_catch(NameError, "NameError") try: x = undefined_variable except NameError: pass self.raise_catch(OverflowError, "OverflowError") x = 1 for dummy in range(128): x += x # this simply shouldn't blow up self.raise_catch(RuntimeError, "RuntimeError") self.raise_catch(SyntaxError, "SyntaxError") try: exec '/\n' except SyntaxError: pass self.raise_catch(IndentationError, "IndentationError") self.raise_catch(TabError, "TabError") # can only be tested under -tt, and is the only test for -tt #try: compile("try:\n\t1.0/0.0\n \t1.0/0.0\nfinally:\n pass\n", '<string>', 'exec') #except TabError: pass #else: self.fail("TabError not raised") self.raise_catch(SystemError, "SystemError") self.raise_catch(SystemExit, "SystemExit") self.assertRaises(SystemExit, sys.exit, 0) self.raise_catch(TypeError, "TypeError") try: [] + () except TypeError: pass self.raise_catch(ValueError, "ValueError") self.assertRaises(ValueError, chr, 10000) self.raise_catch(ZeroDivisionError, "ZeroDivisionError") try: x = 1 // 0 except ZeroDivisionError: pass self.raise_catch(Exception, "Exception") try: x = 1 // 0 except Exception, e: pass
def tearDown(self): test_support.unlink(TESTFN) test_support.unlink(TESTFN2)
def testNotZipFile(self): test_support.unlink(TESTMOD) fp = open(TESTMOD, 'w+') fp.write('a' * 22) fp.close() self.assertZipFailure(TESTMOD)
def testEmptyFile(self): test_support.unlink(TESTMOD) open(TESTMOD, 'w+').close() self.assertZipFailure(TESTMOD)
def setUp(self): if os.path.exists(TESTFN): unlink(TESTFN)
def tearDown(self): for suffix in ["", "1", "2"]: test_support.unlink(test_support.TESTFN + suffix) safe_rmdir(test_support.TESTFN + suffix)
if verbose: print "uudecoding", source, "->", target, "..." uu.decode(source, target) if verbose: print "testing..." ttob = rgbimg.ttob(0) if ttob != 0: raise error, 'ttob should start out as zero' testimg('test' + os.extsep + 'rgb', 'test' + os.extsep + 'rawimg') ttob = rgbimg.ttob(1) if ttob != 0: raise error, 'ttob should be zero' testimg('test' + os.extsep + 'rgb', 'test' + os.extsep + 'rawimg' + os.extsep + 'rev') ttob = rgbimg.ttob(0) if ttob != 1: raise error, 'ttob should be one' ttob = rgbimg.ttob(0) if ttob != 0: raise error, 'ttob should be zero' for source, target in table: unlink(findfile(target))
def setUp(self): unlink(TESTFN)
def test_builtin_zip(self): self.assertEqual(zip(), []) self.assertEqual(zip(*[]), []) self.assertEqual(zip(*[(1, 2), 'ab']), [(1, 'a'), (2, 'b')]) self.assertRaises(TypeError, zip, None) self.assertRaises(TypeError, zip, range(10), 42) self.assertRaises(TypeError, zip, range(10), zip) self.assertEqual(zip(IteratingSequenceClass(3)), [(0, ), (1, ), (2, )]) self.assertEqual(zip(SequenceClass(3)), [(0, ), (1, ), (2, )]) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(d.items(), zip(d, d.itervalues())) # Generate all ints starting at constructor arg. class IntsFrom: def __init__(self, start): self.i = start def __iter__(self): return self def next(self): i = self.i self.i = i + 1 return i f = open(TESTFN, "w") try: f.write("a\n" "bbb\n" "cc\n") finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(zip(IntsFrom(0), f, IntsFrom(-100)), [(0, "a\n", -100), (1, "bbb\n", -99), (2, "cc\n", -98)]) finally: f.close() try: unlink(TESTFN) except OSError: pass self.assertEqual(zip(xrange(5)), [(i, ) for i in range(5)]) # Classes that lie about their lengths. class NoGuessLen5: def __getitem__(self, i): if i >= 5: raise IndexError return i class Guess3Len5(NoGuessLen5): def __len__(self): return 3 class Guess30Len5(NoGuessLen5): def __len__(self): return 30 self.assertEqual(len(Guess3Len5()), 3) self.assertEqual(len(Guess30Len5()), 30) self.assertEqual(zip(NoGuessLen5()), zip(range(5))) self.assertEqual(zip(Guess3Len5()), zip(range(5))) self.assertEqual(zip(Guess30Len5()), zip(range(5))) expected = [(i, i) for i in range(5)] for x in NoGuessLen5(), Guess3Len5(), Guess30Len5(): for y in NoGuessLen5(), Guess3Len5(), Guess30Len5(): self.assertEqual(zip(x, y), expected)
def tearDown(self): rmtree(TESTFN) unlink(TESTFN)
def test_main(): run_unittest(InputValidationTests) try: import imgfile except ImportError: return # Create binary test files uu.decode(get_qualified_path('testrgb' + os.extsep + 'uue'), 'test' + os.extsep + 'rgb') image, width, height = getimage('test' + os.extsep + 'rgb') # Return the selected part of image, which should by width by height # in size and consist of pixels of psize bytes. if verbose: print 'crop' newimage = imageop.crop(image, 4, width, height, 0, 0, 1, 1) # Return image scaled to size newwidth by newheight. No interpolation # is done, scaling is done by simple-minded pixel duplication or removal. # Therefore, computer-generated images or dithered images will # not look nice after scaling. if verbose: print 'scale' scaleimage = imageop.scale(image, 4, width, height, 1, 1) # Run a vertical low-pass filter over an image. It does so by computing # each destination pixel as the average of two vertically-aligned source # pixels. The main use of this routine is to forestall excessive flicker # if the image two vertically-aligned source pixels, hence the name. if verbose: print 'tovideo' videoimage = imageop.tovideo(image, 4, width, height) # Convert an rgb image to an 8 bit rgb if verbose: print 'rgb2rgb8' greyimage = imageop.rgb2rgb8(image, width, height) # Convert an 8 bit rgb image to a 24 bit rgb image if verbose: print 'rgb82rgb' image = imageop.rgb82rgb(greyimage, width, height) # Convert an rgb image to an 8 bit greyscale image if verbose: print 'rgb2grey' greyimage = imageop.rgb2grey(image, width, height) # Convert an 8 bit greyscale image to a 24 bit rgb image if verbose: print 'grey2rgb' image = imageop.grey2rgb(greyimage, width, height) # Convert a 8-bit deep greyscale image to a 1-bit deep image by # thresholding all the pixels. The resulting image is tightly packed # and is probably only useful as an argument to mono2grey. if verbose: print 'grey2mono' monoimage = imageop.grey2mono(greyimage, width, height, 0) # monoimage, width, height = getimage('monotest.rgb') # Convert a 1-bit monochrome image to an 8 bit greyscale or color image. # All pixels that are zero-valued on input get value p0 on output and # all one-value input pixels get value p1 on output. To convert a # monochrome black-and-white image to greyscale pass the values 0 and # 255 respectively. if verbose: print 'mono2grey' greyimage = imageop.mono2grey(monoimage, width, height, 0, 255) # Convert an 8-bit greyscale image to a 1-bit monochrome image using a # (simple-minded) dithering algorithm. if verbose: print 'dither2mono' monoimage = imageop.dither2mono(greyimage, width, height) # Convert an 8-bit greyscale image to a 4-bit greyscale image without # dithering. if verbose: print 'grey2grey4' grey4image = imageop.grey2grey4(greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image without # dithering. if verbose: print 'grey2grey2' grey2image = imageop.grey2grey2(greyimage, width, height) # Convert an 8-bit greyscale image to a 2-bit greyscale image with # dithering. As for dither2mono, the dithering algorithm is currently # very simple. if verbose: print 'dither2grey2' grey2image = imageop.dither2grey2(greyimage, width, height) # Convert a 4-bit greyscale image to an 8-bit greyscale image. if verbose: print 'grey42grey' greyimage = imageop.grey42grey(grey4image, width, height) # Convert a 2-bit greyscale image to an 8-bit greyscale image. if verbose: print 'grey22grey' image = imageop.grey22grey(grey2image, width, height) # Cleanup unlink('test' + os.extsep + 'rgb')
def test_unpack_iter(self): a, b = 1, 2 self.assertEqual((a, b), (1, 2)) a, b, c = IteratingSequenceClass(3) self.assertEqual((a, b, c), (0, 1, 2)) try: # too many values a, b = IteratingSequenceClass(3) except ValueError: pass else: self.fail("should have raised ValueError") try: # not enough values a, b, c = IteratingSequenceClass(2) except ValueError: pass else: self.fail("should have raised ValueError") try: # not iterable a, b, c = len except TypeError: pass else: self.fail("should have raised TypeError") a, b, c = {1: 42, 2: 42, 3: 42}.itervalues() self.assertEqual((a, b, c), (42, 42, 42)) f = open(TESTFN, "w") lines = ("a\n", "bb\n", "ccc\n") try: for line in lines: f.write(line) finally: f.close() f = open(TESTFN, "r") try: a, b, c = f self.assertEqual((a, b, c), lines) finally: f.close() try: unlink(TESTFN) except OSError: pass (a, b), (c, ) = IteratingSequenceClass(2), {42: 24} self.assertEqual((a, b, c), (0, 1, 42)) # Test reference count behavior class C(object): count = 0 def __new__(cls): cls.count += 1 return object.__new__(cls) def __del__(self): cls = self.__class__ assert cls.count > 0 cls.count -= 1 x = C() self.assertEqual(C.count, 1) del x gc.collect() self.assertEqual(C.count, 0) l = [C(), C(), C()] self.assertEqual(C.count, 3) try: a, b = iter(l) except ValueError: pass del l gc.collect() self.assertEqual(C.count, 0)
def setUp(self): test_support.unlink(self.filename)
def tearDown(self): for suffix in ['', '.pag', '.dir', '.db']: test_support.unlink(self.filename + suffix)