desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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... |
'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['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(6... |
'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, 'Threading required for this test.')
def check_interrupted_write_retry(self, item, **fdopen_kwargs):
| select = support.import_module('select')
N = support.PIPE_MAX_SIZE
(r, w) = os.pipe()
fdopen_kwargs['closefd'] = False
read_results = []
write_finished = False
def _read():
while (not write_finished):
while (r in select.select([r], [], [], 1.0)[0]):
s = os... |
'Minimal test of DOMEventStream.parse()'
| def test_parse(self):
| handler = pulldom.parse(tstfile)
self.addCleanup(handler.stream.close)
list(handler)
with open(tstfile, 'rb') as fin:
list(pulldom.parse(fin))
|
'Test DOMEventStream parsing semantics.'
| def test_parse_semantics(self):
| items = pulldom.parseString(SMALL_SAMPLE)
(evt, node) = next(items)
self.assertTrue(hasattr(node, 'createElement'))
self.assertEqual(pulldom.START_DOCUMENT, evt)
(evt, node) = next(items)
self.assertEqual(pulldom.START_ELEMENT, evt)
self.assertEqual('html', node.tagName)
self.assertEqual... |
'Ensure expandItem works as expected.'
| def test_expandItem(self):
| items = pulldom.parseString(SMALL_SAMPLE)
for (evt, item) in items:
if ((evt == pulldom.START_ELEMENT) and (item.tagName == 'title')):
items.expandNode(item)
self.assertEqual(1, len(item.childNodes))
break
else:
self.fail('No "title" element detec... |
'PullDOM does not receive "comment" events.'
| @unittest.expectedFailure
def test_comment(self):
| items = pulldom.parseString(SMALL_SAMPLE)
for (evt, _) in items:
if (evt == pulldom.COMMENT):
break
else:
self.fail('No comment was encountered')
|
'PullDOM does not receive "end-document" events.'
| @unittest.expectedFailure
def test_end_document(self):
| items = pulldom.parseString(SMALL_SAMPLE)
for (evt, node) in items:
if ((evt == pulldom.END_ELEMENT) and (node.tagName == 'html')):
break
try:
(evt, node) = next(items)
self.assertEqual(pulldom.END_DOCUMENT, evt)
except StopIteration:
self.fail('Ran out ... |
'Test some of the hard-to-reach parts of PullDOM.'
| def test_thorough_parse(self):
| self._test_thorough(pulldom.parse(None, parser=SAXExerciser()))
|
'SAX2DOM can"t handle a PI before the root element.'
| @unittest.expectedFailure
def test_sax2dom_fail(self):
| pd = SAX2DOMTestHelper(None, SAXExerciser(), 12)
self._test_thorough(pd)
|
'Test some of the hard-to-reach parts of SAX2DOM.'
| def test_thorough_sax2dom(self):
| pd = SAX2DOMTestHelper(None, SAX2DOMExerciser(), 12)
self._test_thorough(pd, False)
|
'Test some of the hard-to-reach parts of the parser, using a mock
parser.'
| def _test_thorough(self, pd, before_root=True):
| (evt, node) = next(pd)
self.assertEqual(pulldom.START_DOCUMENT, evt)
self.assertTrue(hasattr(node, 'createElement'))
if before_root:
(evt, node) = next(pd)
self.assertEqual(pulldom.COMMENT, evt)
self.assertEqual('a comment', node.data)
(evt, node) = next(pd)
se... |
'Stub method. Does nothing.'
| def stub(self, *args, **kwargs):
| pass
|
'Ensure SAX2DOM can parse from a stream.'
| def test_basic(self):
| with io.StringIO(SMALL_SAMPLE) as fin:
sd = SAX2DOMTestHelper(fin, xml.sax.make_parser(), len(SMALL_SAMPLE))
for (evt, node) in sd:
if ((evt == pulldom.START_ELEMENT) and (node.tagName == 'html')):
break
self.assertGreater(len(node.childNodes), 0)
|
'Ensure SAX2DOM expands nodes as expected.'
| def testSAX2DOM(self):
| sax2dom = pulldom.SAX2DOM()
sax2dom.startDocument()
sax2dom.startElement('doc', {})
sax2dom.characters('text')
sax2dom.startElement('subelm', {})
sax2dom.characters('text')
sax2dom.endElement('subelm')
sax2dom.characters('text')
sax2dom.endElement('doc')
sax2dom.endDocument()
... |
'Returns the infile = ... line of code for the reader process.
subclasseses should override this to test different IO objects.'
| def _generate_infile_setup_code(self):
| return 'import _io ;infile = _io.FileIO(sys.stdin.fileno(), "rb")'
|
'A common way to cleanup and fail with useful debug output.
Kills the process if it is still running, collects remaining output
and fails the test with an error message including the output.
Args:
why: Text to go after "Error from IO process" in the message.
stdout, stderr: standard output and error from the process so... | def fail_with_process_info(self, why, stdout='', stderr='', communicate=True):
| if (self._process.poll() is None):
time.sleep(0.1)
try:
self._process.terminate()
except OSError:
pass
if communicate:
(stdout_end, stderr_end) = self._process.communicate()
stdout += stdout_end
stderr += stderr_end
self.fail(('Error ... |
'Generic buffered read method test harness to validate EINTR behavior.
Also validates that Python signal handlers are run during the read.
Args:
data_to_write: String to write to the child process for reading
before sending it a signal, confirming the signal was handled,
writing a final newline and closing the infile p... | def _test_reading(self, data_to_write, read_and_verify_code):
| infile_setup_code = self._generate_infile_setup_code()
assert (len(data_to_write) < 512), 'data_to_write must fit in pipe buf.'
self._process = subprocess.Popen([sys.executable, '-u', '-c', (((((('import signal, sys ;signal.signal(signal.SIGINT, lambda s, f: sys.stderr.wr... |
'readline() must handle signals and not lose data.'
| def test_readline(self):
| self._test_reading(data_to_write='hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readline', expected='hello, world!\n'))
|
'readlines() must handle signals and not lose data.'
| def test_readlines(self):
| self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readlines', expected=['hello\n', 'world!\n']))
|
'readall() must handle signals and not lose data.'
| def test_readall(self):
| self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readall', expected='hello\nworld!\n'))
self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nw... |
'Returns the infile = ... line of code to make a BufferedReader.'
| def _generate_infile_setup_code(self):
| return 'infile = open(sys.stdin.fileno(), "rb") ;import _io ;assert isinstance(infile, _io.BufferedReader)'
|
'BufferedReader.read() must handle signals and not lose data.'
| def test_readall(self):
| self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nworld!\n'))
|
'Returns the infile = ... line of code to make a TextIOWrapper.'
| def _generate_infile_setup_code(self):
| return 'infile = open(sys.stdin.fileno(), "rt", newline=None) ;import _io ;assert isinstance(infile, _io.TextIOWrapper)'
|
'readline() must handle signals and not lose data.'
| def test_readline(self):
| self._test_reading(data_to_write='hello, world!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readline', expected='hello, world!\n'))
|
'readlines() must handle signals and not lose data.'
| def test_readlines(self):
| self._test_reading(data_to_write='hello\r\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='readlines', expected=['hello\n', 'world!\n']))
|
'read() must handle signals and not lose data.'
| def test_readall(self):
| self._test_reading(data_to_write='hello\nworld!', read_and_verify_code=self._READING_CODE_TEMPLATE.format(read_method_name='read', expected='hello\nworld!\n'))
|
'Test an empty maildir mailbox'
| def test_empty_maildir(self):
| self.mbox = mailbox.Maildir(support.TESTFN)
self.assertIsNone(self.mbox.next())
self.assertIsNone(self.mbox.next())
|
'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 = io.StringIO()
try:
exec code in d
exec compile(... |
'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 raised for invalid code')
except SyntaxError:
self.assertTrue(is_syntax)
except OverflowError:
self.assertTrue((not is_syntax))
|
'The testcase fails if no exception is raised when a filename parameter provided to binhex.binhex()
is too long, or if the exception raised in binhex.binhex() is not an instance of binhex.Error.'
| def test_binhex_error_on_long_filename(self):
| f3 = open(self.fname3, 'wb')
f3.close()
self.assertRaises(binhex.Error, binhex.binhex, self.fname3, self.fname2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.