我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用six.moves.builtins()。
def testEmptyJSON(self): """ If the specification file is empty, a ValueError must be raised. """ data = '' mockOpener = mockOpen(read_data=data) with patch.object(builtins, 'open', mockOpener): if PY3: error = '^Expecting value: line 1 column 1 \(char 0\)$' elif PYPY: # The error message in the exception has a NUL in it. error = ("^No JSON object could be decoded: unexpected " "'\\000' at char 0$") else: error = '^No JSON object could be decoded$' assertRaisesRegex(self, ValueError, error, SlurmPipelineBase, 'file')
def testInvalidJSON(self): """ If the specification file does not contain valid JSON, a ValueError must be raised. """ data = '{' mockOpener = mockOpen(read_data=data) with patch.object(builtins, 'open', mockOpener): if PY3: error = ('^Expecting property name enclosed in double ' 'quotes: line 1 column 2 \(char 1\)$') elif PYPY: # The error message in the exception has a NUL in it. error = ("^No JSON object could be decoded: unexpected " "'\\000' at char 0$") else: error = '^Expecting object: line 1 column 1 \(char 0\)$' assertRaisesRegex(self, ValueError, error, SlurmPipelineBase, 'file')
def __call__(self, result=None, runcondition=None, options=None):\ # pylint: disable=W0613 try: finder = DocTestFinder(skipped=self.skipped) suite = doctest.DocTestSuite(self.module, test_finder=finder) # XXX iirk doctest.DocTestCase._TestCase__exc_info = sys.exc_info except AttributeError: suite = SkippedSuite() # doctest may gork the builtins dictionnary # This happen to the "_" entry used by gettext old_builtins = builtins.__dict__.copy() try: return suite.run(result) finally: builtins.__dict__.clear() builtins.__dict__.update(old_builtins)
def setUp(self): super(HyperVBaseTestCase, self).setUp() self._mock_wmi = mock.MagicMock() wmi_patcher = mock.patch.object(builtins, 'wmi', create=True, new=self._mock_wmi) platform_patcher = mock.patch('sys.platform', 'win32') utilsfactory_patcher = mock.patch.object(utilsfactory, '_get_class') platform_patcher.start() wmi_patcher.start() utilsfactory_patcher.start() self.addCleanup(wmi_patcher.stop) self.addCleanup(platform_patcher.stop) self.addCleanup(utilsfactory_patcher.stop)
def handle_option_and_arg_data(data): data = data or {} if 'type' in data: data['type'] = getattr(builtins, data['type']) if 'help_text' in data: data['help'] = data.pop('help_text') return data
def test_virtual_function(self, mock_readlink, *args): mock_readlink.return_value = '../../../0000.00.00.1' with mock.patch.object(builtins, 'open', side_effect=IOError()): address, physical_function = utils.get_function_by_ifname('eth0') self.assertEqual(address, '0000.00.00.1') self.assertFalse(physical_function)
def test_physical_function(self, mock_readlink, *args): ifname = 'eth0' totalvf_path = "/sys/class/net/%s/device/%s" % (ifname, utils._SRIOV_TOTALVFS) mock_readlink.return_value = '../../../0000:00:00.1' with mock.patch.object(builtins, 'open', mock.mock_open(read_data='4')) as mock_open: address, physical_function = utils.get_function_by_ifname('eth0') self.assertEqual(address, '0000:00:00.1') self.assertTrue(physical_function) mock_open.assert_called_once_with(totalvf_path)
def test_virtual_function(self, *args): with mock.patch.object(builtins, 'open', side_effect=IOError()): self.assertFalse(utils.is_physical_function(*self.pci_args))
def test_physical_function(self, *args): with mock.patch.object(builtins, 'open', mock.mock_open(read_data='4')): self.assertTrue(utils.is_physical_function(*self.pci_args))
def __init__(self, class_names, currmodule, show_builtins=False, private_bases=False, parts=0): """*class_names* is a list of child classes to show bases from. If *show_builtins* is True, then Python builtins will be shown in the graph. """ self.class_names = class_names classes = self._import_classes(class_names, currmodule) self.class_info = self._class_info(classes, show_builtins, private_bases, parts) if not self.class_info: raise InheritanceException('No classes found for ' 'inheritance diagram')
def class_name(self, cls, parts=0): """Given a class object, return a fully-qualified name. This works for things I've tested in matplotlib so far, but may not be completely general. """ module = cls.__module__ if module in ('__builtin__', 'builtins'): fullname = cls.__name__ else: fullname = '%s.%s' % (module, cls.__name__) if parts == 0: return fullname name_parts = fullname.split('.') return '.'.join(name_parts[-parts:])
def is_builtin_class_method(obj, attr_name): """If attr_name is implemented at builtin class, return True. >>> is_builtin_class_method(int, '__init__') True Why this function needed? CPython implements int.__init__ by Descriptor but PyPy implements it by pure Python code. """ classes = [c for c in inspect.getmro(obj) if attr_name in c.__dict__] cls = classes[0] if classes else object if not hasattr(builtins, safe_getattr(cls, '__name__', '')): return False return getattr(builtins, safe_getattr(cls, '__name__', '')) is cls
def testJSONList(self): """ If the specification file contains valid JSON but is a list instead of a JSON object, a SpecificationError must be raised. """ data = '[]' mockOpener = mockOpen(read_data=data) with patch.object(builtins, 'open', mockOpener): error = ('^The specification must be a dict \(i\.e\., a JSON ' 'object when loaded from a file\)$') assertRaisesRegex(self, SpecificationError, error, SlurmPipelineBase, 'file')
def testSpecificationIsStored(self): """ If well-formed JSON is passed, it must be read and stored as the specification. The 'steps' list must be converted to a dict. """ specification = { 'steps': [ { 'name': 'name1', 'script': 'script1', }, { 'name': 'name2', 'script': 'script2', }, ], } data = dumps(specification) mockOpener = mockOpen(read_data=data) with patch.object(builtins, 'open', mockOpener): spb = SlurmPipelineBase('file') expected = { 'steps': { 'name1': { 'name': 'name1', 'script': 'script1', }, 'name2': { 'name': 'name2', 'script': 'script2', }, }, } self.assertEqual(expected, spb.specification)
def patch_input(**kwargs): """A helper to provide mocked cm patching input function which was renamed in PY3""" return patch.object(__builtin__, 'raw_input' if PY2 else 'input', **kwargs)
def test_get_instances_sub_dir(self, fake_path_join): class WindowsError(Exception): def __init__(self, winerror=None): self.winerror = winerror fake_dir_name = "fake_dir_name" fake_windows_error = WindowsError self._pathutils.check_create_dir = mock.MagicMock( side_effect=WindowsError(pathutils.ERROR_INVALID_NAME)) with mock.patch.object(builtins, 'WindowsError', fake_windows_error, create=True): self.assertRaises(exception.AdminRequired, self._pathutils._get_instances_sub_dir, fake_dir_name)
def _class_info(self, classes, show_builtins, private_bases, parts): """Return name and bases for all classes that are ancestors of *classes*. *parts* gives the number of dotted name parts that is removed from the displayed node names. """ all_classes = {} py_builtins = vars(builtins).values() def recurse(cls): if not show_builtins and cls in py_builtins: return if not private_bases and cls.__name__.startswith('_'): return nodename = self.class_name(cls, parts) fullname = self.class_name(cls, 0) # Use first line of docstring as tooltip, if available tooltip = None try: if cls.__doc__: enc = ModuleAnalyzer.for_module(cls.__module__).encoding doc = cls.__doc__.strip().split("\n")[0] if not isinstance(doc, text_type): doc = force_decode(doc, enc) if doc: tooltip = '"%s"' % doc.replace('"', '\\"') except Exception: # might raise AttributeError for strange classes pass baselist = [] all_classes[cls] = (nodename, fullname, baselist, tooltip) for base in cls.__bases__: if not show_builtins and base in py_builtins: continue if not private_bases and base.__name__.startswith('_'): continue baselist.append(self.class_name(base, parts)) if base not in all_classes: recurse(base) for cls in classes: recurse(cls) return list(all_classes.values())
def __deserialize(self, data, klass): """ Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if type(klass) == str: if klass.startswith('list['): sub_kls = re.match('list\[(.*)\]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} # convert str to class # for native types if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = getattr(__builtin__, klass) else: klass = getattr(models, klass, None) or getattr( extensions_beta, klass, None) or getattr(batch, klass) if klass in [int, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) elif klass == date: return self.__deserialize_date(data) elif klass == datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass)