desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'succeed iff {l1} - {ignore} == {l2} - {ignore}'
def assertListEq(self, l1, l2, ignore):
missing = ((set(l1) ^ set(l2)) - set(ignore)) if missing: print >>sys.stderr, ('l1=%r\nl2=%r\nignore=%r' % (l1, l2, ignore)) self.fail(('%r missing' % missing.pop()))
'succeed iff hasattr(obj,attr) or attr in ignore.'
def assertHasattr(self, obj, attr, ignore):
if (attr in ignore): return if (not hasattr(obj, attr)): print '???', attr self.assertTrue(hasattr(obj, attr), ('expected hasattr(%r, %r)' % (obj, attr)))
'succeed iff key in obj or key in ignore.'
def assertHaskey(self, obj, key, ignore):
if (key in ignore): return if (key not in obj): print >>sys.stderr, '***', key self.assertIn(key, obj)
'succeed iff a == b or a in ignore or b in ignore'
def assertEqualsOrIgnored(self, a, b, ignore):
if ((a not in ignore) and (b not in ignore)): self.assertEqual(a, b)
'succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.'
def checkModule(self, moduleName, module=None, ignore=()):
if (module is None): module = __import__(moduleName, globals(), {}, ['<silly>']) dict = pyclbr.readmodule_ex(moduleName) def ismethod(oclass, obj, name): classdict = oclass.__dict__ if isinstance(obj, FunctionType): if (not isinstance(classdict[name], StaticMethodType)): ...
'Wrapper around struct.calcsize which enforces the alignment of the end of a structure to the alignment requirement of pointer. Note: This wrapper should only be used if a pointer member is included and no member with a size larger than a pointer exists.'
def calcsize(self, fmt):
return struct.calcsize((fmt + '0P'))
'Constructor: Rat([num[, den]]). The arguments must be ints or longs, and default to (0, 1).'
def __init__(self, num=0L, den=1L):
if (not isint(num)): raise TypeError, ('Rat numerator must be int or long (%r)' % num) if (not isint(den)): raise TypeError, ('Rat denominator must be int or long (%r)' % den) if (den == 0): raise ZeroDivisionError, 'zero denominator' ...
'Accessor function for read-only \'num\' attribute of Rat.'
def _get_num(self):
return self.__num
'Accessor function for read-only \'den\' attribute of Rat.'
def _get_den(self):
return self.__den
'Convert a Rat to an string resembling a Rat constructor call.'
def __repr__(self):
return ('Rat(%d, %d)' % (self.__num, self.__den))
'Convert a Rat to a string resembling a decimal numeric value.'
def __str__(self):
return str(float(self))
'Convert a Rat to a float.'
def __float__(self):
return ((self.__num * 1.0) / self.__den)
'Convert a Rat to an int; self.den must be 1.'
def __int__(self):
if (self.__den == 1): try: return int(self.__num) except OverflowError: raise OverflowError, ('%s too large to convert to int' % repr(self)) raise ValueError, ("can't convert %s to int" % repr(self))
'Convert a Rat to an long; self.den must be 1.'
def __long__(self):
if (self.__den == 1): return long(self.__num) raise ValueError, ("can't convert %s to long" % repr(self))
'Add two Rats, or a Rat and a number.'
def __add__(self, other):
if isint(other): other = Rat(other) if isRat(other): return Rat(((self.__num * other.__den) + (other.__num * self.__den)), (self.__den * other.__den)) if isnum(other): return (float(self) + other) return NotImplemented
'Subtract two Rats, or a Rat and a number.'
def __sub__(self, other):
if isint(other): other = Rat(other) if isRat(other): return Rat(((self.__num * other.__den) - (other.__num * self.__den)), (self.__den * other.__den)) if isnum(other): return (float(self) - other) return NotImplemented
'Subtract two Rats, or a Rat and a number (reversed args).'
def __rsub__(self, other):
if isint(other): other = Rat(other) if isRat(other): return Rat(((other.__num * self.__den) - (self.__num * other.__den)), (self.__den * other.__den)) if isnum(other): return (other - float(self)) return NotImplemented
'Multiply two Rats, or a Rat and a number.'
def __mul__(self, other):
if isRat(other): return Rat((self.__num * other.__num), (self.__den * other.__den)) if isint(other): return Rat((self.__num * other), self.__den) if isnum(other): return (float(self) * other) return NotImplemented
'Divide two Rats, or a Rat and a number.'
def __truediv__(self, other):
if isRat(other): return Rat((self.__num * other.__den), (self.__den * other.__num)) if isint(other): return Rat(self.__num, (self.__den * other)) if isnum(other): return (float(self) / other) return NotImplemented
'Divide two Rats, or a Rat and a number (reversed args).'
def __rtruediv__(self, other):
if isRat(other): return Rat((other.__num * self.__den), (other.__den * self.__num)) if isint(other): return Rat((other * self.__den), self.__num) if isnum(other): return (other / float(self)) return NotImplemented
'Divide two Rats, returning the floored result.'
def __floordiv__(self, other):
if isint(other): other = Rat(other) elif (not isRat(other)): return NotImplemented x = (self / other) return (x.__num // x.__den)
'Divide two Rats, returning the floored result (reversed args).'
def __rfloordiv__(self, other):
x = (other / self) return (x.__num // x.__den)
'Divide two Rats, returning quotient and remainder.'
def __divmod__(self, other):
if isint(other): other = Rat(other) elif (not isRat(other)): return NotImplemented x = (self // other) return (x, (self - (other * x)))
'Divide two Rats, returning quotient and remainder (reversed args).'
def __rdivmod__(self, other):
if isint(other): other = Rat(other) elif (not isRat(other)): return NotImplemented return divmod(other, self)
'Take one Rat modulo another.'
def __mod__(self, other):
return divmod(self, other)[1]
'Take one Rat modulo another (reversed args).'
def __rmod__(self, other):
return divmod(other, self)[1]
'Compare two Rats for equality.'
def __eq__(self, other):
if isint(other): return ((self.__den == 1) and (self.__num == other)) if isRat(other): return ((self.__num == other.__num) and (self.__den == other.__den)) if isnum(other): return (float(self) == other) return NotImplemented
'Compare two Rats for inequality.'
def __ne__(self, other):
return (not (self == other))
'Make sure the specified module, when imported, raises a DeprecationWarning and specifies itself in the message.'
def check_removal(self, module_name, optional=False):
with CleanImport(module_name): with warnings.catch_warnings(): warnings.filterwarnings('error', '.+ (module|package) .+ removed', DeprecationWarning, __name__) warnings.filterwarnings('error', '.+ removed .+ (module|package)', DeprecationWarning, __name__) ...
'>>> print TwoNames().f() f'
def f(self):
return 'f'
'Writes a file in the given path. path can be a string or a sequence.'
def write_file(self, path, content='xxx'):
if isinstance(path, (list, tuple)): path = os.path.join(*path) f = open(path, 'w') try: f.write(content) finally: f.close()
'Create a temporary directory that will be cleaned up. Returns the path of the directory.'
def mkdtemp(self):
d = tempfile.mkdtemp() self.tempdirs.append(d) return d
'Convert x into the appropriate type for these tests.'
def marshal(self, x):
raise RuntimeError('test class must provide a marshal method')
'assert that dedent() has no effect on \'text\''
def assertUnchanged(self, text):
self.assertEqual(text, dedent(text))
'A trace function that raises an exception in response to a specific trace event.'
def trace(self, frame, event, arg):
if (event == self.raiseOnEvent): raise ValueError else: return self.trace
'The function to trace; raises an exception if that\'s the case we\'re testing, so that the \'exception\' trace event fires.'
def f(self):
if (self.raiseOnEvent == 'exception'): x = 0 y = (1 // x) else: return 1
'Tests that an exception raised in response to the given event is handled OK.'
def run_test_for_event(self, event):
self.raiseOnEvent = event try: for i in xrange((sys.getrecursionlimit() + 1)): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail('exception not thrown!') except RuntimeE...
'>>> print C() # 4 42'
def __str__(self):
return '42'
'>>> c = C() # 7 >>> c.x = 12 # 8 >>> print c.x # 9 -12'
def getx(self):
return (- self._x)
'>>> c = C() # 10 >>> c.x = 12 # 11 >>> print c.x # 12 -12'
def setx(self, value):
self._x = value
'A static method. >>> print C.statm() # 16 666 >>> print C().statm() # 17 666'
@staticmethod def statm():
return 666
'A class method. >>> print C.clsm(22) # 18 22 >>> print C().clsm(23) # 19 23'
@classmethod def clsm(cls, val):
return val
'Make sure attribute names with underscores are accepted'
def test_underscore_in_attrname(self):
self.check_events('<a has_under _under>', [('starttag', 'a', [('has_under', 'has_under'), ('_under', '_under')])])
'Make sure tag names with underscores are accepted'
def test_underscore_in_tagname(self):
self.check_events('<has_under></has_under>', [('starttag', 'has_under', []), ('endtag', 'has_under')])
'Be sure quotes in unquoted attributes are made part of the value'
def test_quotes_in_unquoted_attrs(self):
self.check_events('<a href=foo\'bar"baz>', [('starttag', 'a', [('href', 'foo\'bar"baz')])])
'Handling of XHTML-style empty start tags'
def test_xhtml_empty_tag(self):
self.check_events('<br />text<i></i>', [('starttag', 'br', []), ('data', 'text'), ('starttag', 'i', []), ('endtag', 'i')])
'Substitution of entities and charrefs in attribute values'
def test_attr_values_entities(self):
self.check_events('<a b=&lt; c=&lt;&gt; d=&lt-&gt; e=\'&lt; \'\n f="&xxx;" g=\'&#32;&#33;\' h=\'&#500;\'\n ...
'read_until(expected, [timeout]) Read until the expected string has been seen, or a timeout is hit (default is no timeout); may block.'
def test_read_until_A(self):
want = [('x' * 10), 'match', ('y' * 10), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) self.dataq.join() data = telnet.read_until('match') self.assertEqual(data, ''.join(want[:(-2)]))
'read_all() Read all data until EOF; may block.'
def test_read_all_A(self):
want = [('x' * 500), ('y' * 500), ('z' * 500), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) self.dataq.join() data = telnet.read_all() self.assertEqual(data, ''.join(want[:(-1)])) return
'read_some() Read at least one byte or EOF; may block.'
def test_read_some_A(self):
want = [('x' * 500), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) self.dataq.join() data = telnet.read_all() self.assertTrue((len(data) >= 1))
'read_very_eager() Read all data available already queued or on the socket, without blocking.'
def _test_read_any_eager_A(self, func_name):
want = [self.block_long, ('x' * 100), ('y' * 100), EOF_sigil] expects = (want[1] + want[2]) self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) self.dataq.join() func = getattr(telnet, func_name) data = '' while True: try: data += func() self.a...
'helper for testing IAC + cmd'
def _test_command(self, data):
self.setUp() self.dataq.put(data) telnet = telnetlib.Telnet(HOST, self.port) self.dataq.join() nego = nego_collector() telnet.set_option_negotiation_callback(nego.do_nego) txt = telnet.read_all() cmd = nego.seen self.assertTrue((len(cmd) > 0)) self.assertIn(cmd[0], self.cmds) ...
'Block when a given char is encountered.'
def block_on(self, char):
self._blocker_char = char
'Check that a partial write, when it gets interrupted, properly invokes the signal handler, and bubbles up the exception raised in the latter.'
@unittest.skipUnless(threading, u'Threading required for this test.') def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
read_results = [] def _read(): s = os.read(r, 1) read_results.append(s) t = threading.Thread(target=_read) t.daemon = True (r, w) = os.pipe() try: wio = self.io.open(w, **fdopen_kwargs) t.start() signal.alarm(1) self.assertRaises(ZeroDivisionError,...
'Check that a buffered read, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.'
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
(r, w) = os.pipe() fdopen_kwargs[u'closefd'] = False def alarm_handler(sig, frame): os.write(w, 'bar') signal.signal(signal.SIGALRM, alarm_handler) try: rio = self.io.open(r, **fdopen_kwargs) os.write(w, 'foo') signal.alarm(1) self.assertEqual(decode(rio.read(...
'Check that a buffered write, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.'
@unittest.skipUnless(threading, u'Threading required for this test.') def check_interrupted_write_retry(self, item, **fdopen_kwargs):
select = support.import_module(u'select') N = (1024 * 1024) (r, w) = os.pipe() fdopen_kwargs[u'closefd'] = False read_results = [] write_finished = False def _read(): while (not write_finished): while (r in select.select([r], [], [], 1.0)[0]): s = os.read(...
'Bounce a pickled object through another version of Python. This will pickle the object, send it to a child process where it will be unpickled, then repickled and sent back to the parent process. Args: python: the name of the Python binary to start. obj: object to pickle. proto: pickle protocol number to use. Returns: ...
def send_to_worker(self, python, obj, proto):
target = __file__ if (target[(-1)] in ('c', 'o')): target = target[:(-1)] data = self.module.dumps((proto, obj), proto) worker = subprocess.Popen([python, target, 'worker'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = worker.communicate(data) ...
'Test an empty maildir mailbox'
def test_empty_maildir(self):
self.mbox = mailbox.Maildir(test_support.TESTFN) self.assertIs(self.mbox.next(), None) self.assertIs(self.mbox.next(), None)
'Import a module and return a reference to it or None on failure.'
def _conditional_import_module(self, module_name):
try: exec ('import ' + module_name) except ImportError as error: if self._warn_on_extension_import: warnings.warn(('Did a C extension fail to compile? %s' % error)) return locals().get(module_name)
'succeed iff str is a valid piece of code'
def assertValid(self, str, symbol='single'):
if is_jython: code = compile_command(str, '<input>', symbol) self.assertTrue(code) if (symbol == 'single'): (d, r) = ({}, {}) saved_stdout = sys.stdout sys.stdout = cStringIO.StringIO() try: exec code in d exec c...
'succeed iff str is the start of a valid piece of code'
def assertIncomplete(self, str, symbol='single'):
self.assertEqual(compile_command(str, symbol=symbol), None)
'succeed iff str is the start of an invalid piece of code'
def assertInvalid(self, str, symbol='single', is_syntax=1):
try: compile_command(str, symbol=symbol) self.fail('No exception thrown for invalid code') except SyntaxError: self.assertTrue(is_syntax) except OverflowError: self.assertTrue((not is_syntax))
'Check handling of non-integer ports.'
def test_attributes_bad_port(self):
p = urlparse.urlsplit('http://www.example.net:foo') self.assertEqual(p.netloc, 'www.example.net:foo') self.assertRaises(ValueError, (lambda : p.port)) p = urlparse.urlparse('http://www.example.net:foo') self.assertEqual(p.netloc, 'www.example.net:foo') self.assertRaises(ValueError, (lambda : p.p...
'Compare calculation against known value, if available'
def numeric_tester(self, calc_type, calc_value, data_type, used_locale):
try: set_locale = setlocale(LC_NUMERIC) except Error: set_locale = '<not able to determine>' known_value = known_numerics.get(used_locale, ('', ''))[(data_type == 'thousands_sep')] if (known_value and calc_value): self.assertEqual(calc_value, known_value, (self.lc_numeri...
'Save a copy of sys.path'
def setUp(self):
self.sys_path = sys.path[:] self.old_base = site.USER_BASE self.old_site = site.USER_SITE self.old_prefixes = site.PREFIXES self.old_vars = copy(sysconfig._CONFIG_VARS)
'Restore sys.path'
def tearDown(self):
sys.path[:] = self.sys_path site.USER_BASE = self.old_base site.USER_SITE = self.old_site site.PREFIXES = self.old_prefixes sysconfig._CONFIG_VARS = self.old_vars
'Contain common code for testing results of reading a .pth file'
def pth_file_tests(self, pth_file):
self.assertIn(pth_file.imported, sys.modules, ('%s not in sys.modules' % pth_file.imported)) self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertFalse(os.path.exists(pth_file.bad_dir_path))
'Initialize instance variables'
def __init__(self, filename_base=TESTFN, imported='time', good_dirname='__testdir__', bad_dirname='__bad'):
self.filename = (filename_base + '.pth') self.base_dir = os.path.abspath('') self.file_path = os.path.join(self.base_dir, self.filename) self.imported = imported self.good_dirname = good_dirname self.bad_dirname = bad_dirname self.good_dir_path = os.path.join(self.base_dir, self.good_dirname...
'Create a .pth file with a comment, blank lines, an ``import <self.imported>``, a line with self.good_dirname, and a line with self.bad_dirname. Creation of the directory for self.good_dir_path (based off of self.good_dirname) is also performed. Make sure to call self.cleanup() to undo anything done by this method.'
def create(self):
FILE = open(self.file_path, 'w') try: print >>FILE, '#import @bad module name' print >>FILE, '\n' print >>FILE, ('import %s' % self.imported) print >>FILE, self.good_dirname print >>FILE, self.bad_dirname finally: FILE.close() os.mkdir(self.goo...
'Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.'
def cleanup(self, prep=False):
if os.path.exists(self.file_path): os.remove(self.file_path) if prep: self.imported_module = sys.modules.get(self.imported) if self.imported_module: del sys.modules[self.imported] elif self.imported_module: sys.modules[self.imported] = self.imported_module if ...
'Make a copy of sys.path'
def setUp(self):
self.sys_path = sys.path[:]
'Restore sys.path'
def tearDown(self):
sys.path[:] = self.sys_path
'Wow, I have no function!'
def __init__():
pass
'Check that int(x) has the correct value and type, for a float x.'
def check_conversion_to_int(self, x):
n = int(x) if (x >= 0.0): self.assertLessEqual(n, x) self.assertLess(x, (n + 1)) else: self.assertGreaterEqual(n, x) self.assertGreater(x, (n - 1)) if (((- sys.maxint) - 1) <= n <= sys.maxint): self.assertEqual(type(n), int) else: self.assertEqual(type...
'Check that compiling code raises SyntaxError with errtext. errtest is a regular expression that must be present in the test of the exception raised. If subclass is specified it is the expected subclass of SyntaxError (e.g. IndentationError).'
def _check_error(self, code, errtext, filename='<testcase>', mode='exec', subclass=None):
try: compile(code, filename, mode) except SyntaxError as err: if (subclass and (not isinstance(err, subclass))): self.fail(('SyntaxError is not a %s' % subclass.__name__)) mo = re.search(errtext, str(err)) if (mo is None): self.fail(("%s did...
'Compare the result of Python\'s builtin correctly rounded string->float conversion (using float) to a pure Python correctly rounded string->float implementation. Fail if the two methods give different results.'
def check_strtod(self, s):
try: fs = float(s) except OverflowError: got = ('-inf' if (s[0] == '-') else 'inf') except MemoryError: got = 'memory error' else: got = fs.hex() expected = strtod(s) self.assertEqual(expected, got, 'Incorrectly rounded str->float conversion for ...
'Try to save previous ulimit, then set it to (0, 0).'
def __enter__(self):
try: import resource self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) except (ImportError, ValueError, resource.error): pass if (sys.platform == 'darwin'): value = subprocess.Popen(['/usr/bin/defaults', 'read',...
'Return core file behavior to default.'
def __exit__(self, *args):
if (self.old_limit is None): return try: import resource resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) except (ImportError, ValueError, resource.error): pass
'Fail if the two floating-point numbers are not almost equal. Determine whether floating-point values a and b are equal to within a (small) rounding error. The default values for rel_err and abs_err are chosen to be suitable for platforms where a float is represented by an IEEE 754 double. They allow an error of betw...
def rAssertAlmostEqual(self, a, b, rel_err=2e-15, abs_err=5e-323, msg=None):
if math.isnan(a): if math.isnan(b): return self.fail((msg or '{!r} should be nan'.format(b))) if math.isinf(a): if (a == b): return self.fail((msg or 'finite result where infinity expected: expected {!r}, got {!r}'.format(a...
'This method allows the server to explicitly indicate that it wants the client thread to proceed. This is useful if the server is about to execute a blocking routine that is dependent upon the client thread during its setup routine.'
def serverExplicitReady(self):
self.server_ready.set()
'Use a temporary socket to elicit an unused ephemeral port. Args: bind_address: Hostname or IP address to search for a port on. Returns: A most likely to be unused port.'
def _get_unused_port(self, bind_address='0.0.0.0'):
tempsock = socket.socket() tempsock.bind((bind_address, 0)) (host, port) = tempsock.getsockname() tempsock.close() return port
'Return a socket which times out on connect'
@contextlib.contextmanager def mocked_socket_module(self):
old_socket = socket.socket socket.socket = self.MockSocket try: (yield) finally: socket.socket = old_socket
'pstats.add_callers should combine the call results of both target and source by adding the call time. See issue1269.'
def test_combine_results(self):
target = {'a': (1, 2, 3, 4)} source = {'a': (1, 2, 3, 4), 'b': (5, 6, 7, 8)} new_callers = pstats.add_callers(target, source) self.assertEqual(new_callers, {'a': (2, 4, 6, 8), 'b': (5, 6, 7, 8)}) target = {'a': 1} source = {'a': 1, 'b': 5} new_callers = pstats.add_callers(target, source) ...
'Test data splitting with posix parser'
def testSplitPosix(self):
self.splitTest(self.posix_data, comments=True)
'Test compatibility interface'
def testCompat(self):
for i in range(len(self.data)): l = self.oldSplit(self.data[i][0]) self.assertEqual(l, self.data[i][1:], ('%s: %s != %s' % (self.data[i][0], l, self.data[i][1:])))
'This will prove that the timeout gets through HTTPConnection and into the socket.'
def testTimeoutAttribute(self):
self.assertTrue((socket.getdefaulttimeout() is None)) socket.setdefaulttimeout(30) try: httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() ...
'Add an event to the log.'
def add_event(self, event, frame=None):
if (frame is None): frame = sys._getframe(1) try: frameno = self.frames.index(frame) except ValueError: frameno = len(self.frames) self.frames.append(frame) self.events.append((frameno, event, ident(frame)))
'Remove calls to add_event().'
def get_events(self):
disallowed = [ident(self.add_event.im_func), ident(ident)] self.frames = None return [item for item in self.events if (item[2] not in disallowed)]
'SF bug #1486663 -- this used to erroneously raise a TypeError'
def test_keywords_in_subclass(self):
SetSubclassWithKeywordArgs(newarg=1)
'Helper function to make a list of random numbers'
def randomlist(self, n):
return [self.gen.random() for i in xrange(n)]
'Test multiple targets on the left hand side.'
def testMultipleLHS(self):
snippets = ['a, b = 1, 2', '(a, b) = 1, 2', '((a, b), c) = (1, 2), 3'] for s in snippets: a = transformer.parse(s) self.assertIsInstance(a, ast.Module) child1 = a.getChildNodes()[0] self.assertIsInstance(child1, ast.Stmt) child2 =...
'Make a copy of sys.path'
def setUp(self):
super(TestSysConfig, self).setUp() self.sys_path = sys.path[:] self.makefile = None if hasattr(os, 'uname'): self.uname = os.uname self._uname = os.uname() else: self.uname = None self._uname = None os.uname = self._get_uname self.name = os.name self.platf...
'Restore sys.path'
def tearDown(self):
sys.path[:] = self.sys_path if (self.makefile is not None): os.unlink(self.makefile) self._cleanup_testfn() if (self.uname is not None): os.uname = self.uname else: del os.uname os.name = self.name sys.platform = self.platform sys.version = self.version os.sep...
'Setup of a temp file to use for testing'
def setUp(self):
self.text = ('test_urllib: %s\n' % self.__class__.__name__) FILE = file(test_support.TESTFN, 'wb') try: FILE.write(self.text) finally: FILE.close() self.pathname = test_support.TESTFN self.returned_obj = urllib.urlopen(('file:%s' % self.pathname))
'Shut down the open object'
def tearDown(self):
self.returned_obj.close() os.remove(test_support.TESTFN)
'Creates a new temporary file containing the specified data, registers the file for deletion during the test fixture tear down, and returns the absolute path of the file.'
def createNewTempFile(self, data=''):
(newFd, newFilePath) = tempfile.mkstemp() try: self.registerFileForCleanUp(newFilePath) newFile = os.fdopen(newFd, 'wb') newFile.write(data) newFile.close() finally: try: newFile.close() except: pass return newFilePath
'Helper method for testing different input types. \'given\' must lead to only the pairs: * 1st, 1 * 2nd, 2 * 3rd, 3 Test cannot assume anything about order. Docs make no guarantee and have possible dictionary input.'
def help_inputtype(self, given, test_type):
expect_somewhere = ['1st=1', '2nd=2', '3rd=3'] result = urllib.urlencode(given) for expected in expect_somewhere: self.assertIn(expected, result, ('testing %s: %s not found in %s' % (test_type, expected, result))) self.assertEqual(result.count('&'), 2, ("testing %s: expec...
'Some of the password examples are not sensible, but it is added to confirming to RFC2617 and addressing issue4675.'
def test_splitpasswd(self):
self.assertEqual(('user', 'ab'), urllib.splitpasswd('user:ab')) self.assertEqual(('user', 'a\nb'), urllib.splitpasswd('user:a\nb')) self.assertEqual(('user', 'a DCTB b'), urllib.splitpasswd('user:a DCTB b')) self.assertEqual(('user', 'a\rb'), urllib.splitpasswd('user:a\rb')) self.assertEqual(('user'...
'Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and posit...
def assertParseOK(self, args, expected_opts, expected_positional_args):
(options, positional_args) = self.parser.parse_args(args) optdict = vars(options) self.assertEqual(optdict, expected_opts, ('\nOptions are %(optdict)s.\nShould be %(expected_opts)s.\nArgs were %(args)s.' % locals())) self.assertEqual(positional_args, expected_positional_args, ('\nPosit...
'Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_mes...
def assertRaises(self, func, args, kwargs, expected_exception, expected_message):
if (args is None): args = () if (kwargs is None): kwargs = {} try: func(*args, **kwargs) except expected_exception as err: actual_message = str(err) if isinstance(expected_message, retype): self.assertTrue(expected_message.search(actual_message), ("exp...