desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests invoking FileInput.__getitem__() with an index unequal to the line number'
def test__getitem__invalid_key(self):
t = writeTmp(1, ['line1\n', 'line2\n']) self.addCleanup(remove_tempfiles, t) with FileInput(files=[t]) as fi: with self.assertRaises(RuntimeError) as cm: fi[1] self.assertEqual(cm.exception.args, ('accessing lines out of order',))
'Tests invoking FileInput.__getitem__() with the line number but at end-of-input'
def test__getitem__eof(self):
t = writeTmp(1, []) self.addCleanup(remove_tempfiles, t) with FileInput(files=[t]) as fi: with self.assertRaises(IndexError) as cm: fi[0] self.assertEqual(cm.exception.args, ('end of input reached',))
'Tests invoking FileInput.nextfile() when the attempt to delete the backup file would raise OSError. This error is expected to be silently ignored'
def test_nextfile_oserror_deleting_backup(self):
os_unlink_orig = os.unlink os_unlink_replacement = UnconditionallyRaise(OSError) try: t = writeTmp(1, ['\n']) self.addCleanup(remove_tempfiles, t) with FileInput(files=[t], inplace=True) as fi: next(fi) os.unlink = os_unlink_replacement fi.nextfile...
'Tests invoking FileInput.readline() when os.fstat() raises OSError. This exception should be silently discarded.'
def test_readline_os_fstat_raises_OSError(self):
os_fstat_orig = os.fstat os_fstat_replacement = UnconditionallyRaise(OSError) try: t = writeTmp(1, ['\n']) self.addCleanup(remove_tempfiles, t) with FileInput(files=[t], inplace=True) as fi: os.fstat = os_fstat_replacement fi.readline() finally: os...
'Tests invoking FileInput.readline() when os.chmod() raises OSError. This exception should be silently discarded.'
@unittest.skipIf((not hasattr(os, 'chmod')), 'os.chmod does not exist') def test_readline_os_chmod_raises_OSError(self):
os_chmod_orig = os.chmod os_chmod_replacement = UnconditionallyRaise(OSError) try: t = writeTmp(1, ['\n']) self.addCleanup(remove_tempfiles, t) with FileInput(files=[t], inplace=True) as fi: os.chmod = os_chmod_replacement fi.readline() finally: os...
'Tests invoking fileinput.input() when fileinput._state is not None and its _file attribute is also not None. Expect RuntimeError to be raised with a meaningful error message and for fileinput._state to *not* be modified.'
def test_state_is_not_None_and_state_file_is_not_None(self):
instance = MockFileInput() instance._file = object() fileinput._state = instance with self.assertRaises(RuntimeError) as cm: fileinput.input() self.assertEqual(('input() already active',), cm.exception.args) self.assertIs(instance, fileinput._state, 'fileinput._state')
'Tests invoking fileinput.input() when fileinput._state is not None but its _file attribute *is* None. Expect it to create and return a new fileinput.FileInput object with all method parameters passed explicitly to the __init__() method; also ensure that fileinput._state is set to the returned instance.'
def test_state_is_not_None_and_state_file_is_None(self):
instance = MockFileInput() instance._file = None fileinput._state = instance self.do_test_call_input()
'Tests invoking fileinput.input() when fileinput._state is None Expect it to create and return a new fileinput.FileInput object with all method parameters passed explicitly to the __init__() method; also ensure that fileinput._state is set to the returned instance.'
def test_state_is_None(self):
fileinput._state = None self.do_test_call_input()
'Tests that fileinput.input() creates a new fileinput.FileInput object, passing the given parameters unmodified to fileinput.FileInput.__init__(). Note that this test depends on the monkey patching of fileinput.FileInput done by setUp().'
def do_test_call_input(self):
files = object() inplace = object() backup = object() bufsize = object() mode = object() openhook = object() result = fileinput.input(files=files, inplace=inplace, backup=backup, bufsize=bufsize, mode=mode, openhook=openhook) self.assertIs(result, fileinput._state, 'fileinput._state') ...
'Tests that fileinput.close() does nothing if fileinput._state is None'
def test_state_is_None(self):
fileinput._state = None fileinput.close() self.assertIsNone(fileinput._state)
'Tests that fileinput.close() invokes close() on fileinput._state and sets _state=None'
def test_state_is_not_None(self):
instance = MockFileInput() fileinput._state = instance fileinput.close() self.assertExactlyOneInvocation(instance, 'close') self.assertIsNone(fileinput._state)
'Tests fileinput.nextfile() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.nextfile() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.nextfile() when fileinput._state is not None. Ensure that it invokes fileinput._state.nextfile() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
nextfile_retval = object() instance = MockFileInput() instance.return_values['nextfile'] = nextfile_retval fileinput._state = instance retval = fileinput.nextfile() self.assertExactlyOneInvocation(instance, 'nextfile') self.assertIs(retval, nextfile_retval) self.assertIs(fileinput._state...
'Tests fileinput.filename() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.filename() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.filename() when fileinput._state is not None. Ensure that it invokes fileinput._state.filename() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
filename_retval = object() instance = MockFileInput() instance.return_values['filename'] = filename_retval fileinput._state = instance retval = fileinput.filename() self.assertExactlyOneInvocation(instance, 'filename') self.assertIs(retval, filename_retval) self.assertIs(fileinput._state...
'Tests fileinput.lineno() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.lineno() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.lineno() when fileinput._state is not None. Ensure that it invokes fileinput._state.lineno() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
lineno_retval = object() instance = MockFileInput() instance.return_values['lineno'] = lineno_retval fileinput._state = instance retval = fileinput.lineno() self.assertExactlyOneInvocation(instance, 'lineno') self.assertIs(retval, lineno_retval) self.assertIs(fileinput._state, instance)
'Tests fileinput.filelineno() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.filelineno() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.filelineno() when fileinput._state is not None. Ensure that it invokes fileinput._state.filelineno() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
filelineno_retval = object() instance = MockFileInput() instance.return_values['filelineno'] = filelineno_retval fileinput._state = instance retval = fileinput.filelineno() self.assertExactlyOneInvocation(instance, 'filelineno') self.assertIs(retval, filelineno_retval) self.assertIs(file...
'Tests fileinput.fileno() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.fileno() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.fileno() when fileinput._state is not None. Ensure that it invokes fileinput._state.fileno() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
fileno_retval = object() instance = MockFileInput() instance.return_values['fileno'] = fileno_retval instance.fileno_retval = fileno_retval fileinput._state = instance retval = fileinput.fileno() self.assertExactlyOneInvocation(instance, 'fileno') self.assertIs(retval, fileno_retval) ...
'Tests fileinput.isfirstline() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.isfirstline() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.isfirstline() when fileinput._state is not None. Ensure that it invokes fileinput._state.isfirstline() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
isfirstline_retval = object() instance = MockFileInput() instance.return_values['isfirstline'] = isfirstline_retval fileinput._state = instance retval = fileinput.isfirstline() self.assertExactlyOneInvocation(instance, 'isfirstline') self.assertIs(retval, isfirstline_retval) self.assertI...
'Tests fileinput.isstdin() when fileinput._state is None. Ensure that it raises RuntimeError with a meaningful error message and does not modify fileinput._state'
def test_state_is_None(self):
fileinput._state = None with self.assertRaises(RuntimeError) as cm: fileinput.isstdin() self.assertEqual(('no active input()',), cm.exception.args) self.assertIsNone(fileinput._state)
'Tests fileinput.isstdin() when fileinput._state is not None. Ensure that it invokes fileinput._state.isstdin() exactly once, returns whatever it returns, and does not modify fileinput._state to point to a different object.'
def test_state_is_not_None(self):
isstdin_retval = object() instance = MockFileInput() instance.return_values['isstdin'] = isstdin_retval fileinput._state = instance retval = fileinput.isstdin() self.assertExactlyOneInvocation(instance, 'isstdin') self.assertIs(retval, isstdin_retval) self.assertIs(fileinput._state, inst...
'Asserts that both the types and values are the same.'
def assertTypedEquals(self, expected, actual):
self.assertEqual(type(expected), type(actual)) self.assertEqual(expected, actual)
'Asserts that callable(*args, **kwargs) raises exc_type(message).'
def assertRaisesMessage(self, exc_type, message, callable, *args, **kwargs):
try: callable(*args, **kwargs) except exc_type as e: self.assertEqual(message, str(e)) else: self.fail(('%s not raised' % exc_type.__name__))
'Returns instr if op is found, otherwise throws AssertionError'
def assertInBytecode(self, x, opname, argval=_UNSPECIFIED):
for instr in dis.get_instructions(x): if (instr.opname == opname): if ((argval is _UNSPECIFIED) or (instr.argval == argval)): return instr disassembly = self.get_disassembly_as_string(x) if (argval is _UNSPECIFIED): msg = ('%s not found in bytecode:\n%...
'Throws AssertionError if op is found'
def assertNotInBytecode(self, x, opname, argval=_UNSPECIFIED):
for instr in dis.get_instructions(x): if (instr.opname == opname): disassembly = self.get_disassembly_as_string(co) if (opargval is _UNSPECIFIED): msg = ('%s occurs in bytecode:\n%s' % (opname, disassembly)) elif (instr.argval == argval): ...
'Check that compileall recreates bytecode when the new metadata is used.'
@unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') def recreation_check(self, metadata):
py_compile.compile(self.source_path) self.assertEqual(*self.data()) with open(self.bc_path, 'rb') as file: bc = file.read()[len(metadata):] with open(self.bc_path, 'wb') as file: file.write(metadata) file.write(bc) self.assertNotEqual(*self.data()) compileall.compile_dir(...
'Another docstring containing tabs'
def abuse(self, a, b, c):
self.argue(a, b, c)
'Common code for chown, fchown and lchown tests.'
def _test_all_chown_common(self, chown_func, first_param, stat_func):
def check_stat(uid, gid): if (stat_func is not None): stat = stat_func(first_param) self.assertEqual(stat.st_uid, uid) self.assertEqual(stat.st_gid, gid) uid = os.getuid() gid = os.getgid() chown_func(first_param, uid, gid) check_stat(uid, gid) chown_f...
'Test functions that call path_error2(), providing two filenames in their exceptions.'
def test_path_error2(self):
for name in ('rename', 'replace', 'link', 'symlink'): function = getattr(os, name, None) if function: for dst in ('noodly2', support.TESTFN): try: function('doesnotexistfilename', dst) except OSError as e: self.asser...
'Issue #11670.'
def test_readline_generator(self):
parser = configparser.ConfigParser() with self.assertRaises(TypeError): parser.read_file(FakeFile()) parser.read_file(readline_generator(FakeFile())) self.assertIn('Foo Bar', parser) self.assertIn('foo', parser['Foo Bar']) self.assertEqual(parser['Foo Bar']['foo'], 'newbar')
'Issue #18260.'
def test_source_as_bytes(self):
lines = textwrap.dedent('\n [badbad]\n [badbad]').strip().split('\n') parser = configparser.ConfigParser() with self.assertRaises(configparser.DuplicateSectionError) as dse: parser.read_file(lines, source='badbad') self.assertEqual(st...
'Test the specified socket method. The method is run at most `count` times and must raise a socket.timeout within `timeout` + self.fuzz seconds.'
def _sock_operation(self, count, timeout, method, *args):
self.sock.settimeout(timeout) method = getattr(self.sock, method) for i in range(count): t1 = time.time() try: method(*args) except socket.timeout as e: delta = (time.time() - t1) break else: self.fail('socket.timeout was not r...
'Ensure exception does not display a context by default Wraps unittest.TestCase.assertRaisesRegex'
@contextlib.contextmanager def assertCleanError(self, exc_type, details, *args):
if args: details = (details % args) cm = self.assertRaisesRegex(exc_type, details) with cm as exc: (yield exc) if (exc.exception.__context__ is not None): self.assertTrue(exc.exception.__suppress_context__)
'Ensure a clean AddressValueError'
def assertAddressError(self, details, *args):
return self.assertCleanError(ipaddress.AddressValueError, details, *args)
'Ensure a clean NetmaskValueError'
def assertNetmaskError(self, details, *args):
return self.assertCleanError(ipaddress.NetmaskValueError, details, *args)
'Check constructor arguments produce equivalent instances'
def assertInstancesEqual(self, lhs, rhs):
self.assertEqual(self.factory(lhs), self.factory(rhs))
'Ensure a clean ValueError with the expected message'
def assertFactoryError(self, factory, kind):
addr = 'camelot' msg = '%r does not appear to be an IPv4 or IPv6 %s' with self.assertCleanError(ValueError, msg, addr, kind): factory(addr)
'Construct a bunch of `n` threads running the same function `f`. If `wait_before_exit` is True, the threads won\'t terminate until do_finish() is called.'
def __init__(self, f, n, wait_before_exit=False):
self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = (not wait_before_exit) def task(): tid = threading.get_ident() self.started.append(tid) try: f() finally: self.finished.append(tid) while (not self._can...
'Test that a barrier is passed in lockstep'
def test_barrier(self, passes=1):
results = [[], []] def f(): self.multipass(results, passes) self.run_threads(f)
'Test that a barrier works for 10 consecutive runs'
def test_barrier_10(self):
return self.test_barrier(10)
'test the return value from barrier.wait'
def test_wait_return(self):
results = [] def f(): r = self.barrier.wait() results.append(r) self.run_threads(f) self.assertEqual(sum(results), sum(range(self.N)))
'Test the \'action\' callback'
def test_action(self):
results = [] def action(): results.append(True) barrier = self.barriertype(self.N, action) def f(): barrier.wait() self.assertEqual(len(results), 1) self.run_threads(f)
'Test that an abort will put the barrier in a broken state'
def test_abort(self):
results1 = [] results2 = [] def f(): try: i = self.barrier.wait() if (i == (self.N // 2)): raise RuntimeError self.barrier.wait() results1.append(True) except threading.BrokenBarrierError: results2.append(True) ...
'Test that a \'reset\' on a barrier frees the waiting threads'
def test_reset(self):
results1 = [] results2 = [] results3 = [] def f(): i = self.barrier.wait() if (i == (self.N // 2)): while (self.barrier.n_waiting < (self.N - 1)): time.sleep(0.001) self.barrier.reset() else: try: self.barrier.wa...
'Test that a barrier can be reset after being broken.'
def test_abort_and_reset(self):
results1 = [] results2 = [] results3 = [] barrier2 = self.barriertype(self.N) def f(): try: i = self.barrier.wait() if (i == (self.N // 2)): raise RuntimeError self.barrier.wait() results1.append(True) except threading.B...
'Test wait(timeout)'
def test_timeout(self):
def f(): i = self.barrier.wait() if (i == (self.N // 2)): time.sleep(1.0) self.assertRaises(threading.BrokenBarrierError, self.barrier.wait, 0.5) self.run_threads(f)
'Test the barrier\'s default timeout'
def test_default_timeout(self):
barrier = self.barriertype(self.N, timeout=0.3) def f(): i = barrier.wait() if (i == (self.N // 2)): time.sleep(1.0) self.assertRaises(threading.BrokenBarrierError, barrier.wait) self.run_threads(f)
'Tests for changes for issue #16613.'
def test_new_child(self):
c = ChainMap() c['a'] = 1 c['b'] = 2 m = {'b': 20, 'c': 30} d = c.new_child(m) self.assertEqual(d.maps, [{'b': 20, 'c': 30}, {'a': 1, 'b': 2}]) self.assertIs(m, d.maps[0]) class lowerdict(dict, ): def __getitem__(self, key): if isinstance(key, str): ke...
'Constructor: Rat([num[, den]]). The arguments must be ints, and default to (0, 1).'
def __init__(self, num=0, den=1):
if (not isint(num)): raise TypeError(('Rat numerator must be int (%r)' % num)) if (not isint(den)): raise TypeError(('Rat denominator must be int (%r)' % den)) if (den == 0): raise ZeroDivisionError('zero denominator') g = gcd(den, num) self._...
'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)))
'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))
'Our byte strings are really encoded strings; improve diff output'
def assertBytesEqual(self, first, second, msg):
self.assertEqual(self._bytes_repr(first), self._bytes_repr(second))
'Test for parsing a date with a two-digit year. Parsing a date with a two-digit year should return the correct four-digit year. RFC822 allows two-digit years, but RFC2822 (which obsoletes RFC822) requires four-digit years.'
def test_parsedate_y2k(self):
self.assertEqual(utils.parsedate_tz('25 Feb 03 13:47:26 -0800'), utils.parsedate_tz('25 Feb 2003 13:47:26 -0800')) self.assertEqual(utils.parsedate_tz('25 Feb 71 13:47:26 -0800'), utils.parsedate_tz('25 Feb 1971 13:47:26 -0800'))
'Test proper handling of a nested comment'
def test_getaddresses_embedded_comment(self):
eq = self.assertEqual addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>']) eq(addrs[0][1], 'foo@bar.com')
'FeedParser BufferedSubFile.push() assumed it received complete line endings. A CR ending one push() followed by a LF starting the next push() added an empty line.'
def test_pushCR_LF(self):
imt = [('a\r \n', 2), ('b', 0), ('c\n', 1), ('', 0), ('d\r\n', 1), ('e\r', 0), ('\nf', 1), ('\r\n', 1)] from email.feedparser import BufferedSubFile, NeedMoreData bsf = BufferedSubFile() om = [] nt = 0 for (il, n) in imt: bsf.push(il) nt += n n1 = 0 for ol in i...
'Run \'script\' lines with pdb and the pdb \'commands\'.'
def run_pdb(self, script, commands):
filename = 'main.py' with open(filename, 'w') as f: f.write(textwrap.dedent(script)) self.addCleanup(support.unlink, filename) cmd = [sys.executable, '-m', 'pdb', filename] stdout = stderr = None with subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess....
'>>> print(TwoNames().f()) f'
def f(self):
return 'f'
'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))
'Test the normal data case on both master_fd and stdin.'
def test__copy_to_each(self):
(read_from_stdout_fd, mock_stdout_fd) = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd (mock_stdin_fd, write_to_stdin_fd) = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] os.write(masters[1], 'from master') os....
'Test the empty read EOF case on both master_fd and stdin.'
def test__copy_eof_on_all(self):
(read_from_stdout_fd, mock_stdout_fd) = self._pipe() pty.STDOUT_FILENO = mock_stdout_fd (mock_stdin_fd, write_to_stdin_fd) = self._pipe() pty.STDIN_FILENO = mock_stdin_fd socketpair = self._socketpair() masters = [s.fileno() for s in socketpair] os.close(masters[1]) socketpair[1].close()...
'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 range((sys.getrecursionlimit() + 1)): sys.settrace(self.trace) try: self.f() except ValueError: pass else: self.fail('exception not raised!') except RuntimeEr...
'>>> 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
'headers: list of RFC822-style \'Key: value\' strings'
def __init__(self, headers=[], url=None):
import email self._headers = email.message_from_string('\n'.join(headers)) self._url = url
'read_until(expected, timeout=None) test the blocking version of read_util'
def test_read_until(self):
want = ['xxxmatchyyy'] telnet = test_telnet(want) data = telnet.read_until('match') self.assertEqual(data, 'xxxmatch', msg=(telnet.cookedq, telnet.rawq, telnet.sock.reads)) reads = [('x' * 50), 'match', ('y' * 50)] expect = ''.join(reads[:(-1)]) telnet = test_telnet(reads) data = telnet....
'read_all() Read all data until EOF; may block.'
def test_read_all(self):
reads = [('x' * 500), ('y' * 500), ('z' * 500)] expect = ''.join(reads) telnet = test_telnet(reads) data = telnet.read_all() self.assertEqual(data, expect) return
'read_some() Read at least one byte or EOF; may block.'
def test_read_some(self):
telnet = test_telnet([('x' * 500)]) data = telnet.read_some() self.assertTrue((len(data) >= 1)) telnet = test_telnet() data = telnet.read_some() self.assertEqual('', data)
'read_*_eager() Read all data available already queued or on the socket, without blocking.'
def _read_eager(self, func_name):
want = ('x' * 100) telnet = test_telnet([want]) func = getattr(telnet, func_name) telnet.sock.block = True self.assertEqual('', func()) telnet.sock.block = False data = '' while True: try: data += func() except EOFError: break self.assertEqual(...
'helper for testing IAC + cmd'
def _test_command(self, data):
telnet = test_telnet(data) data_len = len(''.join(data)) 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[:1], self.cmds) self.assertEqual(cmd[1:2], tl.NOOPT) sel...
'expect(expected, [timeout]) Read until the expected string has been seen, or a timeout is hit (default is no timeout); may block.'
def test_expect(self):
want = [('x' * 10), 'match', ('y' * 10)] telnet = test_telnet(want) (_, _, data) = telnet.expect(['match']) self.assertEqual(data, ''.join(want[:(-1)]))
'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, 'Threading required for this test.') def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
read_results = [] def _read(): if hasattr(signal, 'pthread_sigmask'): signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGALRM]) s = os.read(r, 1) read_results.append(s) t = threading.Thread(target=_read) t.daemon = True (r, w) = os.pipe() fdopen_kwargs['close...