Use pre-commit for pep8 checks

Also include fixes by pyupgrade.

Co-Authored-By: Takashi Kajinami <kajinamit@oss.nttdata.com>
Change-Id: I47b31b369c871ab8457cc7b7e73bf16cf79351e7
Signed-off-by: Jaromir Wysoglad <jwysogla@redhat.com>
This commit is contained in:
Jaromir Wysoglad
2025-10-10 02:40:02 -04:00
parent 130e6a995d
commit 4ff4703127
15 changed files with 75 additions and 35 deletions

36
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,36 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: trailing-whitespace
# Replaces or checks mixed line ending
- id: mixed-line-ending
args: ['--fix', 'lf']
exclude: '.*\.(svg)$'
# Forbid files which have a UTF-8 byte-order marker
- id: fix-byte-order-marker
# Checks that non-binary executables have a proper shebang
- id: check-executables-have-shebangs
# Check for files that contain merge conflict strings.
- id: check-merge-conflict
# Check for debugger imports and py37+ breakpoint()
# calls in python source
- id: debug-statements
- id: check-yaml
files: .*\.(yaml|yml)$
- repo: https://opendev.org/openstack/hacking
rev: 7.0.0
hooks:
- id: hacking
additional_dependencies: []
- repo: https://github.com/asottile/pyupgrade
rev: v3.20.0
hooks:
- id: pyupgrade
args: [--py310-plus]
- repo: https://github.com/openstack/bashate
rev: 2.1.1
hooks:
- id: bashate
args: ['-v', '-iE006']
exclude: '.tox/.*'

View File

@@ -25,7 +25,7 @@ def gen_ref(ver, title, names):
refdir = os.path.join(BASE_DIR, "ref")
pkg = "observabilityclient"
if ver:
pkg = "%s.%s" % (pkg, ver)
pkg = f"{pkg}.{ver}"
refdir = os.path.join(refdir, ver)
if not os.path.exists(refdir):
os.makedirs(refdir)
@@ -54,6 +54,7 @@ def gen_ref(ver, title, names):
"signs": "=" * len(name),
"pkg": pkg, "name": name})
gen_ref("v1", "Version 1 API", ["client", "python_api"])
gen_ref("", "rbac", ["rbac"])
@@ -64,7 +65,7 @@ gen_ref("", "rbac", ["rbac"])
extensions = [
'sphinx.ext.autodoc',
'openstackdocstheme',
#'sphinx.ext.intersphinx',
# 'sphinx.ext.intersphinx',
]
# autodoc generation is a bit aggressive and a nuisance when doing heavy
@@ -81,7 +82,7 @@ master_doc = 'index'
openstackdocs_repo_name = 'openstack/python-observabilityclient'
openstackdocs_bug_project = 'python-observabilityclient'
openstackdocs_bug_tag = ''
copyright = u'2025, OpenStack Foundation'
copyright = '2025, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
@@ -103,7 +104,7 @@ pygments_style = 'native'
html_theme = 'openstackdocs'
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = ['_theme']
# html_theme_path = ['_theme']
# Output file base name for HTML help builder.
htmlhelp_basename = 'observabilityclientdoc'
@@ -114,9 +115,9 @@ htmlhelp_basename = 'observabilityclientdoc'
latex_documents = [
('index',
'observabilityclient.tex',
u'observabilityclient Documentation',
u'OpenStack Foundation', 'manual'),
'observabilityclient Documentation',
'OpenStack Foundation', 'manual'),
]
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}
# intersphinx_mapping = {'http://docs.python.org/': None}

View File

@@ -45,14 +45,14 @@ class PrometheusAPIClientError(Exception):
return self.__str__()
class PrometheusMetric(object):
class PrometheusMetric:
def __init__(self, input):
self.timestamp = input['value'][0]
self.labels = input['metric']
self.value = input['value'][1]
class PrometheusAPIClient(object):
class PrometheusAPIClient:
def __init__(self, host, session=None, root_path=""):
self._host = host
if not self._host.endswith('/'):

View File

@@ -17,7 +17,7 @@ import re
from observabilityclient.utils.metric_utils import format_labels
class PromQLRbac(object):
class PromQLRbac:
def __init__(self, prom_api_client, project_id, project_label='project'):
self.client = prom_api_client

View File

@@ -47,7 +47,7 @@ class PythonAPITestCase(testtools.TestCase):
return session.Session(auth=auth)
def setUp(self):
super(PythonAPITestCase, self).setUp()
super().setUp()
self.client = client.Client(
1,
self._getKeystoneSession()

View File

@@ -23,7 +23,7 @@ from observabilityclient.v1 import cli
class CliTest(testtools.TestCase):
def setUp(self):
super(CliTest, self).setUp()
super().setUp()
self.client = mock.Mock()
self.client.query = mock.Mock()

View File

@@ -58,23 +58,23 @@ class MetricListMatcher(testtools.Matcher):
class PrometheusAPIClientTestBase(testtools.TestCase):
def setUp(self):
super(PrometheusAPIClientTestBase, self).setUp()
super().setUp()
class GoodResponse(object):
class GoodResponse:
def __init__(self):
self.status_code = 200
def json(self):
return {"status": "success"}
class BadResponse(object):
class BadResponse:
def __init__(self):
self.status_code = 500
def json(self):
return {"status": "error", "error": "test_error"}
class NoContentResponse(object):
class NoContentResponse:
def __init__(self):
self.status_code = 204

View File

@@ -26,7 +26,7 @@ from observabilityclient.v1 import python_api
class QueryManagerTest(testtools.TestCase):
def setUp(self):
super(QueryManagerTest, self).setUp()
super().setUp()
self.client = mock.Mock()
prom_client = prometheus_client.PrometheusAPIClient("somehost")
self.client.prometheus_client = prom_client

View File

@@ -21,7 +21,7 @@ from observabilityclient import rbac
class PromQLRbacTest(testtools.TestCase):
def setUp(self):
super(PromQLRbacTest, self).setUp()
super().setUp()
self.project_id = "project123"
self.rbac = rbac.PromQLRbac(mock.Mock(), mock.Mock())
self.rbac.labels = {

View File

@@ -25,20 +25,20 @@ from observabilityclient.utils import metric_utils
class GetConfigFileTest(testtools.TestCase):
def setUp(self):
super(GetConfigFileTest, self).setUp()
super().setUp()
def test_current_dir(self):
with mock.patch.object(os.path, 'exists', return_value=True), \
mock.patch.object(metric_utils, 'open') as m:
metric_utils.get_config_file()
m.assert_called_with(metric_utils.CONFIG_FILE_NAME, 'r')
m.assert_called_with(metric_utils.CONFIG_FILE_NAME)
def test_path_order(self):
expected = [mock.call(metric_utils.CONFIG_FILE_NAME, 'r'),
mock.call((f"{os.environ['HOME']}/.config/openstack/"
f"{metric_utils.CONFIG_FILE_NAME}")),
mock.call((f"/etc/openstack/"
f"{metric_utils.CONFIG_FILE_NAME}"))]
mock.call(f"{os.environ['HOME']}/.config/openstack/"
f"{metric_utils.CONFIG_FILE_NAME}"),
mock.call(f"/etc/openstack/"
f"{metric_utils.CONFIG_FILE_NAME}")]
with mock.patch.object(os.path, 'exists', return_value=False) as m:
ret = metric_utils.get_config_file()
m.call_args_list == expected
@@ -47,7 +47,7 @@ class GetConfigFileTest(testtools.TestCase):
class GetPrometheusClientTest(testtools.TestCase):
def setUp(self):
super(GetPrometheusClientTest, self).setUp()
super().setUp()
config_data = 'host: "somehost"\nport: "1234"'
self.config_file = mock.mock_open(read_data=config_data)("name", 'r')
@@ -185,7 +185,7 @@ class GetPrometheusClientTest(testtools.TestCase):
class FormatLabelsTest(testtools.TestCase):
def setUp(self):
super(FormatLabelsTest, self).setUp()
super().setUp()
def test_format_labels_with_normal_labels(self):
input_dict = {"label_key1": "label_value1",
@@ -206,7 +206,7 @@ class FormatLabelsTest(testtools.TestCase):
class Metrics2ColsTest(testtools.TestCase):
def setUp(self):
super(Metrics2ColsTest, self).setUp()
super().setUp()
def test_metrics2cols(self):
metric = {

View File

@@ -40,12 +40,12 @@ class ConfigurationError(Exception):
def get_config_file():
if os.path.exists(CONFIG_FILE_NAME):
LOG.debug("Using %s as prometheus configuration", CONFIG_FILE_NAME)
return open(CONFIG_FILE_NAME, "r")
return open(CONFIG_FILE_NAME)
for path in DEFAULT_CONFIG_LOCATIONS:
full_filename = path + CONFIG_FILE_NAME
if os.path.exists(full_filename):
LOG.debug("Using %s as prometheus configuration", full_filename)
return open(full_filename, "r")
return open(full_filename)
return None
@@ -154,7 +154,7 @@ def format_labels(d: dict) -> str:
ret = ""
for key, value in d.items():
ret += "{}='{}', ".format(key, value)
ret += f"{key}='{value}', "
ret = ret[0:-2]
old = ""
while ret != old:

View File

@@ -51,7 +51,7 @@ class ObservabilityBaseCommand(command.Command):
return parser
class Manager(object):
class Manager:
"""Base class for the python api."""
DEFAULT_HEADERS = {

View File

@@ -19,7 +19,7 @@ from observabilityclient.utils.metric_utils import get_prometheus_client
from observabilityclient.v1 import python_api
class Client(object):
class Client:
"""Client for the observabilityclient api."""
def __init__(self, session=None, adapter_options=None,

View File

@@ -31,7 +31,7 @@ class QueryManager(base.Manager):
metrics = self.prom.series(match)
if metrics == []:
return []
unique_metric_names = list(set([m['__name__'] for m in metrics]))
unique_metric_names = list({m['__name__'] for m in metrics})
return sorted(unique_metric_names)
def show(self, name, disable_rbac=True):

View File

@@ -18,8 +18,11 @@ deps =
commands = stestr run --slowest {posargs} --test-path {env:OS_TEST_PATH}
[testenv:pep8]
deps = hacking>=7.0.0,<7.1.0
commands = flake8
skip_install = true
deps =
pre-commit
commands =
pre-commit run -a
[testenv:venv]
commands = {posargs}