From b3c009b22ef6c47a54faa4c8bf4e10bb62caeef4 Mon Sep 17 00:00:00 2001 From: nicolargo Date: Sun, 20 Mar 2022 09:26:06 +0100 Subject: [PATCH] Correct unitary test failed --- glances/__init__.py | 4 +- glances/compat.py | 237 ++++++++++--------------------- glances/exports/csv/__init__.py | 8 +- glances/exports/json/__init__.py | 18 +-- glances/main.py | 2 +- 5 files changed, 85 insertions(+), 184 deletions(-) diff --git a/glances/__init__.py b/glances/__init__.py index d7d8a498..be2a80bb 100644 --- a/glances/__init__.py +++ b/glances/__init__.py @@ -42,7 +42,6 @@ except ImportError: # Import Glances libs # Note: others Glances libs will be imported optionally -from glances.compat import PY3 from glances.logger import logger from glances.main import GlancesMain from glances.timer import Counter @@ -66,8 +65,7 @@ if psutil_version_info < psutil_min_version: sys.exit(1) # Trac malloc is only available on Python 3.4 or higher -if PY3: - import tracemalloc +import tracemalloc def __signal_handler(signal, frame): diff --git a/glances/compat.py b/glances/compat.py index 8adf68c7..e75df810 100644 --- a/glances/compat.py +++ b/glances/compat.py @@ -33,196 +33,111 @@ from datetime import datetime from glances.logger import logger -PY3 = sys.version_info[0] == 3 +import queue +from configparser import ConfigParser, NoOptionError, NoSectionError +from statistics import mean +from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server +from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer +from urllib.request import urlopen +from urllib.error import HTTPError, URLError +from urllib.parse import urlparse -if PY3: - import queue - from configparser import ConfigParser, NoOptionError, NoSectionError - from statistics import mean - from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server - from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer - from urllib.request import urlopen - from urllib.error import HTTPError, URLError - from urllib.parse import urlparse +# Correct issue #1025 by monkey path the xmlrpc lib +from defusedxml.xmlrpc import monkey_patch - # Correct issue #1025 by monkey path the xmlrpc lib - from defusedxml.xmlrpc import monkey_patch +monkey_patch() - monkey_patch() +input = input +range = range +map = map - input = input - range = range - map = map +text_type = str +binary_type = bytes +bool_type = bool +long = int - text_type = str - binary_type = bytes - bool_type = bool - long = int +PermissionError = OSError - PermissionError = OSError +viewkeys = operator.methodcaller('keys') +viewvalues = operator.methodcaller('values') +viewitems = operator.methodcaller('items') - viewkeys = operator.methodcaller('keys') - viewvalues = operator.methodcaller('values') - viewitems = operator.methodcaller('items') - def printandflush(string): - """Print and flush (used by stdout* outputs modules)""" - print(string, flush=True) +def printandflush(string): + """Print and flush (used by stdout* outputs modules)""" + print(string, flush=True) - def to_ascii(s): - """Convert the bytes string to a ASCII string - Useful to remove accent (diacritics) - """ - if isinstance(s, binary_type): - return s.decode() - return s.encode('ascii', 'ignore').decode() +def to_ascii(s): + """Convert the bytes string to a ASCII string - def listitems(d): - return list(d.items()) + Useful to remove accent (diacritics) + """ + if isinstance(s, binary_type): + return s.decode() + return s.encode('ascii', 'ignore').decode() - def listkeys(d): - return list(d.keys()) - def listvalues(d): - return list(d.values()) +def listitems(d): + return list(d.items()) - def iteritems(d): - return iter(d.items()) - def iterkeys(d): - return iter(d.keys()) +def listkeys(d): + return list(d.keys()) - def itervalues(d): - return iter(d.values()) - def u(s, errors='replace'): - if isinstance(s, text_type): - return s - return s.decode('utf-8', errors=errors) +def listvalues(d): + return list(d.values()) - def b(s, errors='replace'): - if isinstance(s, binary_type): - return s - return s.encode('utf-8', errors=errors) - def n(s): - '''Only in Python 2... - from future.utils import bytes_to_native_str as n - ''' +def iteritems(d): + return iter(d.items()) + + +def iterkeys(d): + return iter(d.keys()) + + +def itervalues(d): + return iter(d.values()) + + +def u(s, errors='replace'): + if isinstance(s, text_type): return s + return s.decode('utf-8', errors=errors) - def nativestr(s, errors='replace'): - if isinstance(s, text_type): - return s - elif isinstance(s, (int, float)): - return s.__str__() - else: - return s.decode('utf-8', errors=errors) - def system_exec(command): - """Execute a system command and return the result as a str""" - try: - res = subprocess.run(command.split(' '), stdout=subprocess.PIPE).stdout.decode('utf-8') - except Exception as e: - logger.debug('Can not evaluate command {} ({})'.format(command, e)) - res = '' - return res.rstrip() +def b(s, errors='replace'): + if isinstance(s, binary_type): + return s + return s.encode('utf-8', errors=errors) -else: + +def n(s): + '''Only in Python 2... from future.utils import bytes_to_native_str as n - import Queue as queue - from itertools import imap as map - from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError, NoSectionError - from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer - from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport, Server - from urllib2 import urlopen, HTTPError, URLError - from urlparse import urlparse + ''' + return s - # Correct issue #1025 by monkey path the xmlrpc lib - from defusedxml.xmlrpc import monkey_patch - monkey_patch() - - input = raw_input - range = xrange - ConfigParser.read_file = ConfigParser.readfp - - text_type = unicode - binary_type = str - bool_type = types.BooleanType - long = long - - PermissionError = OSError - - viewkeys = operator.methodcaller('viewkeys') - viewvalues = operator.methodcaller('viewvalues') - viewitems = operator.methodcaller('viewitems') - - def printandflush(string): - """Print and flush (used by stdout* outputs modules)""" - print(string) - sys.stdout.flush() - - def mean(numbers): - return float(sum(numbers)) / max(len(numbers), 1) - - def to_ascii(s): - """Convert the unicode 's' to a ASCII string - - Useful to remove accent (diacritics) - """ - if isinstance(s, binary_type): - return s - return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore') - - def listitems(d): - return d.items() - - def listkeys(d): - return d.keys() - - def listvalues(d): - return d.values() - - def iteritems(d): - return d.iteritems() - - def iterkeys(d): - return d.iterkeys() - - def itervalues(d): - return d.itervalues() - - def u(s, errors='replace'): - if isinstance(s, text_type): - return s.encode('utf-8', errors=errors) +def nativestr(s, errors='replace'): + if isinstance(s, text_type): + return s + elif isinstance(s, (int, float)): + return s.__str__() + else: return s.decode('utf-8', errors=errors) - def b(s, errors='replace'): - if isinstance(s, binary_type): - return s - return s.encode('utf-8', errors=errors) - def nativestr(s, errors='replace'): - if isinstance(s, binary_type): - return s - elif isinstance(s, (int, float)): - return s.__str__() - else: - return s.encode('utf-8', errors=errors) - - def system_exec(command): - """Execute a system command and return the resul as a str""" - try: - res = subprocess.check_output(command.split(' ')) - except Exception as e: - logger.debug('Can not execute command {} ({})'.format(command, e)) - res = '' - return res.rstrip() - - -# Globals functions for both Python 2 and 3 +def system_exec(command): + """Execute a system command and return the result as a str""" + try: + res = subprocess.run(command.split(' '), stdout=subprocess.PIPE).stdout.decode('utf-8') + except Exception as e: + logger.debug('Can not evaluate command {} ({})'.format(command, e)) + res = '' + return res.rstrip() def subsample(data, sampling): diff --git a/glances/exports/csv/__init__.py b/glances/exports/csv/__init__.py index 45c3bb23..1b1b8aa9 100644 --- a/glances/exports/csv/__init__.py +++ b/glances/exports/csv/__init__.py @@ -24,7 +24,7 @@ import csv import sys import time -from glances.globals import PY3, iterkeys, itervalues +from glances.globals import iterkeys, itervalues from glances.logger import logger from glances.exports.export import GlancesExport @@ -129,8 +129,4 @@ class Export(GlancesExport): def open_csv_file(file_name, file_mode): - if PY3: - csv_file = open(file_name, file_mode, newline='') - else: - csv_file = open(file_name, file_mode + 'b') - return csv_file + return open(file_name, file_mode, newline='') diff --git a/glances/exports/json/__init__.py b/glances/exports/json/__init__.py index ce642acc..0ba3d399 100644 --- a/glances/exports/json/__init__.py +++ b/glances/exports/json/__init__.py @@ -3,7 +3,7 @@ import sys import json -from glances.globals import PY3, listkeys +from glances.globals import listkeys from glances.logger import logger from glances.exports.export import GlancesExport @@ -21,12 +21,8 @@ class Export(GlancesExport): # Set the JSON output file try: - if PY3: - self.json_file = open(self.json_filename, 'w') - self.json_file.close() - else: - self.json_file = open(self.json_filename, 'wb') - self.json_file.close() + self.json_file = open(self.json_filename, 'w') + self.json_file.close() except IOError as e: logger.critical("Cannot create the JSON file: {}".format(e)) sys.exit(2) @@ -53,12 +49,8 @@ class Export(GlancesExport): logger.debug("Exporting stats ({}) to JSON file ({})".format(listkeys(self.buffer), self.json_filename)) # Export stats to JSON file - if PY3: - with open(self.json_filename, "w") as self.json_file: - self.json_file.write("{}\n".format(json.dumps(self.buffer))) - else: - with open(self.json_filename, "wb") as self.json_file: - self.json_file.write("{}\n".format(json.dumps(self.buffer))) + with open(self.json_filename, "w") as self.json_file: + self.json_file.write("{}\n".format(json.dumps(self.buffer))) # Reset buffer self.buffer = {} diff --git a/glances/main.py b/glances/main.py index 08734b21..621fd0ed 100644 --- a/glances/main.py +++ b/glances/main.py @@ -697,7 +697,7 @@ Examples of use: if getattr(self.args, 'memory_leak', True) and not self.is_standalone(): logger.critical("Option --memory-leak is only available in the terminal mode") sys.exit(2) - elif getattr(self.args, 'memory_leak', True) and (PY3 or self.is_standalone()): + elif getattr(self.args, 'memory_leak', True) and self.is_standalone(): logger.info('Memory leak detection enabled') self.args.quiet = True if not self.args.stop_after: