Skip to contentSkip to conversation

tests: py: fix python3

PATCH Superseded Shekhar Sharma 3 participants 4 messages May 27, 2019 – May 28, 2019 netfilter

v5 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

PATCH v5 1/1 tests: py: fix python3

This patch converts the 'nft-test.py' file to run on both python 2 and python3.

The version hystory of this patch is:
v1:conversion to py3 by changing the print statements. v2:add the '__future__' package for compatibility with py2 and py3. v3:solves the 'version' problem in argparse by adding a new argument. v4:uses .format() method to make print statements clearer.
v5: updated the shebang and corrected the sequence of import statements.

---
 tests/py/nft-test.py | 44 +++++++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 21 deletions(-)
tests/py/nft-test.py +23 -21
index 1c0afd0e..fe56340c 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python
 #
 # (C) 2014 by Ana Rey Botello <[email protected]>
 #
@@ -13,6 +13,7 @@
 # Thanks to the Outreach Program for Women (OPW) for sponsoring this test
 # infrastructure.
 
+from __future__ import print_function
 import sys
 import os
 import argparse
@@ -436,7 +437,7 @@ def set_delete(table, filename=None, lineno=None):
     '''
     Deletes set and its content.
     '''
-    for set_name in all_set.keys():
+    for set_name in list(all_set.keys()):
         # Check if exists the set
         if not set_exist(set_name, table, filename, lineno):
             reason = "The set %s does not exist, " \
@@ -1002,9 +1003,9 @@ def execute_cmd(cmd, filename, lineno, stdout_log=False, debug=False):
     :param debug: temporarily set these debug flags
     '''
     global log_file
-    print >> log_file, "command: %s" % cmd
+    print("command: {}".format(cmd), file = log_file)
     if debug_option:
-        print cmd
+        print(cmd)
 
     if debug:
         debug_old = nftables.get_debug()
@@ -1198,7 +1199,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
         sys.stdout.flush()
 
         if signal_received == 1:
-            print "\nSignal received. Cleaning up and Exitting..."
+            print("\nSignal received. Cleaning up and Exitting...")
             cleanup_on_exit()
             sys.exit(0)
 
@@ -1305,13 +1306,13 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
     if specific_file:
         if force_all_family_option:
-            print print_result_all(filename, tests, total_warning, total_error,
-                                   total_unit_run)
+            print(print_result_all(filename, tests, total_warning, total_error,
+                                   total_unit_run))
         else:
-            print print_result(filename, tests, total_warning, total_error)
+            print(print_result(filename, tests, total_warning, total_error))
     else:
         if tests == passed and tests > 0:
-            print filename + ": " + Colors.GREEN + "OK" + Colors.ENDC
+            print(filename + ": " + Colors.GREEN + "OK" + Colors.ENDC)
 
     f.close()
     del table_list[:]
@@ -1322,7 +1323,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
 
 def main():
-    parser = argparse.ArgumentParser(description='Run nft tests', version='1.0')
+    parser = argparse.ArgumentParser(description='Run nft tests')
 
     parser.add_argument('filenames', nargs='*', metavar='path/to/file.t',
                         help='Run only these tests')
@@ -1341,6 +1342,10 @@ def main():
                         dest='enable_json',
                         help='test JSON functionality as well')
 
+    parser.add_argument('-v', '--version', action='version',
+                        version= '1.0',
+                        help='prints the version information')
+
     args = parser.parse_args()
     global debug_option, need_fix_option, enable_json_option
     debug_option = args.debug
@@ -1353,15 +1358,15 @@ def main():
     signal.signal(signal.SIGTERM, signal_handler)
 
     if os.getuid() != 0:
-        print "You need to be root to run this, sorry"
+        print("You need to be root to run this, sorry")
         return
 
     # Change working directory to repository root
     os.chdir(TESTS_PATH + "/../..")
 
     if not os.path.exists('src/.libs/libnftables.so'):
-        print "The nftables library does not exist. " \
-              "You need to build the project."
+        print("The nftables library does not exist. "
+              "You need to build the project.")
         return
 
     global nftables
@@ -1411,18 +1416,15 @@ def main():
             run_total += file_unit_run
 
     if test_files == 0:
-        print "No test files to run"
+        print("No test files to run")
     else:
         if not specific_file:
             if force_all_family_option:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d total executed, %d error, %d warning" \
-                      % (test_files, files_ok, tests, run_total, errors,
-                         warnings)
+                print("{} test files, {} files passed, {} unit tests,".format(test_files, files_ok, tests))
+                print("{} total executed, {} error, {} warning".format(run_total, errors, warnings))
             else:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d error, %d warning" \
-                      % (test_files, files_ok, tests, errors, warnings)
+                print("{} test files, {} files passed, {} unit tests".format(test_files, files_ok, tests))
+                print("{} error, {} warning".format(errors, warnings))
 
 
 if __name__ == '__main__':
Signature · 1 line
2.17.1
#1 lore raw
Quoted 35 lines · Shekhar Sharma

This patch converts the 'nft-test.py' file to run on both python 2 and python3.

The version hystory of this patch is:
v1:conversion to py3 by changing the print statements. v2:add the '__future__' package for compatibility with py2 and py3. v3:solves the 'version' problem in argparse by adding a new argument. v4:uses .format() method to make print statements clearer.
v5: updated the shebang and corrected the sequence of import statements.

---
 tests/py/nft-test.py | 44 +++++++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 21 deletions(-)
tests/py/nft-test.py +2 -1
index 1c0afd0e..fe56340c 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python
 #
 # (C) 2014 by Ana Rey Botello <[email protected]>
 #
@@ -13,6 +13,7 @@
 # Thanks to the Outreach Program for Women (OPW) for sponsoring this test
 # infrastructure.
 
+from __future__ import print_function
 import sys
 import os
 import argparse

tests/py/nft-test.py def set_delete(table, filename=None, lineno=None): · line 440

Quoted 5 lines
tests/py/nft-test.py +1 -1
@@ -436,7 +437,7 @@ def set_delete(table, filename=None, lineno=None):
     '''
     Deletes set and its content.
     '''
-    for set_name in all_set.keys():
+    for set_name in list(all_set.keys()):

What exactly is this list() for? This is not a generator expression.

Quoted 52 lines
tests/py/nft-test.py +8 -8
         # Check if exists the set
         if not set_exist(set_name, table, filename, lineno):
             reason = "The set %s does not exist, " \
@@ -1002,9 +1003,9 @@ def execute_cmd(cmd, filename, lineno, stdout_log=False, debug=False):
     :param debug: temporarily set these debug flags
     '''
     global log_file
-    print >> log_file, "command: %s" % cmd
+    print("command: {}".format(cmd), file = log_file)
     if debug_option:
-        print cmd
+        print(cmd)
 
     if debug:
         debug_old = nftables.get_debug()
@@ -1198,7 +1199,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
         sys.stdout.flush()
 
         if signal_received == 1:
-            print "\nSignal received. Cleaning up and Exitting..."
+            print("\nSignal received. Cleaning up and Exitting...")
             cleanup_on_exit()
             sys.exit(0)
 
@@ -1305,13 +1306,13 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
     if specific_file:
         if force_all_family_option:
-            print print_result_all(filename, tests, total_warning, total_error,
-                                   total_unit_run)
+            print(print_result_all(filename, tests, total_warning, total_error,
+                                   total_unit_run))
         else:
-            print print_result(filename, tests, total_warning, total_error)
+            print(print_result(filename, tests, total_warning, total_error))
     else:
         if tests == passed and tests > 0:
-            print filename + ": " + Colors.GREEN + "OK" + Colors.ENDC
+            print(filename + ": " + Colors.GREEN + "OK" + Colors.ENDC)
 
     f.close()
     del table_list[:]
@@ -1322,7 +1323,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
 
 def main():
-    parser = argparse.ArgumentParser(description='Run nft tests', version='1.0')
+    parser = argparse.ArgumentParser(description='Run nft tests')
 
     parser.add_argument('filenames', nargs='*', metavar='path/to/file.t',
                         help='Run only these tests')

tests/py/nft-test.py def main(): · line 1347

Quoted 6 lines
tests/py/nft-test.py +3 -0
@@ -1341,6 +1342,10 @@ def main():
                         dest='enable_json',
                         help='test JSON functionality as well')
 
+    parser.add_argument('-v', '--version', action='version',
+                        version= '1.0',
+                        help='prints the version information')

Since this message is for the user, it should be "print" IMO.

Quoted 50 lines
tests/py/nft-test.py +9 -12
+
     args = parser.parse_args()
     global debug_option, need_fix_option, enable_json_option
     debug_option = args.debug
@@ -1353,15 +1358,15 @@ def main():
     signal.signal(signal.SIGTERM, signal_handler)
 
     if os.getuid() != 0:
-        print "You need to be root to run this, sorry"
+        print("You need to be root to run this, sorry")
         return
 
     # Change working directory to repository root
     os.chdir(TESTS_PATH + "/../..")
 
     if not os.path.exists('src/.libs/libnftables.so'):
-        print "The nftables library does not exist. " \
-              "You need to build the project."
+        print("The nftables library does not exist. "
+              "You need to build the project.")
         return
 
     global nftables
@@ -1411,18 +1416,15 @@ def main():
             run_total += file_unit_run
 
     if test_files == 0:
-        print "No test files to run"
+        print("No test files to run")
     else:
         if not specific_file:
             if force_all_family_option:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d total executed, %d error, %d warning" \
-                      % (test_files, files_ok, tests, run_total, errors,
-                         warnings)
+                print("{} test files, {} files passed, {} unit tests,".format(test_files, files_ok, tests))
+                print("{} total executed, {} error, {} warning".format(run_total, errors, warnings))
             else:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d error, %d warning" \
-                      % (test_files, files_ok, tests, errors, warnings)
+                print("{} test files, {} files passed, {} unit tests".format(test_files, files_ok, tests))
+                print("{} error, {} warning".format(errors, warnings))
 
 
 if __name__ == '__main__':
--

2.17.1

Signature · 2 lines
Shivani
https://about.me/shivani.bhardwaj
#2 lore raw
Quoted 32 lines · Shivani Bhardwaj
Quoted 30 lines · Shekhar Sharma

This patch converts the 'nft-test.py' file to run on both python 2 and python3.

The version hystory of this patch is:
v1:conversion to py3 by changing the print statements. v2:add the '__future__' package for compatibility with py2 and py3. v3:solves the 'version' problem in argparse by adding a new argument. v4:uses .format() method to make print statements clearer.
v5: updated the shebang and corrected the sequence of import statements.

---
 tests/py/nft-test.py | 44 +++++++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 21 deletions(-)
tests/py/nft-test.py +1 -1
index 1c0afd0e..fe56340c 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python
 #
 # (C) 2014 by Ana Rey Botello <[email protected]>
 #
@@ -13,6 +13,7 @@
 # Thanks to the Outreach Program for Women (OPW) for sponsoring this test
 # infrastructure.
 
Quoted 12 lines

tests/py/nft-test.py def set_delete(table, filename=None, lineno=None): · line 440

Quoted 10 lines
tests/py/nft-test.py +2 -1
+from __future__ import print_function
 import sys
 import os
 import argparse
@@ -436,7 +437,7 @@ def set_delete(table, filename=None, lineno=None):
     '''
     Deletes set and its content.
     '''
-    for set_name in all_set.keys():
+    for set_name in list(all_set.keys()):

What exactly is this list() for? This is not a generator expression.

The .keys() method returns a list in python2 whereas in python3 it does not do that.
So, i just wanted to be sure that whatever is returned is used as a list. (but now it turns out that even without that, the code is running perfectly in python3!)

Quoted 55 lines
Quoted 55 lines
tests/py/nft-test.py +8 -8
         # Check if exists the set
         if not set_exist(set_name, table, filename, lineno):
             reason = "The set %s does not exist, " \
@@ -1002,9 +1003,9 @@ def execute_cmd(cmd, filename, lineno, stdout_log=False, debug=False):
     :param debug: temporarily set these debug flags
     '''
     global log_file
-    print >> log_file, "command: %s" % cmd
+    print("command: {}".format(cmd), file = log_file)
     if debug_option:
-        print cmd
+        print(cmd)
 
     if debug:
         debug_old = nftables.get_debug()
@@ -1198,7 +1199,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
         sys.stdout.flush()
 
         if signal_received == 1:
-            print "\nSignal received. Cleaning up and Exitting..."
+            print("\nSignal received. Cleaning up and Exitting...")
             cleanup_on_exit()
             sys.exit(0)
 
@@ -1305,13 +1306,13 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
     if specific_file:
         if force_all_family_option:
-            print print_result_all(filename, tests, total_warning, total_error,
-                                   total_unit_run)
+            print(print_result_all(filename, tests, total_warning, total_error,
+                                   total_unit_run))
         else:
-            print print_result(filename, tests, total_warning, total_error)
+            print(print_result(filename, tests, total_warning, total_error))
     else:
         if tests == passed and tests > 0:
-            print filename + ": " + Colors.GREEN + "OK" + Colors.ENDC
+            print(filename + ": " + Colors.GREEN + "OK" + Colors.ENDC)
 
     f.close()
     del table_list[:]
@@ -1322,7 +1323,7 @@ def run_test_file(filename, force_all_family_option, specific_file):
 
 
 def main():
-    parser = argparse.ArgumentParser(description='Run nft tests', version='1.0')
+    parser = argparse.ArgumentParser(description='Run nft tests')
 
     parser.add_argument('filenames', nargs='*', metavar='path/to/file.t',
                         help='Run only these tests')
@@ -1341,6 +1342,10 @@ def main():
                         dest='enable_json',
                         help='test JSON functionality as well')
 
Quoted 5 lines

tests/py/nft-test.py def main(): · line 1347

Quoted 3 lines
tests/py/nft-test.py +3 -0
+    parser.add_argument('-v', '--version', action='version',
+                        version= '1.0',
+                        help='prints the version information')

Since this message is for the user, it should be "print" IMO.

True. Will change it.

Quoted 46 lines
Quoted 46 lines
tests/py/nft-test.py +9 -11
+
     args = parser.parse_args()
     global debug_option, need_fix_option, enable_json_option
     debug_option = args.debug
@@ -1353,15 +1358,15 @@ def main():
     signal.signal(signal.SIGTERM, signal_handler)
 
     if os.getuid() != 0:
-        print "You need to be root to run this, sorry"
+        print("You need to be root to run this, sorry")
         return
 
     # Change working directory to repository root
     os.chdir(TESTS_PATH + "/../..")
 
     if not os.path.exists('src/.libs/libnftables.so'):
-        print "The nftables library does not exist. " \
-              "You need to build the project."
+        print("The nftables library does not exist. "
+              "You need to build the project.")
         return
 
     global nftables
@@ -1411,18 +1416,15 @@ def main():
             run_total += file_unit_run
 
     if test_files == 0:
-        print "No test files to run"
+        print("No test files to run")
     else:
         if not specific_file:
             if force_all_family_option:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d total executed, %d error, %d warning" \
-                      % (test_files, files_ok, tests, run_total, errors,
-                         warnings)
+                print("{} test files, {} files passed, {} unit tests,".format(test_files, files_ok, tests))
+                print("{} total executed, {} error, {} warning".format(run_total, errors, warnings))
             else:
-                print "%d test files, %d files passed, %d unit tests, " \
-                      "%d error, %d warning" \
-                      % (test_files, files_ok, tests, errors, warnings)
+                print("{} test files, {} files passed, {} unit tests".format(test_files, files_ok, tests))
+                print("{} error, {} warning".format(errors, warnings))
 
 
Quoted 9 lines
Quoted 4 lines
tests/py/nft-test.py +0 -1
 if __name__ == '__main__':
--

2.17.1

--
Shivani
https://about.me/shivani.bhardwaj

Thanks!
Shekhar

#3 lore raw
In reply to Shivani Bhardwaj
Quoted 31 lines · Shivani Bhardwaj
Quoted 30 lines · Shekhar Sharma

This patch converts the 'nft-test.py' file to run on both python 2 and python3.

The version hystory of this patch is:
v1:conversion to py3 by changing the print statements. v2:add the '__future__' package for compatibility with py2 and py3. v3:solves the 'version' problem in argparse by adding a new argument. v4:uses .format() method to make print statements clearer.
v5: updated the shebang and corrected the sequence of import statements.

---
 tests/py/nft-test.py | 44 +++++++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 21 deletions(-)
tests/py/nft-test.py +1 -1
index 1c0afd0e..fe56340c 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/python2
+#!/usr/bin/python
 #
 # (C) 2014 by Ana Rey Botello <[email protected]>
 #
@@ -13,6 +13,7 @@
 # Thanks to the Outreach Program for Women (OPW) for sponsoring this test
 # infrastructure.
 
Quoted 11 lines

tests/py/nft-test.py def set_delete(table, filename=None, lineno=None): · line 440

Quoted 10 lines
tests/py/nft-test.py +2 -1
+from __future__ import print_function
 import sys
 import os
 import argparse
@@ -436,7 +437,7 @@ def set_delete(table, filename=None, lineno=None):
     '''
     Deletes set and its content.
     '''
-    for set_name in all_set.keys():
+    for set_name in list(all_set.keys()):

What exactly is this list() for? This is not a generator expression.

I think it's a generic python2 to python3 porting idiom to cover the case in which the set you're iterating over is being modified inside the for loop. However, that does not appear to the be the case here.