[Git][NTPsec/ntpsec][master] shallow attempt at pep-0008 conformance

Gary E. Miller gitlab at mg.gitlab.com
Mon Aug 13 01:51:41 UTC 2018


Gary E. Miller pushed to branch master at NTPsec / ntpsec


Commits:
bfa2e3b5 by James Browning at 2018-08-13T00:23:51Z
shallow attempt at pep-0008 conformance

- - - - -


20 changed files:

- devel/python_paths.py
- ntpclients/ntpdig.py
- ntpclients/ntpkeygen.py
- ntpclients/ntploggps.py
- ntpclients/ntplogtemp.py
- ntpclients/ntpmon.py
- ntpclients/ntpq.py
- ntpclients/ntpsnmpd.py
- ntpclients/ntpsweep.py
- ntpclients/ntptrace.py
- ntpclients/ntpviz.py
- ntpclients/ntpwait.py
- pylib/agentx.py
- pylib/packet.py
- pylib/util.py
- tests/pylib/test_agentx.py
- tests/pylib/test_agentx_packet.py
- tests/pylib/test_packet.py
- tests/pylib/test_statfiles.py
- tests/pylib/test_util.py


Changes:

=====================================
devel/python_paths.py
=====================================
@@ -101,10 +101,11 @@ def main(argv=None):  # pylint: disable=too-many-locals
         this_file.close()
         result = PythonCommands(['ssh', '-T', argv[1], 'python'], this_script)
         if result and result[-1]:
-            result += ['']  #  Add trailing EOL if needed
+            result += ['']  # Add trailing EOL if needed
         sys.stdout.write('\n'.join(result))
         return 0
-    python_list = ExeFilter(FileList(MakePatterns(GetPaths(), PYTHON_PATTERNS)))
+    python_list = ExeFilter(FileList(MakePatterns(GetPaths(),
+                            PYTHON_PATTERNS)))
     done = set()
     unique = total = 0
     for python in python_list:
@@ -141,7 +142,8 @@ def main(argv=None):  # pylint: disable=too-many-locals
             _print(' Prefix(sys): %s' % valdict['sys-prefix'])
             _print(' Prefix(std): %s' % valdict['std-prefix'])
             _print(' Prefix(exec): %s' % valdict['exec-prefix'])
-    plural = unique != 1 and 's' or ''  # pylint: disable=consider-using-ternary
+    plural = unique != 1 and 's' or ''
+    # pylint: disable=consider-using-ternary
     print('Found %d unique Python installation%s out of %d total'
           % (unique, plural, total))
     return 0


=====================================
ntpclients/ntpdig.py
=====================================
@@ -7,7 +7,22 @@ ntpdig - simple SNTP client
 # SPDX-License-Identifier: BSD-2-clause
 # This code runs identically under Python 2 and Python 3. Keep it that way!
 from __future__ import print_function, division
+import getopt
+import math
+import select
+import socket
+import sys
+import time
 
+try:
+    import ntp.magic
+    import ntp.packet
+    import ntp.util
+except ImportError as e:
+    sys.stderr.write(
+        "ntpdig: can't find Python NTP library -- check PYTHONPATH.\n")
+    sys.stderr.write("%s\n" % e)
+    sys.exit(1)
 # This code is somewhat stripped down from the legacy C version.  It
 # does however have one additional major feature; it can filter
 # out falsetickers from multiple samples, like the ntpdate of old,
@@ -39,23 +54,6 @@ from __future__ import print_function, division
 #
 # The one new option in this version is -p, borrowed from ntpdate.
 
-import sys
-import socket
-import select
-import time
-import getopt
-import math
-
-try:
-    import ntp.magic
-    import ntp.packet
-    import ntp.util
-except ImportError as e:
-    sys.stderr.write(
-        "ntpdig: can't find Python NTP library -- check PYTHONPATH.\n")
-    sys.stderr.write("%s\n" % e)
-    sys.exit(1)
-
 
 def read_append(s, packets, packet, sockaddr):
     d, a = s.recvfrom(1024)
@@ -233,6 +231,7 @@ def report(packet, json):
             say(" " + packet.resolved)
         say(" s%d %s\n" % (packet.stratum, packet.leap()))
 
+
 usage = """
 USAGE:  ntpdig [-<flag> [<val>] | --<name>[{=| }<val>]]...
                 [ hostname-or-IP ...]
@@ -261,6 +260,7 @@ USAGE:  ntpdig [-<flag> [<val>] | --<name>[{=| }<val>]]...
    -h no  help            Display extended usage information and exit
 """
 
+
 if __name__ == '__main__':
     try:
         try:
@@ -367,7 +367,8 @@ if __name__ == '__main__':
         try:
             credentials = ntp.packet.Authenticator(keyfile)
         except (OSError, IOError):
-            sys.stderr.write("ntpdig: %s nonexistent or unreadable\n" % keyfile)
+            sys.stderr.write("ntpdig: %s nonexistent or unreadable\n" %
+                             keyfile)
             raise SystemExit(1)
         if credentials:
             try:


=====================================
ntpclients/ntpkeygen.py
=====================================
@@ -79,6 +79,7 @@ def fheader(file,       # file name id
         sys.stderr.write("Key file creation or link failed.\n")
         raise SystemExit(1)
 
+
 if __name__ == '__main__':
     try:
         (options, arguments) = getopt.getopt(sys.argv[1:], "hM", ["help"])


=====================================
ntpclients/ntploggps.py
=====================================
@@ -52,6 +52,7 @@ except ImportError as e:
     sys.stderr.write("%s\n" % e)
     sys.exit(1)
 
+
 def logging_setup():
     "Create logging object"
     logFormat = logging.Formatter('%(message)s')
@@ -175,6 +176,7 @@ class GpsPoller(threading.Thread):
             return t
         return gps.isotime(t)
 
+
 if __name__ == '__main__':
     # this is the main thread
     if args.verbose:


=====================================
ntpclients/ntplogtemp.py
=====================================
@@ -39,6 +39,7 @@ except ImportError as e:
     sys.stderr.write("%s\n" % e)
     sys.exit(1)
 
+
 def run_binary(cmd):
     """\
 Run a binary
@@ -96,12 +97,14 @@ class CpuTemp:
                 if match and match.group(1):
                     _now = int(time.time())
                     _cpu_temprature = match.group(1)
-                    _data.append('%d LM%s %s' % (_now, _index, _cpu_temprature))
+                    _data.append('%d LM%s %s' % (_now, _index,
+                                                 _cpu_temprature))
                     _index += 1
         else:
             self.has_sensors = False
             if args.verbose:
-                sys.stderr.write("No sensors returned temperatures. Have you run sensors-detect?")
+                sys.stderr.write("No sensors returned temperatures. ",
+                                 "Have you run sensors-detect?")
 
         return _data
 


=====================================
ntpclients/ntpmon.py
=====================================
@@ -191,6 +191,7 @@ class OutputContext:
     def __exit__(self, extype_unused, value_unused, traceback_unused):
         curses.endwin()
 
+
 usage = '''
 USAGE: ntpmon [-nudV] [-l logfile] [-D lvl] [host]
   Flg Arg Option-Name    Description


=====================================
ntpclients/ntpq.py
=====================================
@@ -1730,10 +1730,9 @@ if __name__ == '__main__':
         interpreter.chosts.append((DEFHOST, session.ai_family))
 
     if (len(interpreter.ccmds) == 0 and
-                not interpreter.interactive and
-                os.isatty(0) and
-                os.isatty(1)
-            ):
+            not interpreter.interactive and
+            os.isatty(0) and
+            os.isatty(1)):
         interpreter.interactive = True
 
     try:


=====================================
ntpclients/ntpsnmpd.py
=====================================
@@ -149,8 +149,8 @@ class DataSource(ntp.agentx.MIBControl):
         self.addNode((1, 5, 1, 0),  # ntpEntNotifMessage utf8str
                      self.cbr_entNotifMessage)
         # block 2 # all compliance statements
-        #print(repr(self.oidTree))
-        #print(self.oidTree[1]["subids"][1][1][0])
+        # print(repr(self.oidTree))
+        # print(self.oidTree[1]["subids"][1][1][0])
         self.session = ntp.packet.ControlSession()
         self.hostname = hostname if hostname else DEFHOST
         self.session.openhost(self.hostname)


=====================================
ntpclients/ntpsweep.py
=====================================
@@ -5,7 +5,7 @@ ntpsweep - print various information about given NTP servers
 USAGE: ntpsweep [-<flag> [<val>] | --<name>[{=| }<val>]]... [hostfile]
 
     -h, --host=str             Host to execute actions on
-    -l, --host-list=str        Comma-delimited list of Hosts to 
+    -l, --host-list=str        Comma-delimited list of Hosts to
                                    execute actions on
     -p, --peers                Recursively list all peers a host syncs to
     -m, --maxlevel=num         Traverse peers up to this level
@@ -38,6 +38,7 @@ except ImportError as e:
     sys.stderr.write("%s\n" % e)
     sys.exit(1)
 
+
 def ntp_peers(host):
     """Return: a list of peer IP addrs for a specified host,
             empty list if query failed.
@@ -145,6 +146,7 @@ def scan_host(host, level):
             printhost = printhost.replace(strip, "")
         print("%-32s  ?" % printhost[:32])
 
+
 if __name__ == '__main__':
     try:
         (options, arguments) = getopt.getopt(


=====================================
ntpclients/ntptrace.py
=====================================
@@ -26,6 +26,7 @@ except ImportError as e:
     sys.stderr.write("%s\n" % e)
     sys.exit(1)
 
+
 def get_info(host):
     info = ntp_read_vars(0, [], host)
     if info is None or 'stratum' not in info:


=====================================
ntpclients/ntpviz.py
=====================================
@@ -109,6 +109,7 @@ class UTC(datetime.tzinfo):
     def dst(self, dt):
         return datetime.timedelta(0)
 
+
 try:
     import ntp.statfiles
     import ntp.util
@@ -1258,6 +1259,7 @@ plot \
                'title': "Local Clock Time Offset Histogram"}
         return ret
 
+
 # Multiplotting can't live inside NTPViz because it consumes a list
 # of such objects, not a single one.
 
@@ -1294,6 +1296,7 @@ plot \\
     ret['plot'] = plot + plot_data
     return ret
 
+
 # here is how to create the base64 from an image file:
 # with open("path/to/file.png", "rb") as f:
 #    data = f.read()


=====================================
ntpclients/ntpwait.py
=====================================
@@ -36,6 +36,7 @@ except ImportError as e:
     sys.stderr.write("%s\n" % e)
     sys.exit(1)
 
+
 class Unbuffered(object):
     def __init__(self, stream):
         self.stream = stream


=====================================
pylib/agentx.py
=====================================
@@ -306,7 +306,7 @@ class PacketControl:
                    callback=None):
         encoded = packet.encode()
         self.log("Sending packet (with reply: %s): %s" % (expectsReply,
-                                                            repr(packet)), 4)
+                                                          repr(packet)), 4)
         self.socket.sendall(encoded)
         if expectsReply is True:
             index = (packet.sessionID,


=====================================
pylib/packet.py
=====================================
@@ -1178,7 +1178,7 @@ class ControlSession:
                                                   self.debug, th))
 
         if ((rpkt.version() > ntp.magic.NTP_VERSION) or
-            (rpkt.version() < ntp.magic.NTP_OLDVERSION)):
+           (rpkt.version() < ntp.magic.NTP_OLDVERSION)):
             warndbg("Fragment received with version %d"
                     % rpkt.version(), 1)
             return False


=====================================
pylib/util.py
=====================================
@@ -56,6 +56,7 @@ def check_unicode():  # pragma: no cover
         return True  # needed by ntpmon
     return False
 
+
 def deunicode_units():  # pragma: no cover
     "Under certain conditions it is not possible to force unicode output, "
     "this overwrites units that contain unicode with safe versions"
@@ -71,6 +72,7 @@ def deunicode_units():  # pragma: no cover
     UNIT_US = new_us
     UNIT_PPK = new_ppk
 
+
 # Variables that have units
 S_VARS = ("tai", "poll")
 MS_VARS = ("rootdelay", "rootdisp", "rootdist", "offset", "sys_jitter",
@@ -272,7 +274,7 @@ def stringfiltcooker(data):
         part = rescalestring(part, mostcommon)
         fitted = fitinfield(part, 7)
         cooked.append(fitted)
-    rendered = " ".join(cooked) + " " + UNITS_SEC[mostcommon + \
+    rendered = " ".join(cooked) + " " + UNITS_SEC[mostcommon +
                                                   UNITS_SEC.index(UNIT_MS)]
     return rendered
 


=====================================
tests/pylib/test_agentx.py
=====================================
@@ -61,8 +61,8 @@ class TestMIBControl(unittest.TestCase):
         self.assertEqual(c.oidTree,
                          {0: {"reader": 1, "writer": 2, "subids": None},
                           1: {"reader": 1, "writer": 2, "subids":
-                             {2: {"reader": None, "writer": None, "subids": {
-                                 3: {"reader": 1, "writer": 2, "subids": None}}}}},
+                              {2: {"reader": None, "writer": None, "subids": {
+                                   3: {"reader": 1, "writer": 2, "subids": None}}}}},
                           2: {"reader": None, "writer": None, "subids": 3}})
 
     def test_getOID_andNext(self):
@@ -212,7 +212,7 @@ class TestPacketControl(unittest.TestCase):
         # need jigs for
         # time
         pkts = []
-        recpTimes = []
+        # recpTimes = []
         handler_calls = [0]
 
         def packetEater_jig(self):
@@ -633,7 +633,7 @@ class TestPacketControl(unittest.TestCase):
         handlerCalls = []
         handlerReturns = [AP.ERR_NOERROR, AP.ERR_NOERROR]
         handler = (lambda a, vb: (handlerCalls.append((a, vb)),
-                                      handlerReturns.pop(0))[1])
+                   handlerReturns.pop(0))[1])
         mjig = AX.MIBControl()
         mjig.setVarbinds = ["foo", "bar"]
         mjig.setHandlers = [handler, handler]
@@ -709,6 +709,7 @@ class TestPacketControl(unittest.TestCase):
 
     def test_handle_ResponsePDU(self):
         cbreturn = []
+
         def callback(pkt, origpkt):
             cbreturn.append((pkt, origpkt))
         opkt = AP.PingPDU(True, 42, 4, 50)


=====================================
tests/pylib/test_agentx_packet.py
=====================================
@@ -1088,7 +1088,7 @@ class TestNtpclientsNtpsnmpd(unittest.TestCase):
                           "varbinds": (AX.Varbind(AX.VALUE_OID, (1, 2, 3),
                                                   AX.OID((4, 5, 6), False)),
                                        AX.Varbind(AX.VALUE_OCTET_STR, (1, 2, 4),
-                                                 "blah")),
+                                                  "blah")),
                           "context": "blah"})
 
     def test_IndexAllocPDU(self):
@@ -1189,7 +1189,7 @@ class TestNtpclientsNtpsnmpd(unittest.TestCase):
                           "varbinds": (AX.Varbind(AX.VALUE_OID, (1, 2, 3),
                                                   AX.OID((4, 5, 6), False)),
                                        AX.Varbind(AX.VALUE_OCTET_STR, (1, 2, 4),
-                                                 "blah")),
+                                                  "blah")),
                           "context": "blah"})
 
     def test_IndexDeallocPDU(self):
@@ -1291,7 +1291,7 @@ class TestNtpclientsNtpsnmpd(unittest.TestCase):
                           "varbinds": (AX.Varbind(AX.VALUE_OID, (1, 2, 3),
                                                   AX.OID((4, 5, 6), False)),
                                        AX.Varbind(AX.VALUE_OCTET_STR, (1, 2, 4),
-                                                 "blah")),
+                                                  "blah")),
                           "context": "blah"})
 
     def test_AddAgentCapsPDU(self):
@@ -2416,8 +2416,8 @@ class TestNtpclientsNtpsnmpd(unittest.TestCase):
                            b"\x02\x00\x00\x00"
                            b"\x00\x00\x00\x08\x00\x00\x00\x09"),
                          (AX.GetBulkPDU(True, 1, 2, 3, 1, 5,
-                                       (srch((1, 2), (3, 4), False),
-                                        srch((6, 7), (8, 9), True))),
+                                        (srch((1, 2), (3, 4), False),
+                                         srch((6, 7), (8, 9), True))),
                           b""))
         # Test test set
         self.assertEqual(f(b"\x01\x08\x10\x00"
@@ -2611,7 +2611,7 @@ class TestNtpclientsNtpsnmpd(unittest.TestCase):
                           True, True, True, False])
         # Test partial bytes
         self.assertEqual(bits2bool("\xFF\xE1", 12),  # The extra bit is to
-                         [True, True, True, True,  #   confirm crop
+                         [True, True, True, True,    # confirm crop
                           True, True, True, True,
                           True, True, True, False])
 


=====================================
tests/pylib/test_packet.py
=====================================
@@ -299,7 +299,7 @@ class TestSyncPacket(unittest.TestCase):
         self.assertEqual(errored, "Packet is a runt")
         # Test with extension, runt 16
         data2 = data + ext + "\x00\x11\x22\x33\x44\x55\x66\x77" \
-                "\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"
+                             "\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"
         try:
             cls = self.target(data2)
             errored = False
@@ -502,6 +502,7 @@ class TestSyncPacket(unittest.TestCase):
                          "1970-01-01T00:00:02Z:1970-01-01T00:00:03Z:"
                          "'foobar':machinations>")
 
+
 class TestMisc(unittest.TestCase):
     def test_Peer(self):
         session = SessionJig()
@@ -998,7 +999,7 @@ class TestControlSession(unittest.TestCase):
             cls.passwd = None
             cls.auth.fail_getitem = True
             fakegetpmod.getpass_returns = ["0102030405060708090A"
-                                          "0B0C0D0E0F1011121314"]  # 40 char
+                                           "0B0C0D0E0F1011121314"]  # 40 char
             cls.password()
             self.assertEqual(fakegetpmod.getpass_calls,
                              [("keytype Password: ", None)])


=====================================
tests/pylib/test_statfiles.py
=====================================
@@ -133,10 +133,12 @@ class TestNTPStats(unittest.TestCase):
         fakeglobmod = jigs.GlobModuleJig()
         load_args = []
         load_returns = []
+
         def loadjig(self, statsdir, stem):
             load_args.append((statsdir, stem))
             return load_returns.pop(0)
         process_args = []
+
         def processjig(self, stem, lines):
             process_args.append((stem, lines))
             return [stem + " " + line for line in lines]


=====================================
tests/pylib/test_util.py
=====================================
@@ -36,6 +36,7 @@ class TestPylibUtilMethods(unittest.TestCase):
 
         faketimemod = jigs.TimeModuleJig()
         # We need a test jig
+
         class LogTester:
             def __init__(self):
                 self.written = None
@@ -79,7 +80,7 @@ class TestPylibUtilMethods(unittest.TestCase):
             # Test successful float
             self.assertAlmostEqual(f("5.23", float, "blah %s",
                                      "\nDo the needful\n"),
-                             5.23)
+                                   5.23)
             self.assertEqual(errjig.data, [])
             # Test failure
             try:



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/bfa2e3b5971cdca6a98e237c0abd3d0a3e67c9c3

-- 
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/bfa2e3b5971cdca6a98e237c0abd3d0a3e67c9c3
You're receiving this email because of your account on gitlab.com.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20180813/2843aaa9/attachment-0001.html>


More information about the vc mailing list