chore: ruff cleanup

This commit is contained in:
Bharath Vignesh J K 2024-05-16 17:31:42 +05:30
parent 396e78c415
commit acb5ef585f
26 changed files with 144 additions and 107 deletions

View File

@ -125,8 +125,7 @@ html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
# documentation. # documentation.
html_theme_options = { html_theme_options = {}
}
# Add any paths that contain custom themes here, relative to this directory. # Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = [] # html_theme_path = []
@ -166,14 +165,7 @@ html_static_path = ['_static']
# html_use_smartypants = True # html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # Custom sidebar templates, maps document names to template names.
html_sidebars = { html_sidebars = {'**': ['about.html', 'navigation.html', 'links.html', 'searchbox.html']}
'**': [
'about.html',
'navigation.html',
'links.html',
'searchbox.html'
]
}
# Additional templates that should be rendered to pages, maps page names to # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.
@ -227,13 +219,10 @@ htmlhelp_basename = 'Glancesdoc'
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt', # 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
# 'preamble': '', # 'preamble': '',
# Latex figure (float) alignment # Latex figure (float) alignment
# 'figure_align': 'htbp', # 'figure_align': 'htbp',
} }
@ -242,8 +231,7 @@ latex_elements = {
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
(master_doc, 'Glances.tex', 'Glances Documentation', (master_doc, 'Glances.tex', 'Glances Documentation', 'Nicolas Hennion', 'manual'),
'Nicolas Hennion', 'manual'),
] ]
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
@ -271,10 +259,7 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [('glances', 'glances', 'An eye on your system', '', 1)]
('glances', 'glances', 'An eye on your system',
'', 1)
]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
# man_show_urls = False # man_show_urls = False
@ -286,9 +271,15 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
(master_doc, 'Glances', 'Glances Documentation', (
author, 'Glances', 'One line description of project.', master_doc,
'Miscellaneous'), 'Glances',
'Glances Documentation',
author,
'Glances',
'One line description of project.',
'Miscellaneous',
),
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.

View File

@ -122,8 +122,9 @@ class GlancesClient(object):
else: else:
self.log_and_exit( self.log_and_exit(
( (
'Client and server not compatible: ' 'Client and server not compatible: ' 'Client version: {} / Server version: {}'.format(
'Client version: {} / Server version: {}'.format(__version__, client_version) __version__, client_version
)
) )
) )
return False return False

View File

@ -9,7 +9,6 @@
"""RESTful interface class.""" """RESTful interface class."""
from glances.globals import listkeys from glances.globals import listkeys
from glances.logger import logger from glances.logger import logger
from glances.exports.export import GlancesExport from glances.exports.export import GlancesExport

View File

@ -8,6 +8,7 @@
# #
"""Manage the folder list.""" """Manage the folder list."""
from __future__ import unicode_literals from __future__ import unicode_literals

View File

@ -19,8 +19,6 @@ import sys
import platform import platform
import ujson import ujson
from operator import itemgetter, methodcaller from operator import itemgetter, methodcaller
import unicodedata
import types
import subprocess import subprocess
from datetime import datetime from datetime import datetime
import re import re
@ -28,14 +26,8 @@ import base64
import functools import functools
import weakref import weakref
import queue
from configparser import ConfigParser, NoOptionError, NoSectionError
from statistics import mean from statistics import mean
from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server
from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from urllib.request import urlopen, Request from urllib.request import urlopen, Request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
# Correct issue #1025 by monkey path the xmlrpc lib # Correct issue #1025 by monkey path the xmlrpc lib
from defusedxml.xmlrpc import monkey_patch from defusedxml.xmlrpc import monkey_patch

View File

@ -241,7 +241,7 @@ Examples of use:
) )
parser.add_argument( parser.add_argument(
'--enable-irq', action='store_true', default=False, dest='enable_irq', help='enable IRQ module' '--enable-irq', action='store_true', default=False, dest='enable_irq', help='enable IRQ module'
), )
parser.add_argument( parser.add_argument(
'--enable-process-extended', '--enable-process-extended',
action='store_true', action='store_true',
@ -255,14 +255,14 @@ Examples of use:
default=True, default=True,
dest='enable_separator', dest='enable_separator',
help='disable separator in the UI (between top and others modules)', help='disable separator in the UI (between top and others modules)',
), )
parser.add_argument( parser.add_argument(
'--disable-cursor', '--disable-cursor',
action='store_true', action='store_true',
default=False, default=False,
dest='disable_cursor', dest='disable_cursor',
help='disable cursor (process selection) in the UI', help='disable cursor (process selection) in the UI',
), )
# Sort processes list # Sort processes list
parser.add_argument( parser.add_argument(
'--sort-processes', '--sort-processes',

View File

@ -46,7 +46,7 @@ class Outdated(object):
self.cache_file = os.path.join(self.cache_dir, 'glances-version.db') self.cache_file = os.path.join(self.cache_dir, 'glances-version.db')
# Set default value... # Set default value...
self.data = {u'installed_version': __version__, u'latest_version': '0.0', u'refresh_date': datetime.now()} self.data = {'installed_version': __version__, 'latest_version': '0.0', 'refresh_date': datetime.now()}
# Disable update check if `packaging` is not installed # Disable update check if `packaging` is not installed
if not PACKAGING_IMPORT: if not PACKAGING_IMPORT:
@ -154,14 +154,14 @@ class Outdated(object):
logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(PYPI_API_URL)) logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(PYPI_API_URL))
# Update the current time # Update the current time
self.data[u'refresh_date'] = datetime.now() self.data['refresh_date'] = datetime.now()
try: try:
res = urlopen(PYPI_API_URL, timeout=3).read() res = urlopen(PYPI_API_URL, timeout=3).read()
except (HTTPError, URLError, CertificateError) as e: except (HTTPError, URLError, CertificateError) as e:
logger.debug("Cannot get Glances version from the PyPI RESTful API ({})".format(e)) logger.debug("Cannot get Glances version from the PyPI RESTful API ({})".format(e))
else: else:
self.data[u'latest_version'] = json.loads(nativestr(res))['info']['version'] self.data['latest_version'] = json.loads(nativestr(res))['info']['version']
logger.debug("Save Glances version to the cache file") logger.debug("Save Glances version to the cache file")
# Save result to the cache file # Save result to the cache file

View File

@ -8,6 +8,7 @@
# #
"""Curses interface class.""" """Curses interface class."""
from __future__ import unicode_literals from __future__ import unicode_literals
import sys import sys

View File

@ -16,7 +16,7 @@ from io import open
import webbrowser import webbrowser
from urllib.parse import urljoin from urllib.parse import urljoin
try: try:
from typing import Annotated from typing import Annotated
except ImportError: except ImportError:
# Only for Python 3.8 # Only for Python 3.8

View File

@ -75,9 +75,7 @@ WebUI refresh
It is possible to change the Web UI refresh rate (default is 2 seconds) using the following option in the URL: It is possible to change the Web UI refresh rate (default is 2 seconds) using the following option in the URL:
``http://localhost:61208/glances/?refresh=5`` ``http://localhost:61208/glances/?refresh=5``
""".format( """.format(api_version=__apiversion__)
api_version=__apiversion__
)
def indent_stat(stat, indent=' '): def indent_stat(stat, indent=' '):

View File

@ -10,14 +10,14 @@
"""Manage unicode message for Glances output.""" """Manage unicode message for Glances output."""
_unicode_message = { _unicode_message = {
'ARROW_LEFT': [u'\u2190', u'<'], 'ARROW_LEFT': ['\u2190', '<'],
'ARROW_RIGHT': [u'\u2192', u'>'], 'ARROW_RIGHT': ['\u2192', '>'],
'ARROW_UP': [u'\u2191', u'^'], 'ARROW_UP': ['\u2191', '^'],
'ARROW_DOWN': [u'\u2193', u'v'], 'ARROW_DOWN': ['\u2193', 'v'],
'CHECK': [u'\u2713', u''], 'CHECK': ['\u2713', ''],
'PROCESS_SELECTOR': [u'>', u'>'], 'PROCESS_SELECTOR': ['>', '>'],
'MEDIUM_LINE': [u'\u23AF', u'-'], 'MEDIUM_LINE': ['\u23af', '-'],
'LOW_LINE': [u'\u2581', u'_'], 'LOW_LINE': ['\u2581', '_'],
} }

View File

@ -8,6 +8,7 @@
# #
"""Connections plugin.""" """Connections plugin."""
from __future__ import unicode_literals from __future__ import unicode_literals
from glances.logger import logger from glances.logger import logger

View File

@ -8,6 +8,7 @@
# #
"""Docker Extension unit for Glances' Containers plugin.""" """Docker Extension unit for Glances' Containers plugin."""
import time import time
from glances.globals import iterkeys, itervalues, nativestr, pretty_date, replace_special_chars from glances.globals import iterkeys, itervalues, nativestr, pretty_date, replace_special_chars

View File

@ -7,6 +7,7 @@
# SPDX-License-Identifier: LGPL-3.0-only # SPDX-License-Identifier: LGPL-3.0-only
"""Podman Extension unit for Glances' Containers plugin.""" """Podman Extension unit for Glances' Containers plugin."""
from datetime import datetime from datetime import datetime
from glances.globals import iterkeys, itervalues, nativestr, pretty_date, string_value_to_float, replace_special_chars from glances.globals import iterkeys, itervalues, nativestr, pretty_date, string_value_to_float, replace_special_chars

View File

@ -8,6 +8,7 @@
# #
"""Disk I/O plugin.""" """Disk I/O plugin."""
from __future__ import unicode_literals from __future__ import unicode_literals
from glances.logger import logger from glances.logger import logger

View File

@ -8,6 +8,7 @@
# #
"""Folder plugin.""" """Folder plugin."""
from __future__ import unicode_literals from __future__ import unicode_literals
from glances.logger import logger from glances.logger import logger

View File

@ -8,6 +8,7 @@
# #
"""File system plugin.""" """File system plugin."""
from __future__ import unicode_literals from __future__ import unicode_literals
import operator import operator
@ -166,7 +167,7 @@ class PluginModel(GlancesPluginModel):
'device_name': fs.device, 'device_name': fs.device,
'fs_type': fs.fstype, 'fs_type': fs.fstype,
# Manage non breaking space (see issue #1065) # Manage non breaking space (see issue #1065)
'mnt_point': u(fs.mountpoint).replace(u'\u00A0', ' '), 'mnt_point': u(fs.mountpoint).replace('\u00a0', ' '),
'size': fs_usage.total, 'size': fs_usage.total,
'used': fs_usage.used, 'used': fs_usage.used,
'free': fs_usage.free, 'free': fs_usage.free,

View File

@ -12,6 +12,7 @@ Help plugin.
Just a stupid plugin to display the help screen. Just a stupid plugin to display the help screen.
""" """
import sys import sys
from glances.globals import iteritems from glances.globals import iteritems
from glances import __version__, psutil_version from glances import __version__, psutil_version

View File

@ -8,6 +8,7 @@
# #
"""Network plugin.""" """Network plugin."""
from __future__ import unicode_literals from __future__ import unicode_literals
from glances.plugins.plugin.model import GlancesPluginModel from glances.plugins.plugin.model import GlancesPluginModel

View File

@ -8,6 +8,7 @@
# #
"""Sensors plugin.""" """Sensors plugin."""
from enum import Enum from enum import Enum
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict, Literal, Any from typing import List, Dict, Literal, Any
@ -369,8 +370,7 @@ class GlancesGrabSensors(object):
sensors_current['label'] = feature.label sensors_current['label'] = feature.label
# Sensors value, limit and unit # Sensors value, limit and unit
sensors_current['unit'] = self.sensor_unit sensors_current['unit'] = self.sensor_unit
sensors_current['value'] = int( sensors_current['value'] = int(getattr(feature, 'current', 0) if getattr(feature, 'current', 0) else 0)
getattr(feature, 'current', 0) if getattr(feature, 'current', 0) else 0)
system_warning = getattr(feature, 'high', None) system_warning = getattr(feature, 'high', None)
system_critical = getattr(feature, 'critical', None) system_critical = getattr(feature, 'critical', None)
sensors_current['warning'] = int(system_warning) if system_warning is not None else None sensors_current['warning'] = int(system_warning) if system_warning is not None else None

View File

@ -97,7 +97,7 @@ class GlancesSNMPClient(object):
cmdgen.UdpTransportTarget((self.host, self.port)), cmdgen.UdpTransportTarget((self.host, self.port)),
non_repeaters, non_repeaters,
max_repetitions, max_repetitions,
*oid *oid,
) )
if self.version.startswith('2'): if self.version.startswith('2'):
errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd( errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd(
@ -105,7 +105,7 @@ class GlancesSNMPClient(object):
cmdgen.UdpTransportTarget((self.host, self.port)), cmdgen.UdpTransportTarget((self.host, self.port)),
non_repeaters, non_repeaters,
max_repetitions, max_repetitions,
*oid *oid,
) )
else: else:
# Bulk request are not available with SNMP version 1 # Bulk request are not available with SNMP version 1

View File

@ -4,6 +4,13 @@ skip-string-normalization = true
exclude = '\./glances/outputs/static/*' exclude = '\./glances/outputs/static/*'
[tool.ruff] [tool.ruff]
line-length = 120
target-version = "py38"
[tool.ruff.format]
quote-style = "preserve"
[tool.ruff.lint]
# Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default. # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
select = ["E", "F"] select = ["E", "F"]
ignore = [] ignore = []
@ -34,18 +41,13 @@ exclude = [
"dist", "dist",
"node_modules", "node_modules",
"venv", "venv",
"docs" "docs",
"./glances/outputs/static/*"
] ]
# Same as Black.
line-length = 120
# Allow unused variables when underscore-prefixed. # Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
# Assume Python 3.11 [tool.ruff.lint.mccabe]
target-version = "py311"
[tool.ruff.mccabe]
# Unlike Flake8, default to a complexity level of 10. # Unlike Flake8, default to a complexity level of 10.
max-complexity = 10 max-complexity = 10

1
run.py
View File

@ -3,6 +3,7 @@
import re import re
import sys import sys
from glances import main from glances import main
if __name__ == '__main__': if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main()) sys.exit(main())

View File

@ -32,16 +32,20 @@ with open('README.rst', encoding='utf-8') as f:
def get_data_files(): def get_data_files():
data_files = [ data_files = [
('share/doc/glances', ['AUTHORS', 'COPYING', 'NEWS.rst', 'README.rst', "SECURITY.md", (
'CONTRIBUTING.md', 'conf/glances.conf']), 'share/doc/glances',
('share/man/man1', ['docs/man/glances.1']) ['AUTHORS', 'COPYING', 'NEWS.rst', 'README.rst', "SECURITY.md", 'CONTRIBUTING.md', 'conf/glances.conf'],
),
('share/man/man1', ['docs/man/glances.1']),
] ]
return data_files return data_files
with open('requirements.txt') as f: with open('requirements.txt') as f:
required = f.read().splitlines() required = f.read().splitlines()
def get_install_requires(): def get_install_requires():
requires = required requires = required
if sys.platform.startswith('win'): if sys.platform.startswith('win'):
@ -59,10 +63,23 @@ def get_install_extras_require():
'browser': ['zeroconf>=0.19.1'], 'browser': ['zeroconf>=0.19.1'],
'cloud': ['requests'], 'cloud': ['requests'],
'containers': ['docker>=6.1.1', 'python-dateutil', 'six', 'podman', 'packaging'], 'containers': ['docker>=6.1.1', 'python-dateutil', 'six', 'podman', 'packaging'],
'export': ['bernhard', 'cassandra-driver', 'elasticsearch', 'graphitesender', 'export': [
'ibmcloudant', 'influxdb>=1.0.0', 'influxdb-client', 'pymongo', 'bernhard',
'kafka-python', 'pika', 'paho-mqtt', 'potsdb', 'prometheus_client', 'cassandra-driver',
'pyzmq', 'statsd'], 'elasticsearch',
'graphitesender',
'ibmcloudant',
'influxdb>=1.0.0',
'influxdb-client',
'pymongo',
'kafka-python',
'pika',
'paho-mqtt',
'potsdb',
'prometheus_client',
'pyzmq',
'statsd',
],
'gpu': ['nvidia-ml-py'], 'gpu': ['nvidia-ml-py'],
'graph': ['pygal'], 'graph': ['pygal'],
'ip': ['netifaces'], 'ip': ['netifaces'],
@ -71,7 +88,7 @@ def get_install_extras_require():
'snmp': ['pysnmp'], 'snmp': ['pysnmp'],
'sparklines': ['sparklines'], 'sparklines': ['sparklines'],
'web': ['fastapi', 'uvicorn', 'jinja2', 'requests'], 'web': ['fastapi', 'uvicorn', 'jinja2', 'requests'],
'wifi': ['wifi'] 'wifi': ['wifi'],
} }
if sys.platform.startswith('linux'): if sys.platform.startswith('linux'):
extras_require['sensors'] = ['batinfo'] extras_require['sensors'] = ['batinfo']
@ -94,6 +111,7 @@ class tests(Command):
def run(self): def run(self):
import subprocess import subprocess
import sys import sys
for t in glob.glob('unittest-core.py'): for t in glob.glob('unittest-core.py'):
ret = subprocess.call([sys.executable, t]) != 0 ret = subprocess.call([sys.executable, t]) != 0
if ret != 0: if ret != 0:
@ -138,6 +156,6 @@ setup(
'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.12',
'Topic :: System :: Monitoring' 'Topic :: System :: Monitoring',
] ],
) )

View File

@ -45,8 +45,7 @@ test_config = core.get_config()
test_args = core.get_args() test_args = core.get_args()
# Init Glances stats # Init Glances stats
stats = GlancesStats(config=test_config, stats = GlancesStats(config=test_config, args=test_args)
args=test_args)
# Unitest class # Unitest class
# ============== # ==============
@ -78,7 +77,14 @@ class TestGlances(unittest.TestCase):
self.assertIsInstance(plugin_instance.get_raw(), (dict, list)) self.assertIsInstance(plugin_instance.get_raw(), (dict, list))
if plugin_instance.history_enable() and isinstance(plugin_instance.get_raw(), dict): if plugin_instance.history_enable() and isinstance(plugin_instance.get_raw(), dict):
self.assertEqual(plugin_instance.get_key(), None) self.assertEqual(plugin_instance.get_key(), None)
self.assertTrue(all([f in [h['name'] for h in plugin_instance.items_history_list] for f in plugin_instance.get_raw_history()])) self.assertTrue(
all(
[
f in [h['name'] for h in plugin_instance.items_history_list]
for f in plugin_instance.get_raw_history()
]
)
)
elif plugin_instance.history_enable() and isinstance(plugin_instance.get_raw(), list): elif plugin_instance.history_enable() and isinstance(plugin_instance.get_raw(), list):
self.assertNotEqual(plugin_instance.get_key(), None) self.assertNotEqual(plugin_instance.get_key(), None)
@ -135,11 +141,17 @@ class TestGlances(unittest.TestCase):
if isinstance(plugin_instance.get_raw(), dict): if isinstance(plugin_instance.get_raw(), dict):
first_history_field = plugin_instance.get_items_history_list()[0]['name'] first_history_field = plugin_instance.get_items_history_list()[0]['name']
elif isinstance(plugin_instance.get_raw(), list): elif isinstance(plugin_instance.get_raw(), list):
first_history_field = '_'.join([plugin_instance.get_raw()[0][plugin_instance.get_key()], first_history_field = '_'.join(
plugin_instance.get_items_history_list()[0]['name']]) [
plugin_instance.get_raw()[0][plugin_instance.get_key()],
plugin_instance.get_items_history_list()[0]['name'],
]
)
self.assertEqual(len(plugin_instance.get_raw_history(first_history_field)), 2) self.assertEqual(len(plugin_instance.get_raw_history(first_history_field)), 2)
self.assertGreater(plugin_instance.get_raw_history(first_history_field)[1][0], self.assertGreater(
plugin_instance.get_raw_history(first_history_field)[0][0]) plugin_instance.get_raw_history(first_history_field)[1][0],
plugin_instance.get_raw_history(first_history_field)[0][0],
)
# Update stats (add third element) # Update stats (add third element)
plugin_instance.update() plugin_instance.update()
@ -158,10 +170,8 @@ class TestGlances(unittest.TestCase):
elif isinstance(plugin_instance.get_raw(), list): elif isinstance(plugin_instance.get_raw(), list):
first_history_field = plugin_instance.get_items_history_list()[0]['name'] first_history_field = plugin_instance.get_items_history_list()[0]['name']
first_item = plugin_instance.get_raw()[0][plugin_instance.get_key()] first_item = plugin_instance.get_raw()[0][plugin_instance.get_key()]
self.assertIsInstance(plugin_instance.get_views(item=first_item, self.assertIsInstance(plugin_instance.get_views(item=first_item, key=first_history_field), dict)
key=first_history_field), dict) self.assertTrue('decoration' in plugin_instance.get_views(item=first_item, key=first_history_field))
self.assertTrue('decoration' in plugin_instance.get_views(item=first_item,
key=first_history_field))
self.assertIsInstance(json.loads(plugin_instance.get_json_views()), dict) self.assertIsInstance(json.loads(plugin_instance.get_json_views()), dict)
self.assertEqual(json.loads(plugin_instance.get_json_views()), plugin_instance.get_views()) self.assertEqual(json.loads(plugin_instance.get_json_views()), plugin_instance.get_views())
@ -352,12 +362,14 @@ class TestGlances(unittest.TestCase):
def test_016_subsample(self): def test_016_subsample(self):
"""Test subsampling function.""" """Test subsampling function."""
print('INFO: [TEST_016] Subsampling') print('INFO: [TEST_016] Subsampling')
for l_test in [([1, 2, 3], 4), for l_test in [
([1, 2, 3, 4], 4), ([1, 2, 3], 4),
([1, 2, 3, 4, 5, 6, 7], 4), ([1, 2, 3, 4], 4),
([1, 2, 3, 4, 5, 6, 7, 8], 4), ([1, 2, 3, 4, 5, 6, 7], 4),
(list(range(1, 800)), 4), ([1, 2, 3, 4, 5, 6, 7, 8], 4),
(list(range(1, 8000)), 800)]: (list(range(1, 800)), 4),
(list(range(1, 8000)), 800),
]:
l_subsample = subsample(l_test[0], l_test[1]) l_subsample = subsample(l_test[0], l_test[1])
self.assertLessEqual(len(l_subsample), l_test[1]) self.assertLessEqual(len(l_subsample), l_test[1])
@ -501,8 +513,9 @@ class TestGlances(unittest.TestCase):
plugins_list = stats.getPluginsList() plugins_list = stats.getPluginsList()
for plugin in plugins_list: for plugin in plugins_list:
for method in mandatories_methods: for method in mandatories_methods:
self.assertTrue(hasattr(stats.get_plugin(plugin), method), self.assertTrue(
msg='{} has no method {}()'.format(plugin, method)) hasattr(stats.get_plugin(plugin), method), msg='{} has no method {}()'.format(plugin, method)
)
def test_096_views(self): def test_096_views(self):
"""Test get_views method""" """Test get_views method"""
@ -511,14 +524,14 @@ class TestGlances(unittest.TestCase):
for plugin in plugins_list: for plugin in plugins_list:
stats.get_plugin(plugin).get_raw() stats.get_plugin(plugin).get_raw()
views_grab = stats.get_plugin(plugin).get_views() views_grab = stats.get_plugin(plugin).get_views()
self.assertTrue(isinstance(views_grab, dict), self.assertTrue(isinstance(views_grab, dict), msg='{} view is not a dict'.format(plugin))
msg='{} view is not a dict'.format(plugin))
def test_097_attribute(self): def test_097_attribute(self):
"""Test GlancesAttribute classes""" """Test GlancesAttribute classes"""
print('INFO: [TEST_097] Test attribute') print('INFO: [TEST_097] Test attribute')
# GlancesAttribute # GlancesAttribute
from glances.attribute import GlancesAttribute from glances.attribute import GlancesAttribute
a = GlancesAttribute('a', description='ad', history_max_size=3) a = GlancesAttribute('a', description='ad', history_max_size=3)
self.assertEqual(a.name, 'a') self.assertEqual(a.name, 'a')
self.assertEqual(a.description, 'ad') self.assertEqual(a.description, 'ad')
@ -542,6 +555,7 @@ class TestGlances(unittest.TestCase):
print('INFO: [TEST_098] Test history') print('INFO: [TEST_098] Test history')
# GlancesHistory # GlancesHistory
from glances.history import GlancesHistory from glances.history import GlancesHistory
h = GlancesHistory() h = GlancesHistory()
h.add('a', 1, history_max_size=100) h.add('a', 1, history_max_size=100)
h.add('a', 2, history_max_size=100) h.add('a', 2, history_max_size=100)
@ -633,10 +647,8 @@ class TestGlances(unittest.TestCase):
print('INFO: [TEST_700] Secure functions') print('INFO: [TEST_700] Secure functions')
if WINDOWS: if WINDOWS:
self.assertIn(secure_popen('echo TEST'), ['TEST\n', self.assertIn(secure_popen('echo TEST'), ['TEST\n', 'TEST\r\n'])
'TEST\r\n']) self.assertIn(secure_popen('echo TEST1 && echo TEST2'), ['TEST1\nTEST2\n', 'TEST1\r\nTEST2\r\n'])
self.assertIn(secure_popen('echo TEST1 && echo TEST2'), ['TEST1\nTEST2\n',
'TEST1\r\nTEST2\r\n'])
else: else:
self.assertEqual(secure_popen('echo -n TEST'), 'TEST') self.assertEqual(secure_popen('echo -n TEST'), 'TEST')
self.assertEqual(secure_popen('echo -n TEST1 && echo -n TEST2'), 'TEST1TEST2') self.assertEqual(secure_popen('echo -n TEST1 && echo -n TEST2'), 'TEST1TEST2')
@ -647,6 +659,7 @@ class TestGlances(unittest.TestCase):
def test_800_memory_leak(self): def test_800_memory_leak(self):
"""Memory leak check""" """Memory leak check"""
import tracemalloc import tracemalloc
print('INFO: [TEST_800] Memory leak check') print('INFO: [TEST_800] Memory leak check')
tracemalloc.start() tracemalloc.start()
# 3 iterations just to init the stats and fill the memory # 3 iterations just to init the stats and fill the memory

View File

@ -43,12 +43,9 @@ class TestGlances(unittest.TestCase):
def http_get(self, url, gzip=False): def http_get(self, url, gzip=False):
"""Make the request""" """Make the request"""
if gzip: if gzip:
ret = requests.get(url, ret = requests.get(url, stream=True, headers={'Accept-encoding': 'gzip'})
stream=True,
headers={'Accept-encoding': 'gzip'})
else: else:
ret = requests.get(url, ret = requests.get(url, headers={'Accept-encoding': 'identity'})
headers={'Accept-encoding': 'identity'})
return ret return ret
def test_000_start_server(self): def test_000_start_server(self):
@ -102,9 +99,24 @@ class TestGlances(unittest.TestCase):
self.assertTrue(req.ok) self.assertTrue(req.ok)
if p in ('uptime', 'version', 'psutilversion'): if p in ('uptime', 'version', 'psutilversion'):
self.assertIsInstance(req.json(), text_type) self.assertIsInstance(req.json(), text_type)
elif p in ('fs', 'percpu', 'sensors', 'alert', 'processlist', 'diskio', elif p in (
'hddtemp', 'batpercent', 'network', 'folders', 'amps', 'ports', 'fs',
'irq', 'wifi', 'gpu', 'containers'): 'percpu',
'sensors',
'alert',
'processlist',
'diskio',
'hddtemp',
'batpercent',
'network',
'folders',
'amps',
'ports',
'irq',
'wifi',
'gpu',
'containers',
):
self.assertIsInstance(req.json(), list) self.assertIsInstance(req.json(), list)
if len(req.json()) > 0: if len(req.json()) > 0:
self.assertIsInstance(req.json()[0], dict) self.assertIsInstance(req.json()[0], dict)