Scale back warnings.warn and add stacklevels= where appropriate.
authorScott <[email protected]>
Wed, 12 Jan 2022 17:06:29 +0000 (09:06 -0800)
committerScott <[email protected]>
Wed, 12 Jan 2022 17:06:29 +0000 (09:06 -0800)
14 files changed:
arper.py
base_presence.py
camera_utils.py
decorator_utils.py
executors.py
google_assistant.py
lockfile.py
logging_utils.py
persistent.py
smart_home/lights.py
smart_home/outlets.py
smart_home/registry.py
string_utils.py
unittest_utils.py

index c0cc9f035af4367ce0c84a0e623a2ea6ae320699..a4e8d3e1196a1f683a24a9d43f4ec48fc8890253 100644 (file)
--- a/arper.py
+++ b/arper.py
@@ -128,8 +128,8 @@ class Arper(persistent.Persistent):
                 return cls(cached_state)
             else:
                 msg = f'{cache_file} is invalid: only {len(cached_state)} entries.  Deleting it.'
-                warnings.warn(msg)
                 logger.warning(msg)
+                warnings.warn(msg, stacklevel=2)
                 os.remove(cache_file)
         logger.debug('No usable saved state found')
         return None
index b38b436be2820a3fd36637569d76eaae86d2aee7..405b743f90e33a85394528403f06bce71d153cc8 100755 (executable)
@@ -115,8 +115,8 @@ class PresenceDetection(object):
         except Exception as e:
             logger.exception(e)
             msg = "Can't see the cabin right now; presence detection impared."
-            logger.warning(msg)
             warnings.warn(msg)
+            logger.warning(msg, stacklevel=2)
             self.dark_locations.add(Location.CABIN)
 
     def update_from_cabin(self) -> None:
@@ -136,7 +136,7 @@ class PresenceDetection(object):
             logger.exception(e)
             msg = "Can't see the house right now; presence detection impared."
             logger.warning(msg)
-            warnings.warn(msg)
+            warnings.warn(msg, stacklevel=2)
             self.dark_locations.add(Location.HOUSE)
 
     def read_persisted_macs_file(
@@ -200,7 +200,7 @@ class PresenceDetection(object):
         if len(self.dark_locations) > 0:
             msg = f"Can't see {self.dark_locations} right now; answer confidence impacted"
             logger.warning(msg)
-            warnings.warn(msg)
+            warnings.warn(msg, stacklevel=2)
         logger.debug(f'Looking for {name}...')
 
         if name is Person.UNKNOWN:
index e69eddb7b3cec5faf915dd6bc23243b261d26858..83664fdc1bad65cb5e9ee4f70de4161df4fad832 100644 (file)
@@ -84,7 +84,7 @@ def fetch_camera_image_from_video_server(
         logger.exception(e)
     msg = f"Got a bad image or HTTP error from {url}; returning None."
     logger.warning(msg)
-    warnings.warn(msg)
+    warnings.warn(msg, stacklevel=2)
     return None
 
 
@@ -135,8 +135,8 @@ def fetch_camera_image_from_rtsp_stream(
     except Exception as e:
         logger.exception(e)
     msg = "Failed to retrieve image via RTSP {stream}, returning None."
-    warnings.warn(msg)
     logger.warning(msg)
+    warnings.warn(msg, stacklevel=2)
     return None
 
 
@@ -165,7 +165,7 @@ def _fetch_camera_image(
         )
     msg = "Failed to retieve image from both video server and direct RTSP stream"
     logger.warning(msg)
-    warnings.warn(msg)
+    warnings.warn(msg, stacklevel=2)
     return RawJpgHsv(None, None, None)
 
 
index 07ad881f63a613de38d82d9a54babce92127b1b5..752fb919df35dc8ff5f93aba672b9d10bc1efb19 100644 (file)
@@ -508,7 +508,6 @@ def thunkify(func):
                 exc[1] = sys.exc_info()  # (type, value, traceback)
                 msg = f"Thunkify has thrown an exception (will be raised on thunk()):\n{traceback.format_exc()}"
                 logger.warning(msg)
-                warnings.warn(msg)
             finally:
                 wait_event.set()
 
index 336f2c72e2685157db362921ce2384fb1476423a..6ccd7b675c760315d05158d68dad0768cc0f0871 100644 (file)
@@ -493,7 +493,6 @@ class WeightedRandomRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):
                     return worker
         msg = 'Unexpectedly could not find a worker, retrying...'
         logger.warning(msg)
-        warnings.warn(msg)
         return None
 
 
@@ -530,7 +529,6 @@ class RoundRobinRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):
             if x == self.index:
                 msg = 'Unexpectedly could not find a worker, retrying...'
                 logger.warning(msg)
-                warnings.warn(msg)
                 return None
 
 
@@ -777,7 +775,6 @@ class RemoteExecutor(BaseExecutor):
                     msg += 'We\'re a backup and this may be caused by the original (or some '
                     msg += 'other backup) already finishing this work.  Ignoring this.'
                     logger.warning(msg)
-                    warnings.warn(msg)
                     return None
 
         # Kick off the work.  Note that if this fails we let
@@ -851,7 +848,6 @@ class RemoteExecutor(BaseExecutor):
             if p is not None:
                 msg = f"{bundle}: Failed to wrap up \"done\" bundle, re-waiting on active ssh."
                 logger.warning(msg)
-                warnings.warn(msg)
                 return self.wait_for_process(p, bundle, depth + 1)
             else:
                 self.status.record_release_worker(
index 041648ca4f15e9db4ce1b1df2862d948ec450325..49c08d3c5efded9bc61e8f647d4c1deff98f5768 100644 (file)
@@ -96,7 +96,7 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
                     logger.exception(e)
                     msg = 'Unable to parse Google assistant\'s response.'
                     logger.warning(msg)
-                    warnings.warn(msg)
+                    warnings.warn(msg, stacklevel=3)
                     audio_transcription = None
         return GoogleResponse(
             success=success,
index 7f10cc1f5894155c65ca352183afc0ea6d81fa37..8a71ca769900983689479157de0cb3132ab731a9 100644 (file)
@@ -90,7 +90,6 @@ class LockFile(object):
             pass
         msg = f'Could not acquire {self.lockfile}.'
         logger.warning(msg)
-        warnings.warn(msg)
         return False
 
     def acquire_with_retries(
@@ -127,7 +126,6 @@ class LockFile(object):
             return self
         msg = f"Couldn't acquire {self.lockfile}; giving up."
         logger.warning(msg)
-        warnings.warn(msg)
         raise LockFileException(msg)
 
     def __exit__(self, type, value, traceback):
@@ -178,7 +176,6 @@ class LockFile(object):
                     except OSError:
                         msg = f'Lockfile {self.lockfile}\'s pid ({contents.pid}) is stale; force acquiring'
                         logger.warning(msg)
-                        warnings.warn(msg)
                         self.release()
 
                     # Has the lock expiration expired?
@@ -187,7 +184,6 @@ class LockFile(object):
                         if now > contents.expiration_datetime:
                             msg = f'Lockfile {self.lockfile} expiration time has passed; force acquiring'
                             logger.warning(msg)
-                            warnings.warn(msg)
                             self.release()
         except Exception:
             pass
index 20a57f7c953ff9474f58a7057d5c20ef757aae2e..f7fac03cd913ef22106fbc25cea821e161e62187 100644 (file)
@@ -13,7 +13,6 @@ import os
 import random
 import sys
 from typing import Callable, Iterable, Mapping, Optional
-import warnings
 
 from overrides import overrides
 import pytz
@@ -526,7 +525,6 @@ def initialize_logging(logger=None) -> logging.Logger:
     if config.config['logging_clear_preexisting_handlers'] and preexisting_handlers_count > 0:
         msg = 'Logging cleared {preexisting_handlers_count} global handlers (--logging_clear_preexisting_handlers)'
         logger.warning(msg)
-        warnings.warn(msg)
     logger.debug(f'Logging format specification is "{fmt}"')
     if config.config['logging_debug_threads']:
         logger.debug('...Logging format spec captures tid/pid (--logging_debug_threads)')
index 2751572553ac7c20c7663974c13e17b13f0ab037..83e6900cc18471ae44503a14f3184a2827420190 100644 (file)
@@ -146,7 +146,7 @@ class persistent_autoloaded_singleton(object):
             if not self.instance:
                 msg = 'Loading from cache failed.'
                 logger.warning(msg)
-                warnings.warn(msg)
+                warnings.warn(msg, stacklevel=2)
                 logger.debug(f'Attempting to instantiate {cls.__name__} directly.')
                 self.instance = cls(*args, **kwargs)
             else:
index 44b3634cd5fb9f5c84620762701f120db8bd3977..237d4e0d93b6c294a13eb95a504d2e125738725c 100644 (file)
@@ -11,7 +11,6 @@ import re
 import subprocess
 import sys
 from typing import Any, Dict, List, Optional, Tuple
-import warnings
 
 from overrides import overrides
 import tinytuya as tt
@@ -49,7 +48,6 @@ def tplink_light_command(command: str) -> bool:
     if signal != 0:
         msg = f'{command} died with signal {signal}'
         logger.warning(msg)
-        warnings.warn(msg)
         logging_utils.hlog(msg)
         return False
     else:
@@ -57,7 +55,6 @@ def tplink_light_command(command: str) -> bool:
         if exit_value != 0:
             msg = f'{command} failed, exited {exit_value}'
             logger.warning(msg)
-            warnings.warn(msg)
             logging_utils.hlog(msg)
             return False
     logger.debug(f'{command} succeeded.')
index 6cc8d57ec065beabc5652c1015fa75df3307cd97..c079cfd09d9cbbfbb8595379770ebc1c8d7497ae 100644 (file)
@@ -13,7 +13,6 @@ import re
 import subprocess
 import sys
 from typing import Any, Dict, List, Optional
-import warnings
 
 from meross_iot.http_api import MerossHttpClient
 from meross_iot.manager import MerossManager
@@ -51,7 +50,6 @@ def tplink_outlet_command(command: str) -> bool:
     if signal != 0:
         msg = f'{command} died with signal {signal}'
         logger.warning(msg)
-        warnings.warn(msg)
         logging_utils.hlog(msg)
         return False
     else:
@@ -59,7 +57,6 @@ def tplink_outlet_command(command: str) -> bool:
         if exit_value != 0:
             msg = f'{command} failed, exited {exit_value}'
             logger.warning(msg)
-            warnings.warn(msg)
             logging_utils.hlog(msg)
             return False
     logger.debug(f'{command} succeeded.')
index 20fb3f43807bf0dbbd45fa7f5c36ed8f4d1bc917..75fe05256cc9f51cdc06a497fe9304917a510218 100644 (file)
@@ -3,7 +3,6 @@
 import logging
 import re
 from typing import List, Optional, Set
-import warnings
 
 import argparse_utils
 import config
@@ -64,9 +63,8 @@ class SmartHomeRegistry(object):
             try:
                 (mac, name, keywords) = line.split(",")
             except ValueError:
-                msg = f'SH-CONFIG> {line} is malformed?!'
+                msg = f'SH-CONFIG> "{line}" is malformed?!  Skipping it.'
                 logger.warning(msg)
-                warnings.warn(msg)
                 continue
             mac = mac.strip()
             name = name.strip()
@@ -190,7 +188,6 @@ class SmartHomeRegistry(object):
                 return device.Device(name, mac, kws)
         msg = f'{mac} is not a known smart home device, returning None'
         logger.warning(msg)
-        warnings.warn(msg)
         return None
 
     def query(self, query: str) -> List[device.Device]:
index b93dc93aaa78e9b1b901499169c3b902f3445a59..6eda2783ea7aafa67bcc4f492825c2aa1bab1cc9 100644 (file)
@@ -1100,7 +1100,6 @@ def to_date(in_str: str) -> Optional[datetime.date]:
     except dp.ParseException:
         msg = f'Unable to parse date {in_str}.'
         logger.warning(msg)
-        warnings.warn(msg)
     return None
 
 
@@ -1116,7 +1115,6 @@ def valid_date(in_str: str) -> bool:
     except dp.ParseException:
         msg = f'Unable to parse date {in_str}.'
         logger.warning(msg)
-        warnings.warn(msg)
     return False
 
 
@@ -1133,7 +1131,6 @@ def to_datetime(in_str: str) -> Optional[datetime.datetime]:
     except ValueError:
         msg = f'Unable to parse datetime {in_str}.'
         logger.warning(msg)
-        warnings.warn(msg)
     return None
 
 
@@ -1146,7 +1143,6 @@ def valid_datetime(in_str: str) -> bool:
         return True
     msg = f'Unable to parse datetime {in_str}.'
     logger.warning(msg)
-    warnings.warn(msg)
     return False
 
 
@@ -1477,7 +1473,7 @@ def chunk(txt: str, chunk_size):
     if len(txt) % chunk_size != 0:
         msg = f'String to chunk\'s length ({len(txt)} is not an even multiple of chunk_size ({chunk_size})'
         logger.warning(msg)
-        warnings.warn(msg)
+        warnings.warn(msg, stacklevel=2)
     for x in range(0, len(txt), chunk_size):
         yield txt[x:x+chunk_size]
 
index 270e20d1e268112f543ac70d4e096745b1861d1c..8c9a1202f99d46708b8abfd083fc3f57256fcacc 100644 (file)
@@ -18,7 +18,6 @@ import time
 import tempfile
 from typing import Callable
 import unittest
-import warnings
 
 import bootstrap
 import config
@@ -81,7 +80,6 @@ def check_method_for_perf_regressions(func: Callable) -> Callable:
             logger.exception(e)
             msg = f'Unable to load perfdb from {_db}'
             logger.warning(msg)
-            warnings.warn(msg)
             perfdb = {}
 
         # This is a unique identifier for a test: filepath!function