Best Python code snippet using lisa_python
__init__.py
Source:__init__.py  
1#2# Copyright (C) 2016  FreeIPA Contributors see COPYING for license3#4import collections5import errno6import json7import locale8import logging9import os10import time11from . import compat12from . import schema13from ipaclient.plugins.rpcclient import rpcclient14from ipalib.constants import USER_CACHE_PATH15from ipapython.dnsutil import DNSName16logger = logging.getLogger(__name__)17class ServerInfo(collections.MutableMapping):18    _DIR = os.path.join(USER_CACHE_PATH, 'ipa', 'servers')19    def __init__(self, api):20        hostname = DNSName(api.env.server).ToASCII()21        self._path = os.path.join(self._DIR, hostname)22        self._force_check = api.env.force_schema_check23        self._dict = {}24        # copy-paste from ipalib/rpc.py25        try:26            self._language = locale.setlocale(27                locale.LC_MESSAGES, ''28            ).split('.')[0].lower()29        except locale.Error:30            self._language = 'en_us'31        self._read()32    def _read(self):33        try:34            with open(self._path, 'r') as sc:35                self._dict = json.load(sc)36        except Exception as e:37            if (isinstance(e, EnvironmentError) and38                    e.errno == errno.ENOENT):  # pylint: disable=no-member39                # ignore non-existent file, this happens when the cache was40                # erased or the server is contacted for the first time41                pass42            else:43                # warn that the file is unreadable, probably corrupted44                logger.warning('Failed to read server info: %s', e)45    def _write(self):46        try:47            try:48                os.makedirs(self._DIR)49            except EnvironmentError as e:50                if e.errno != errno.EEXIST:51                    raise52            with open(self._path, 'w') as sc:53                json.dump(self._dict, sc)54        except EnvironmentError as e:55            logger.warning('Failed to write server info: %s', e)56    def __getitem__(self, key):57        return self._dict[key]58    def __setitem__(self, key, value):59        self._dict[key] = value60    def __delitem__(self, key):61        del self._dict[key]62    def __iter__(self):63        return iter(self._dict)64    def __len__(self):65        return len(self._dict)66    def update_validity(self, ttl=None):67        if ttl is None:68            ttl = 360069        self['expiration'] = time.time() + ttl70        self['language'] = self._language71        self._write()72    def is_valid(self):73        if self._force_check:74            return False75        try:76            expiration = self._dict['expiration']77            language = self._dict['language']78        except KeyError:79            # if any of these is missing consider the entry expired80            return False81        if expiration < time.time():82            # validity passed83            return False84        if language != self._language:85            # language changed since last check86            return False87        return True88def get_package(api):89    if api.env.in_tree:90        # pylint: disable=import-error,ipa-forbidden-import91        from ipaserver import plugins92        # pylint: enable=import-error,ipa-forbidden-import93    else:94        try:95            plugins = api._remote_plugins96        except AttributeError:97            server_info = ServerInfo(api)98            client = rpcclient(api)99            client.finalize()100            try:101                plugins = schema.get_package(server_info, client)102            except schema.NotAvailable:103                plugins = compat.get_package(server_info, client)104            finally:105                if client.isconnected():106                    client.disconnect()107            object.__setattr__(api, '_remote_plugins', plugins)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
