Best Python code snippet using autotest_python
storage_backend.py
Source:storage_backend.py  
1# Copyright 2017 Akretion (http://www.akretion.com).2# @author Sébastien BEAU <sebastien.beau@akretion.com>3# Copyright 2019 Camptocamp SA (http://www.camptocamp.com).4# @author Simone Orsi <simone.orsi@camptocamp.com>5# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).6import base647import fnmatch8import functools9import inspect10import logging11import warnings12from odoo import _, fields, models13_logger = logging.getLogger(__name__)14# TODO: useful for the whole OCA?15def deprecated(reason):16    """Mark functions or classes as deprecated.17    Emit warning at execution.18    The @deprecated is used with a 'reason'.19        .. code-block:: python20            @deprecated("please, use another function")21            def old_function(x, y):22                pass23    """24    def decorator(func1):25        if inspect.isclass(func1):26            fmt1 = "Call to deprecated class {name} ({reason})."27        else:28            fmt1 = "Call to deprecated function {name} ({reason})."29        @functools.wraps(func1)30        def new_func1(*args, **kwargs):31            warnings.simplefilter("always", DeprecationWarning)32            warnings.warn(33                fmt1.format(name=func1.__name__, reason=reason),34                category=DeprecationWarning,35                stacklevel=2,36            )37            warnings.simplefilter("default", DeprecationWarning)38            return func1(*args, **kwargs)39        return new_func140    return decorator41class StorageBackend(models.Model):42    _name = "storage.backend"43    _inherit = ["collection.base", "server.env.mixin"]44    _backend_name = "storage_backend"45    _description = "Storage Backend"46    name = fields.Char(required=True)47    backend_type = fields.Selection(48        selection=[("filesystem", "Filesystem")], required=True, default="filesystem"49    )50    directory_path = fields.Char(51        help="Relative path to the directory to store the file"52    )53    has_validation = fields.Boolean(compute="_compute_has_validation")54    def _compute_has_validation(self):55        for rec in self:56            adapter = self._get_adapter()57            rec.has_validation = hasattr(adapter, "validate_config")58    @property59    def _server_env_fields(self):60        return {"backend_type": {}, "directory_path": {}}61    def add(self, relative_path, data, binary=True, **kwargs):62        if not binary:63            data = base64.b64decode(data)64        return self._forward("add", relative_path, data, **kwargs)65    @deprecated("Use `add`")66    def _add_bin_data(self, relative_path, data, **kwargs):67        return self.add(relative_path, data, **kwargs)68    @deprecated("Use `add` with `binary=False`")69    def _add_b64_data(self, relative_path, data, **kwargs):70        return self.add(relative_path, data, binary=False, **kwargs)71    def get(self, relative_path, binary=True, **kwargs):72        data = self._forward("get", relative_path, **kwargs)73        if not binary and data:74            data = base64.b64encode(data)75        return data76    @deprecated("Use `get` with `binary=False`")77    def _get_b64_data(self, relative_path, **kwargs):78        return self.get(relative_path, binary=False, **kwargs)79    @deprecated("Use `get`")80    def _get_bin_data(self, relative_path, **kwargs):81        return self.get(relative_path, **kwargs)82    def list_files(self, relative_path="", pattern=False):83        names = self._forward("list", relative_path)84        if pattern:85            names = fnmatch.filter(names, pattern)86        return names87    @deprecated("Use `list_files`")88    def _list(self, relative_path="", pattern=False):89        return self.list_files(relative_path, pattern=pattern)90    def find_files(self, pattern, relative_path="", **kw):91        return self._forward("find_files", pattern, relative_path=relative_path)92    @deprecated("Use `find_files`")93    def _find_files(self, pattern, relative_path="", **kw):94        return self.find_files(pattern, relative_path=relative_path, **kw)95    def move_files(self, files, destination_path, **kw):96        return self._forward("move_files", files, destination_path, **kw)97    @deprecated("Use `move_files`")98    def _move_files(self, files, destination_path, **kw):99        return self.move_files(files, destination_path, **kw)100    def delete(self, relative_path):101        return self._forward("delete", relative_path)102    @deprecated("Use `delete`")103    def _delete(self, relative_path):104        return self.delete(relative_path)105    def _forward(self, method, *args, **kwargs):106        _logger.debug(107            "Backend Storage ID: %s type %s: %s file %s %s",108            self.backend_type,109            self.id,110            method,111            args,112            kwargs,113        )114        self.ensure_one()115        adapter = self._get_adapter()116        return getattr(adapter, method)(*args, **kwargs)117    def _get_adapter(self):118        with self.work_on(self._name) as work:119            return work.component(usage=self.backend_type)120    def action_test_config(self):121        if not self.has_validation:122            raise AttributeError("Validation not supported!")123        adapter = self._get_adapter()124        try:125            adapter.validate_config()126            title = _("Connection Test Succeeded!")127            message = _("Everything seems properly set up!")128            msg_type = "success"129        except Exception as err:130            title = _("Connection Test Failed!")131            message = str(err)132            msg_type = "danger"133        return {134            "type": "ir.actions.client",135            "tag": "display_notification",136            "params": {137                "title": title,138                "message": message,139                "type": msg_type,140                "sticky": False,141            },...package_io.py
Source:package_io.py  
1import os2import zipfile3import sublime4from .console_write import console_write5from .open_compat import open_compat, read_compat6from .unicode import unicode_from_os7from .file_not_found_error import FileNotFoundError8def read_package_file(package, relative_path, binary=False, debug=False):9    package_dir = _get_package_dir(package)10    file_path = os.path.join(package_dir, relative_path)11    if os.path.exists(package_dir):12        result = _read_regular_file(package, relative_path, binary, debug)13        if result != False:14            return result15    if int(sublime.version()) >= 3000:16        result = _read_zip_file(package, relative_path, binary, debug)17        if result != False:18            return result19    if debug:20        console_write(u"Unable to find file %s in the package %s" % (relative_path, package), True)21    return False22def package_file_exists(package, relative_path):23    package_dir = _get_package_dir(package)24    file_path = os.path.join(package_dir, relative_path)25    if os.path.exists(package_dir):26        result = _regular_file_exists(package, relative_path)27        if result:28            return result29    if int(sublime.version()) >= 3000:30        return _zip_file_exists(package, relative_path)31    return False32def _get_package_dir(package):33    """:return: The full filesystem path to the package directory"""34    return os.path.join(sublime.packages_path(), package)35def _read_regular_file(package, relative_path, binary=False, debug=False):36    package_dir = _get_package_dir(package)37    file_path = os.path.join(package_dir, relative_path)38    try:39        with open_compat(file_path, ('rb' if binary else 'r')) as f:40            return read_compat(f)41    except (FileNotFoundError) as e:42        if debug:43            console_write(u"Unable to find file %s in the package folder for %s" % (relative_path, package), True)44        return False45def _read_zip_file(package, relative_path, binary=False, debug=False):46    zip_path = os.path.join(sublime.installed_packages_path(),47        package + '.sublime-package')48    if not os.path.exists(zip_path):49        if debug:50            console_write(u"Unable to find a sublime-package file for %s" % package, True)51        return False52    try:53        package_zip = zipfile.ZipFile(zip_path, 'r')54    except (zipfile.BadZipfile):55        console_write(u'An error occurred while trying to unzip the sublime-package file for %s.' % package, True)56        return False57    try:58        contents = package_zip.read(relative_path)59        if not binary:60            contents = contents.decode('utf-8')61        return contents62    except (KeyError) as e:63        if debug:64            console_write(u"Unable to find file %s in the sublime-package file for %s" % (relative_path, package), True)65    except (IOError) as e:66        message = unicode_from_os(e)67        console_write(u'Unable to read file from sublime-package file for %s due to an invalid filename' % package, True)68    except (UnicodeDecodeError):69        console_write(u'Unable to read file from sublime-package file for %s due to an invalid filename or character encoding issue' % package, True)70    return False71def _regular_file_exists(package, relative_path):72    package_dir = _get_package_dir(package)73    file_path = os.path.join(package_dir, relative_path)74    return os.path.exists(file_path)75def _zip_file_exists(package, relative_path):76    zip_path = os.path.join(sublime.installed_packages_path(),77        package + '.sublime-package')78    if not os.path.exists(zip_path):79        return False80    try:81        package_zip = zipfile.ZipFile(zip_path, 'r')82    except (zipfile.BadZipfile):83        console_write(u'An error occurred while trying to unzip the sublime-package file for %s.' % package_name, True)84        return False85    try:86        package_zip.getinfo(relative_path)87        return True88    except (KeyError) as e:...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!!
