def get_platform_subclass(cls): ''' Finds a subclass implementing desired functionality on the platform the code is running on :arg cls: Class to find an appropriate subclass for :returns: A class that implements the functionality on this platform Some Ansible modules have different implementations depending on the platform they run on. This function is used to select between the various implementations and choose one. You can look at the implementation of the Ansible :ref:`User module<user_module>` module for an example of how to use this. This function replaces ``basic.load_platform_subclass()``. When you port code, you need to change the callers to be explicit about instantiating the class. For instance, code in the Ansible User module changed from:: .. code-block:: python # Old class User: def __new__(cls, args, kwargs): return load_platform_subclass(User, args, kwargs) # New class User: def __new__(cls, *args, **kwargs): new_cls = get_platform_subclass(User) return super(cls, new_cls).__new__(new_cls) ''' this_platform = platform.system() distribution = get_distribution() distribution_version = get_distribution_version() subclass = None # set default value for this platform subclass for default_platform_key in ["distribution_version", "distribution", "platform"]: if not hasattr(cls,default_platform_key): setattr(cls, default_platform_key, None) # get the most specific superclass for this platform if distribution_version is not None: for sc in get_all_subclasses(cls): if sc.distribution_version is not None and sc.distribution_version == distribution_version and sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform: subclass = sc if distribution is not None: for sc in get_all_subclasses(cls): if sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform: subclass = sc if subclass is None: for sc in get_all_subclasses(cls): if sc.platform == this_platform and sc.distribution is None: subclass = sc if subclass is None: subclass = cls return subclass
def test_stategy_get_never_writes_in_check_mode(self, isfile): isfile.return_value = True set_module_args({'name': 'fooname', '_ansible_check_mode': True}) subclasses = get_all_subclasses(hostname.BaseStrategy) module = MagicMock() for cls in subclasses: instance = cls(module) instance.module.run_command = MagicMock() instance.module.run_command.return_value = (0, '', '') m = mock_open() builtins = 'builtins' if PY2: builtins = '__builtin__' with patch('%s.open' % builtins, m): instance.get_permanent_hostname() instance.get_current_hostname() self.assertFalse(m.return_value.write.called, msg='%s called write, should not have' % str(cls))
def get_all_pkg_managers(): return {obj.__name__.lower(): obj for obj in get_all_subclasses(PkgMgr) if obj not in (CLIMgr, LibMgr)}
def get_all_pkg_managers(): return dict([(obj.__name__.lower(), obj) for obj in get_all_subclasses(PkgMgr) if obj not in (CLIMgr, LibMgr)])