desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Restore the mock object to its initial state.'
def reset_mock(self):
self.called = False self.call_args = None self.call_count = 0 self.mock_calls = _CallList() self.call_args_list = _CallList() self.method_calls = _CallList() for child in self._mock_children.values(): if isinstance(child, _SpecState): continue child.reset_mock() ret = self._mock_return_value if (_is_instance_mock(ret) and (ret is not self)): ret.reset_mock()
'Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call: >>> attrs = {\'method.return_value\': 3, \'other.side_effect\': KeyError} >>> mock.configure_mock(**attrs)'
def configure_mock(self, **kwargs):
for (arg, val) in sorted(kwargs.items(), key=(lambda entry: entry[0].count('.'))): args = arg.split('.') final = args.pop() obj = self for entry in args: obj = getattr(obj, entry) setattr(obj, final, val)
'Filter the output of `dir(mock)` to only useful members.'
def __dir__(self):
if (not FILTER_DIR): return object.__dir__(self) extras = (self._mock_methods or []) from_type = dir(type(self)) from_dict = list(self.__dict__) from_type = [e for e in from_type if (not e.startswith('_'))] from_dict = [e for e in from_dict if ((not e.startswith('_')) or _is_magic(e))] return sorted(set((((extras + from_type) + from_dict) + list(self._mock_children))))
'Given a call (or simply a (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec\'s signature, if available, or falls back on the arguments themselves.'
def _call_matcher(self, _call):
sig = self._spec_signature if (sig is not None): if (len(_call) == 2): name = '' (args, kwargs) = _call else: (name, args, kwargs) = _call try: return (name, sig.bind(*args, **kwargs)) except TypeError as e: return e.with_traceback(None) else: return _call
'assert that the mock was never called.'
def assert_not_called(_mock_self):
self = _mock_self if (self.call_count != 0): msg = ("Expected '%s' to not have been called. Called %s times." % ((self._mock_name or 'mock'), self.call_count)) raise AssertionError(msg)
'assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.'
def assert_called_with(_mock_self, *args, **kwargs):
self = _mock_self if (self.call_args is None): expected = self._format_mock_call_signature(args, kwargs) raise AssertionError(('Expected call: %s\nNot called' % (expected,))) def _error_message(): msg = self._format_mock_failure_message(args, kwargs) return msg expected = self._call_matcher((args, kwargs)) actual = self._call_matcher(self.call_args) if (expected != actual): raise AssertionError(_error_message())
'assert that the mock was called exactly once and with the specified arguments.'
def assert_called_once_with(_mock_self, *args, **kwargs):
self = _mock_self if (not (self.call_count == 1)): msg = ("Expected '%s' to be called once. Called %s times." % ((self._mock_name or 'mock'), self.call_count)) raise AssertionError(msg) return self.assert_called_with(*args, **kwargs)
'assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls can be in any order, but they must all appear in `mock_calls`.'
def assert_has_calls(self, calls, any_order=False):
expected = [self._call_matcher(c) for c in calls] all_calls = _CallList((self._call_matcher(c) for c in self.mock_calls)) if (not any_order): if (expected not in all_calls): raise AssertionError(('Calls not found.\nExpected: %r\nActual: %r' % (calls, self.mock_calls))) return all_calls = list(all_calls) not_found = [] for kall in expected: try: all_calls.remove(kall) except ValueError: not_found.append(kall) if not_found: raise AssertionError(('%r not all found in call list' % (tuple(not_found),)))
'assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.'
def assert_any_call(self, *args, **kwargs):
expected = self._call_matcher((args, kwargs)) actual = [self._call_matcher(c) for c in self.call_args_list] if (expected not in actual): expected_string = self._format_mock_call_signature(args, kwargs) raise AssertionError(('%s call not found' % expected_string))
'Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. For non-callable mocks the callable variant will be used (rather than any custom subclass).'
def _get_child_mock(self, **kw):
_type = type(self) if (not issubclass(_type, CallableMixin)): if issubclass(_type, NonCallableMagicMock): klass = MagicMock elif issubclass(_type, NonCallableMock): klass = Mock else: klass = _type.__mro__[1] return klass(**kw)
'Perform the patch.'
def __enter__(self):
(new, spec, spec_set) = (self.new, self.spec, self.spec_set) (autospec, kwargs) = (self.autospec, self.kwargs) new_callable = self.new_callable self.target = self.getter() if (spec is False): spec = None if (spec_set is False): spec_set = None if (autospec is False): autospec = None if ((spec is not None) and (autospec is not None)): raise TypeError("Can't specify spec and autospec") if (((spec is not None) or (autospec is not None)) and (spec_set not in (True, None))): raise TypeError("Can't provide explicit spec_set *and* spec or autospec") (original, local) = self.get_original() if ((new is DEFAULT) and (autospec is None)): inherit = False if (spec is True): spec = original if (spec_set is True): spec_set = original spec = None elif (spec is not None): if (spec_set is True): spec_set = spec spec = None elif (spec_set is True): spec_set = original if ((spec is not None) or (spec_set is not None)): if (original is DEFAULT): raise TypeError("Can't use 'spec' with create=True") if isinstance(original, type): inherit = True Klass = MagicMock _kwargs = {} if (new_callable is not None): Klass = new_callable elif ((spec is not None) or (spec_set is not None)): this_spec = spec if (spec_set is not None): this_spec = spec_set if _is_list(this_spec): not_callable = ('__call__' not in this_spec) else: not_callable = (not callable(this_spec)) if not_callable: Klass = NonCallableMagicMock if (spec is not None): _kwargs['spec'] = spec if (spec_set is not None): _kwargs['spec_set'] = spec_set if (isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) new = Klass(**_kwargs) if (inherit and _is_instance_mock(new)): this_spec = spec if (spec_set is not None): this_spec = spec_set if ((not _is_list(this_spec)) and (not _instance_callable(this_spec))): Klass = NonCallableMagicMock _kwargs.pop('name') new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) elif (autospec is not None): if (new is not DEFAULT): raise TypeError("autospec creates the mock for you. Can't specify autospec and new.") if (original is DEFAULT): raise TypeError("Can't use 'autospec' with create=True") spec_set = bool(spec_set) if (autospec is True): autospec = original new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) elif kwargs: raise TypeError("Can't pass kwargs to a mock we aren't creating") new_attr = new self.temp_original = original self.is_local = local setattr(self.target, self.attribute, new_attr) if (self.attribute_name is not None): extra_args = {} if (self.new is DEFAULT): extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = patching.__enter__() if (patching.new is DEFAULT): extra_args.update(arg) return extra_args return new
'Undo the patch.'
def __exit__(self, *exc_info):
if (not _is_started(self)): raise RuntimeError('stop called on unstarted patcher') if (self.is_local and (self.temp_original is not DEFAULT)): setattr(self.target, self.attribute, self.temp_original) else: delattr(self.target, self.attribute) if ((not self.create) and (not hasattr(self.target, self.attribute))): setattr(self.target, self.attribute, self.temp_original) del self.temp_original del self.is_local del self.target for patcher in reversed(self.additional_patchers): if _is_started(patcher): patcher.__exit__(*exc_info)
'Activate a patch, returning any created mock.'
def start(self):
result = self.__enter__() self._active_patches.append(self) return result
'Stop an active patch.'
def stop(self):
try: self._active_patches.remove(self) except ValueError: pass return self.__exit__()
'Patch the dict.'
def __enter__(self):
self._patch_dict()
'Unpatch the dict.'
def __exit__(self, *args):
self._unpatch_dict() return False
'Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.'
def mock_add_spec(self, spec, spec_set=False):
self._mock_add_spec(spec, spec_set) self._mock_set_magics()
'Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.'
def mock_add_spec(self, spec, spec_set=False):
self._mock_add_spec(spec, spec_set) self._mock_set_magics()
'For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call.'
def call_list(self):
vals = [] thing = self while (thing is not None): if thing.from_kall: vals.append(thing) thing = thing.parent return _CallList(reversed(vals))
'>>> 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 i=\'x?a=b&c=d;\'\n j=\'&amp;#42;\' k=\'&#38;#42;\'>', [('starttag', 'a', [('b', '<'), ('c', '<>'), ('d', '&lt->'), ('e', '< '), ('f', '&xxx;'), ('g', ' !'), ('h', '&#500;'), ('i', 'x?a=b&c=d;'), ('j', '&#42;'), ('k', '&#42;')])])
'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)]))
'Use select.poll() to implement telnet.read_until().'
def test_read_until_with_poll(self):
want = [('x' * 10), 'match', ('y' * 10), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) if (not telnet._has_poll): raise unittest.SkipTest('select.poll() is required') telnet._has_poll = True self.dataq.join() data = telnet.read_until('match') self.assertEqual(data, ''.join(want[:(-2)]))
'Use select.select() to implement telnet.read_until().'
def test_read_until_with_select(self):
want = [('x' * 10), 'match', ('y' * 10), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) telnet._has_poll = False 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)]))
'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.assertTrue(expects.startswith(data)) except EOFError: break self.assertEqual(expects, data)
'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) self.assertEqual(cmd[1], tl.NOOPT) self.assertEqual(len(''.join(data[:(-1)])), len((txt + cmd))) nego.sb_getter = None self.tearDown()
'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_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.expect(['match']) self.assertEqual(data, ''.join(want[:(-2)]))
'Use select.poll() to implement telnet.expect().'
def test_expect_with_poll(self):
want = [('x' * 10), 'match', ('y' * 10), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) if (not telnet._has_poll): raise unittest.SkipTest('select.poll() is required') telnet._has_poll = True self.dataq.join() (_, _, data) = telnet.expect(['match']) self.assertEqual(data, ''.join(want[:(-2)]))
'Use select.select() to implement telnet.expect().'
def test_expect_with_select(self):
want = [('x' * 10), 'match', ('y' * 10), EOF_sigil] self.dataq.put(want) telnet = telnetlib.Telnet(HOST, self.port) telnet._has_poll = False self.dataq.join() (_, _, data) = telnet.expect(['match']) self.assertEqual(data, ''.join(want[:(-2)]))
'A version of pkgutil.walk_packages() that will restrict itself to a given path.'
def _restricted_walk_packages(self, walk_packages, path=None):
default_path = (path or [os.path.dirname(__file__)]) def wrapper(path=None, prefix='', onerror=None): return walk_packages((path or default_path), prefix, onerror) return wrapper
'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: The pickled data received from the child process.'
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) if (worker.returncode != 0): raise RuntimeError(stderr) return stdout
'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 far to include in the error message. communicate: bool, when True we call communicate() on the process after killing it to gather additional output.'
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 from IO process %s:\nSTDOUT:\n%sSTDERR:\n%s\n' % (why, stdout.decode(), stderr.decode())))
'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 pipe. read_and_verify_code: Single "line" of code to read from a file object named \'infile\' and validate the result. This will be executed as part of a python subprocess fed data_to_write.'
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 io, signal, sys ;signal.signal(signal.SIGINT, lambda s, f: sys.stderr.write("$\\n")) ;' + infile_setup_code) + ' ;') + 'sys.stderr.write("Worm Sign!\\n") ;') + read_and_verify_code) + ' ;') + 'infile.close()')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) worm_sign = self._process.stderr.read(len('Worm Sign!\n')) if (worm_sign != 'Worm Sign!\n'): self.fail_with_process_info('while awaiting a sign', stderr=worm_sign) self._process.stdin.write(data_to_write) signals_sent = 0 rlist = [] while (not rlist): (rlist, _, _) = select.select([self._process.stderr], (), (), 0.05) self._process.send_signal(signal.SIGINT) signals_sent += 1 if (signals_sent > 200): self._process.kill() self.fail('reader process failed to handle our signals.') signal_line = self._process.stderr.readline() if (signal_line != '$\n'): self.fail_with_process_info('while awaiting signal', stderr=signal_line) (stdout, stderr) = self._process.communicate(input='\n') if self._process.returncode: self.fail_with_process_info(('exited rc=%d' % self._process.returncode), stdout, stderr, communicate=False)
'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\nworld!\n'))
'Returns the infile = ... line of code to make a BufferedReader.'
def _generate_infile_setup_code(self):
return 'infile = io.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 = io.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'))
'Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)'
def translate_path(self, path):
path = urlparse.urlparse(path)[2] path = os.path.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = self.root for word in words: (drive, word) = os.path.splitdrive(word) (head, word) = os.path.split(word) path = os.path.join(path, word) return path
'Serve a GET request.'
def do_GET(self, send_body=True):
sock = self.rfile.raw._sock context = sock.context stats = {'session_cache': context.session_stats(), 'cipher': sock.cipher(), 'compression': sock.compression()} body = pprint.pformat(stats) body = body.encode('utf-8') self.send_response(200) self.send_header('Content-type', 'text/plain; charset=utf-8') self.send_header('Content-Length', str(len(body))) self.end_headers() if send_body: self.wfile.write(body)
'Serve a HEAD request.'
def do_HEAD(self):
self.do_GET(send_body=False)
'Test an empty maildir mailbox'
def test_empty_maildir(self):
self.mbox = mailbox.Maildir(test_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 = cStringIO.StringIO() try: exec code in d exec compile(str, '<input>', 'single') in r finally: sys.stdout = saved_stdout elif (symbol == 'eval'): ctx = {'a': 2} d = {'value': eval(code, ctx)} r = {'value': eval(str, ctx)} self.assertEqual(unify_callables(r), unify_callables(d)) else: expected = compile(str, '<input>', symbol, PyCF_DONT_IMPLY_DEDENT) self.assertEqual(compile_command(str, '<input>', symbol), expected)
'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))
'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.port))
'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_numeric_err_msg % (calc_value, known_value, calc_type, data_type, set_locale, used_locale))) return True
'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) self.bad_dir_path = os.path.join(self.base_dir, self.bad_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.good_dir_path)
'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 os.path.exists(self.good_dir_path): os.rmdir(self.good_dir_path) if os.path.exists(self.bad_dir_path): os.rmdir(self.bad_dir_path)
'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
'Test roundtrip for `untokenize`. `f` is an open file or a string. The source code in f is tokenized, converted back to source code via tokenize.untokenize(), and tokenized again from the latter. The test fails if the second tokenization doesn\'t match the first.'
def check_roundtrip(self, f):
if isinstance(f, str): f = StringIO(f) token_list = list(generate_tokens(f.readline)) f.close() tokens1 = [tok[:2] for tok in token_list] new_text = untokenize(tokens1) readline = iter(new_text.splitlines(1)).next tokens2 = [tok[:2] for tok in generate_tokens(readline)] self.assertEqual(tokens2, tokens1)
'Ensure that although whitespace might be mutated in a roundtrip, the semantic meaning of the indentation remains consistent.'
def test_indentation_semantics_retained(self):
code = 'if False:\n DCTB x=3\n DCTB x=3\n' codelines = self.roundtrip(code).split('\n') self.assertEqual(codelines[1], codelines[2])
'Wow, I have no function!'
def __init__():
pass
'Return say_no()'
def get_answer(self):
return self.say_no()
'Return self.get_answer()'
def is_it_true(self):
return self.get_answer()
'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(n), long) self.assertEqual(type(int(n)), type(n))
'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 not contain '%r'" % (err, errtext))) else: self.fail('compile() did not raise SyntaxError')
'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 {}: expected {}, got {}'.format(s, expected, got))
'Test for the fork() failure fd leak reported in issue16327.'
@unittest.skipUnless(os.path.isdir(('/proc/%d/fd' % os.getpid())), 'Linux specific') def test_failed_child_execute_fd_leak(self):
fd_directory = ('/proc/%d/fd' % os.getpid()) fds_before_popen = os.listdir(fd_directory) with self.assertRaises(PopenTestException): PopenExecuteChildRaises([sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) fds_after_exception = os.listdir(fd_directory) self.assertEqual(fds_before_popen, fds_after_exception)
'Try to save previous ulimit, then set it to (0, 0).'
def __enter__(self):
if (resource is not None): try: self.old_limit = resource.getrlimit(resource.RLIMIT_CORE) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) except (ValueError, resource.error): pass if (sys.platform == 'darwin'): value = subprocess.Popen(['/usr/bin/defaults', 'read', 'com.apple.CrashReporter', 'DialogType'], stdout=subprocess.PIPE).communicate()[0] if (value.strip() == 'developer'): print 'this tests triggers the Crash Reporter, that is intentional' sys.stdout.flush()
'Return core file behavior to default.'
def __exit__(self, *args):
if (self.old_limit is None): return if (resource is not None): try: resource.setrlimit(resource.RLIMIT_CORE, self.old_limit) except (ValueError, resource.error): pass
'Issue16140: Don\'t double close pipes on preexec error.'
@unittest.skipIf((not os.path.exists('/dev/zero')), '/dev/zero required.') def test_preexec_errpipe_does_not_double_close_pipes(self):
def raise_it(): raise RuntimeError('force the _execute_child() errpipe_data path.') with self.assertRaises(RuntimeError): self._TestExecuteChildPopen(self, [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=raise_it)
'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 between 9 and 19 ulps.'
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, b))) if ((not a) and (not b)): if (math.copysign(1.0, a) != math.copysign(1.0, b)): self.fail((msg or 'zero has wrong sign: expected {!r}, got {!r}'.format(a, b))) try: absolute_error = abs((b - a)) except OverflowError: pass else: if (absolute_error <= max(abs_err, (rel_err * abs(a)))): return self.fail((msg or '{!r} and {!r} are not sufficiently close'.format(a, b)))
'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) self.assertEqual(new_callers, {'a': 2, 'b': 5})
'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.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=None) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), None) httpConn.close() httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) httpConn.connect() 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)]
'Records \'timer\' and returns self as callable timer.'
def wrap_timer(self, timer):
self.saved_timer = timer return self
'Check that trying to use the given client certificate fails'
def bad_cert_test(self, certfile):
certfile = os.path.join((os.path.dirname(__file__) or os.curdir), certfile) sock = socket.socket() self.addCleanup(sock.close) with self.assertRaises(ssl.SSLError): ssl.wrap_socket(sock, certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1)
'Wrapping with an empty cert file'
def test_empty_cert(self):
self.bad_cert_test('nullcert.pem')
'Wrapping with a badly formatted certificate (syntax error)'
def test_malformed_cert(self):
self.bad_cert_test('badcert.pem')
'Wrapping with a badly formatted key (syntax error)'
def test_malformed_key(self):
self.bad_cert_test('badkey.pem')
'Test the methods of windows'
def test_window_funcs(self):
stdscr = self.stdscr win = curses.newwin(10, 10) win = curses.newwin(5, 5, 5, 5) win2 = curses.newwin(15, 15, 5, 5) for meth in [stdscr.addch, stdscr.addstr]: for args in ['a', ('a', curses.A_BOLD), (4, 4, 'a'), (5, 5, 'a', curses.A_BOLD)]: meth(*args) for meth in [stdscr.box, stdscr.clear, stdscr.clrtobot, stdscr.clrtoeol, stdscr.cursyncup, stdscr.delch, stdscr.deleteln, stdscr.erase, stdscr.getbegyx, stdscr.getbkgd, stdscr.getkey, stdscr.getmaxyx, stdscr.getparyx, stdscr.getyx, stdscr.inch, stdscr.insertln, stdscr.instr, stdscr.is_wintouched, win.noutrefresh, stdscr.redrawwin, stdscr.refresh, stdscr.standout, stdscr.standend, stdscr.syncdown, stdscr.syncup, stdscr.touchwin, stdscr.untouchwin]: meth() stdscr.addnstr('1234', 3) stdscr.addnstr('1234', 3, curses.A_BOLD) stdscr.addnstr(4, 4, '1234', 3) stdscr.addnstr(5, 5, '1234', 3, curses.A_BOLD) stdscr.attron(curses.A_BOLD) stdscr.attroff(curses.A_BOLD) stdscr.attrset(curses.A_BOLD) stdscr.bkgd(' ') stdscr.bkgd(' ', curses.A_REVERSE) stdscr.bkgdset(' ') stdscr.bkgdset(' ', curses.A_REVERSE) win.border(65, 66, 67, 68, 69, 70, 71, 72) win.border('|', '!', '-', '_', '+', '\\', '#', '/') with self.assertRaises(TypeError, msg='Expected win.border() to raise TypeError'): win.border(65, 66, 67, 68, 69, [], 71, 72) stdscr.clearok(1) win4 = stdscr.derwin(2, 2) win4 = stdscr.derwin(1, 1, 5, 5) win4.mvderwin(9, 9) stdscr.echochar('a') stdscr.echochar('a', curses.A_BOLD) stdscr.hline('-', 5) stdscr.hline('-', 5, curses.A_BOLD) stdscr.hline(1, 1, '-', 5) stdscr.hline(1, 1, '-', 5, curses.A_BOLD) stdscr.idcok(1) stdscr.idlok(1) stdscr.immedok(1) stdscr.insch('c') stdscr.insdelln(1) stdscr.insnstr('abc', 3) stdscr.insnstr('abc', 3, curses.A_BOLD) stdscr.insnstr(5, 5, 'abc', 3) stdscr.insnstr(5, 5, 'abc', 3, curses.A_BOLD) stdscr.insstr('def') stdscr.insstr('def', curses.A_BOLD) stdscr.insstr(5, 5, 'def') stdscr.insstr(5, 5, 'def', curses.A_BOLD) stdscr.is_linetouched(0) stdscr.keypad(1) stdscr.leaveok(1) stdscr.move(3, 3) win.mvwin(2, 2) stdscr.nodelay(1) stdscr.notimeout(1) win2.overlay(win) win2.overwrite(win) win2.overlay(win, 1, 2, 2, 1, 3, 3) win2.overwrite(win, 1, 2, 2, 1, 3, 3) stdscr.redrawln(1, 2) stdscr.scrollok(1) stdscr.scroll() stdscr.scroll(2) stdscr.scroll((-3)) stdscr.move(12, 2) stdscr.setscrreg(10, 15) win3 = stdscr.subwin(10, 10) win3 = stdscr.subwin(10, 10, 5, 5) stdscr.syncok(1) stdscr.timeout(5) stdscr.touchline(5, 5) stdscr.touchline(5, 5, 0) stdscr.vline('a', 3) stdscr.vline('a', 3, curses.A_STANDOUT) stdscr.chgat(5, 2, 3, curses.A_BLINK) stdscr.chgat(3, curses.A_BOLD) stdscr.chgat(5, 8, curses.A_UNDERLINE) stdscr.chgat(curses.A_BLINK) stdscr.refresh() stdscr.vline(1, 1, 'a', 3) stdscr.vline(1, 1, 'a', 3, curses.A_STANDOUT) if hasattr(curses, 'resize'): stdscr.resize() if hasattr(curses, 'enclose'): stdscr.enclose()
'Test module-level functions'
def test_module_funcs(self):
for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() if curses.tigetstr('cnorm'): curses.curs_set(1) curses.delay_output(1) curses.echo() curses.echo(1) with tempfile.TemporaryFile() as f: self.stdscr.putwin(f) f.seek(0) curses.getwin(f) curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50, 50) win = curses.newwin(5, 5) win = curses.newwin(5, 5, 1, 1) curses.nl() curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() curses.raw(1) curses.setsyx(5, 5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1)