def _get_server_version(options: Options) -> str: """Try and get the server version.""" import re def callback(fp: BytesIO) -> str: """Parse the version.""" return re.findall(r"\d+\.\d+.\d+", fp.getvalue().decode("utf-8"), flags=re.IGNORECASE)[0] try: if not options.autoload: raise ValueError( "Autoloading is disabled. You can enable it by setting " "`omnipath.options.autoload = True`.") with Options.from_options( options, num_retries=0, timeout=0.1, cache=None, progress_bar=False, chunk_size=1024, ) as opt: return Downloader(opt).maybe_download( Endpoint.ABOUT.s, callback, params={Key.FORMAT.s: Format.TEXT.s}, cache=False, is_final=False, ) except Exception as e: logging.debug(f"Unable to get server version. Reason: `{e}`") return UNKNOWN_SERVER_VERSION
def test_from_options_new_values(self, options: Options): new_opt = Options.from_options(options, autoload=not options.autoload, num_retries=0) for k, v in options.__dict__.items(): if k not in ("autoload", "num_retries"): assert getattr(new_opt, k) == v assert new_opt.autoload != options.autoload assert new_opt.num_retries == 0
def __new__(cls, clsname, superclasses, attributedict): # noqa: D102 from omnipath import options endpoint = attributedict.pop("__endpoint__", clsname.lower().replace("validator", "")) use_default = True old_members = list(attributedict._member_names) old_values = cls._remove_old_members(attributedict) if endpoint is None: if len(old_members): raise ValueError( "If `__endpoint__` is `None`, no members must be specified." ) elif options.autoload: use_default = False with Options.from_options( options, num_retries=0, timeout=0.1, cache=None, progress_bar=False, chunk_size=2048, ) as opt: try: logging.debug( "Attempting to construct classes from the server") res = Downloader(opt).maybe_download( urljoin(urljoin(opt.url, f"{Key.QUERIES.s}/"), endpoint), callback=json.load, params={Key.FORMAT.s: Format.JSON.s}, ) if len({str(k).upper() for k in res.keys()}) != len(res): raise RuntimeError( f"After upper casing, key will not be unique: `{list(res.keys())}`." ) for k, value in res.items(): if (isinstance(value, str) and "no such query available" in value): raise RuntimeError( f"Invalid endpoint: `{endpoint}`.") key = str(k).upper() if value is None: attributedict[key] = cls.Validator(param=k) elif isinstance(value, Sequence): attributedict[key] = cls.Validator( param=k, haystack={str(v) for v in value}) else: attributedict[key] = cls.Validator(param=k) except Exception as e: logging.debug( f"Unable to construct classes from the server. Reason: `{e}`" ) use_default = True if use_default: if endpoint is not None: logging.debug(f"Using predefined class: `{clsname}`." + ( "" if options.autoload else " Consider specifying `omnipath.options.autoload = True`")) _ = cls._remove_old_members(attributedict) for k, v in zip(old_members, old_values): attributedict[k] = cls.Validator(param=k, doc=v) return super().__new__(cls, clsname, superclasses, attributedict)
def test_from_options(self, options: Options): new_opt = Options.from_options(options) for k, v in options.__dict__.items(): assert getattr(new_opt, k) == v
def test_from_options_invalid_type(self): with pytest.raises(TypeError): Options.from_options("foo")