Skip to content

Commit

Permalink
Enable more of ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Aug 30, 2023
1 parent 1605a74 commit 86ea314
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 105 deletions.
2 changes: 0 additions & 2 deletions doc/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# pyOpenSSL documentation build configuration file, created by
# sphinx-quickstart on Sat Jul 16 07:12:22 2011.
Expand All @@ -16,7 +15,6 @@
import re
import sys


HERE = os.path.abspath(os.path.dirname(__file__))


Expand Down
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@
line-length = 79
target-version = ["py37"]

[tool.ruff]
select = ['E', 'F', 'I', 'W', 'UP', 'RUF']
line-length = 79

[tool.ruff.isort]
known-first-party = ["OpenSSL", "tests"]
10 changes: 3 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Jean-Paul Calderone 2008-2015, All rights reserved
#
Expand All @@ -13,7 +12,6 @@

from setuptools import find_packages, setup


HERE = os.path.abspath(os.path.dirname(__file__))
META_PATH = os.path.join("src", "OpenSSL", "version.py")

Expand All @@ -23,9 +21,7 @@ def read_file(*parts):
Build an absolute path from *parts* and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with open(
os.path.join(HERE, *parts), "r", encoding="utf-8", newline=None
) as f:
with open(os.path.join(HERE, *parts), encoding="utf-8", newline=None) as f:
return f.read()


Expand All @@ -37,11 +33,11 @@ def find_meta(meta):
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M
rf"^__{meta}__ = ['\"]([^'\"]*)['\"]", META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
raise RuntimeError(f"Unable to find __{meta}__ string.")


URI = find_meta("uri")
Expand Down
26 changes: 20 additions & 6 deletions src/OpenSSL/SSL.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import socket
import typing
from errno import errorcode
from functools import partial, wraps
from itertools import chain, count
Expand All @@ -8,18 +9,32 @@

from OpenSSL._util import (
UNSPECIFIED as _UNSPECIFIED,
)
from OpenSSL._util import (
exception_from_error_queue as _exception_from_error_queue,
)
from OpenSSL._util import (
ffi as _ffi,
)
from OpenSSL._util import (
lib as _lib,
)
from OpenSSL._util import (
make_assert as _make_assert,
)
from OpenSSL._util import (
no_zero_allocator as _no_zero_allocator,
)
from OpenSSL._util import (
path_bytes as _path_bytes,
)
from OpenSSL._util import (
text_to_bytes_and_warn as _text_to_bytes_and_warn,
)
from OpenSSL.crypto import (
FILETYPE_PEM,
PKey,
X509,
PKey,
X509Name,
X509Store,
_PassphraseHelper,
Expand Down Expand Up @@ -803,7 +818,7 @@ class Context:
not be used.
"""

_methods = {
_methods: typing.ClassVar[typing.Dict] = {
SSLv23_METHOD: (_lib.TLS_method, None),
TLSv1_METHOD: (_lib.TLS_method, TLS1_VERSION),
TLSv1_1_METHOD: (_lib.TLS_method, TLS1_1_VERSION),
Expand Down Expand Up @@ -1373,8 +1388,8 @@ def set_client_ca_list(self, certificate_authorities):
for ca_name in certificate_authorities:
if not isinstance(ca_name, X509Name):
raise TypeError(
"client CAs must be X509Name objects, not %s "
"objects" % (type(ca_name).__name__,)
"client CAs must be X509Name objects, not {} "
"objects".format(type(ca_name).__name__)
)
copy = _lib.X509_NAME_dup(ca_name._name)
_openssl_assert(copy != _ffi.NULL)
Expand Down Expand Up @@ -1777,8 +1792,7 @@ def __getattr__(self, name):
"""
if self._socket is None:
raise AttributeError(
"'%s' object has no attribute '%s'"
% (self.__class__.__name__, name)
f"'{self.__class__.__name__}' object has no attribute '{name}'"
)
else:
return getattr(self._socket, name)
Expand Down
1 change: 0 additions & 1 deletion src/OpenSSL/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
__version__,
)


__all__ = [
"SSL",
"crypto",
Expand Down
41 changes: 28 additions & 13 deletions src/OpenSSL/crypto.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import calendar
import datetime
import functools
import typing
from base64 import b16encode
from functools import partial
from os import PathLike
Expand All @@ -22,23 +23,36 @@
from cryptography.hazmat.primitives.asymmetric import (
dsa,
ec,
ed25519,
ed448,
ed25519,
rsa,
)

from OpenSSL._util import (
UNSPECIFIED as _UNSPECIFIED,
)
from OpenSSL._util import (
byte_string as _byte_string,
)
from OpenSSL._util import (
exception_from_error_queue as _exception_from_error_queue,
)
from OpenSSL._util import (
ffi as _ffi,
)
from OpenSSL._util import (
lib as _lib,
)
from OpenSSL._util import (
make_assert as _make_assert,
)
from OpenSSL._util import (
path_bytes as _path_bytes,
)
from OpenSSL._util import (
text_to_bytes_and_warn as _text_to_bytes_and_warn,
)


__all__ = [
"FILETYPE_PEM",
"FILETYPE_ASN1",
Expand Down Expand Up @@ -111,7 +125,7 @@ def _untested_error(where: str) -> NoReturn:
encountered isn't one that's exercised by the test suite so future behavior
of pyOpenSSL is now somewhat less predictable.
"""
raise RuntimeError("Unknown %s failure" % (where,))
raise RuntimeError(f"Unknown {where} failure")


def _new_mem_buf(buffer: Optional[bytes] = None) -> Any:
Expand Down Expand Up @@ -448,7 +462,7 @@ def __ne__(self, other: Any) -> bool:
circumstance.
"""
if isinstance(other, _EllipticCurve):
return super(_EllipticCurve, self).__ne__(other)
return super().__ne__(other)
return NotImplemented

@classmethod
Expand Down Expand Up @@ -518,7 +532,7 @@ def __init__(self, lib: Any, nid: int, name: str) -> None:
self.name = name

def __repr__(self) -> str:
return "<Curve %r>" % (self.name,)
return f"<Curve {self.name!r}>"

def _to_EC_KEY(self) -> Any:
"""
Expand Down Expand Up @@ -602,14 +616,15 @@ def __init__(self, name: "X509Name") -> None:

def __setattr__(self, name: str, value: Any) -> None:
if name.startswith("_"):
return super(X509Name, self).__setattr__(name, value)
return super().__setattr__(name, value)

# Note: we really do not want str subclasses here, so we do not use
# isinstance.
if type(name) is not str: # noqa: E721
raise TypeError(
"attribute name must be string, not '%.200s'"
% (type(value).__name__,)
"attribute name must be string, not '{:.200}'".format(
type(value).__name__
)
)

nid = _lib.OBJ_txt2nid(_byte_string(name))
Expand Down Expand Up @@ -701,7 +716,7 @@ def __repr__(self) -> str:
)
_openssl_assert(format_result != _ffi.NULL)

return "<X509Name object '%s'>" % (
return "<X509Name object '{}'>".format(
_ffi.string(result_buffer).decode("utf-8"),
)

Expand Down Expand Up @@ -839,7 +854,7 @@ def _nid(self) -> Any:
_lib.X509_EXTENSION_get_object(self._extension)
)

_prefixes = {
_prefixes: typing.ClassVar[typing.Dict[int, str]] = {
_lib.GEN_EMAIL: "email",
_lib.GEN_DNS: "DNS",
_lib.GEN_URI: "URI",
Expand Down Expand Up @@ -1814,7 +1829,7 @@ class X509StoreContextError(Exception):
def __init__(
self, message: str, errors: List[Any], certificate: X509
) -> None:
super(X509StoreContextError, self).__init__(message)
super().__init__(message)
self.errors = errors
self.certificate = certificate

Expand Down Expand Up @@ -2166,7 +2181,7 @@ class Revoked:
# which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
# OCSP_crl_reason_str. We use the latter, just like the command line
# program.
_crl_reasons = [
_crl_reasons: typing.ClassVar[typing.List[bytes]] = [
b"unspecified",
b"keyCompromise",
b"CACompromise",
Expand Down Expand Up @@ -2667,7 +2682,7 @@ def set_friendlyname(self, name: Optional[bytes]) -> None:
self._friendlyname = None
elif not isinstance(name, bytes):
raise TypeError(
"name must be a byte string or None (not %r)" % (name,)
f"name must be a byte string or None (not {name!r})"
)
self._friendlyname = name

Expand Down
4 changes: 0 additions & 4 deletions src/OpenSSL/debug.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
from __future__ import print_function

import ssl
import sys

import cffi

import cryptography

import OpenSSL.SSL

from . import version


_env_info = """\
pyOpenSSL: {pyopenssl}
cryptography: {cryptography}
Expand Down
2 changes: 1 addition & 1 deletion src/OpenSSL/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
__author__ = "The pyOpenSSL developers"
__email__ = "cryptography-dev@python.org"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2001-2023 {0}".format(__author__)
__copyright__ = f"Copyright 2001-2023 {__author__}"
3 changes: 2 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@


def pytest_report_header(config):
import OpenSSL.SSL
import cryptography

import OpenSSL.SSL

return "OpenSSL: {openssl}\ncryptography: {cryptography}".format(
openssl=OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION),
cryptography=cryptography.__version__,
Expand Down
5 changes: 2 additions & 3 deletions tests/memdbg.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from cffi import api as _api


sys.modules["ssl"] = None
sys.modules["_hashlib"] = None

Expand All @@ -22,7 +21,7 @@
char **backtrace_symbols(void *const *buffer, int size);
void backtrace_symbols_fd(void *const *buffer, int size, int fd);
"""
) # noqa
)
_api = _ffi.verify(
"""
#include <openssl/crypto.h>
Expand Down Expand Up @@ -79,7 +78,7 @@ def free(p):
if p != _ffi.NULL:
C.free(p)
del heap[p]
log("free(0x%x)" % (int(_ffi.cast("int", p)),))
log("free(0x{:x})".format(int(_ffi.cast("int", p))))


if _api.CRYPTO_set_mem_functions(malloc, realloc, free):
Expand Down
Loading

0 comments on commit 86ea314

Please sign in to comment.