Browse Source

[2713] Use OptionsParser instead of getopt

Jelte Jansen 12 years ago
parent
commit
cd98bdae78

+ 25 - 37
src/bin/usermgr/b10-cmdctl-usermgr.py.in

@@ -16,20 +16,24 @@
 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
 
 '''
 '''
-This file implements user management program. The user name and 
+This file implements user management program. The user name and
 its password is appended to csv file.
 its password is appended to csv file.
 '''
 '''
 import random
 import random
 from hashlib import sha1
 from hashlib import sha1
 import csv
 import csv
 import getpass
 import getpass
+
+#remove
 import getopt
 import getopt
+from optparse import OptionParser, OptionValueError
+
 import sys; sys.path.append ('@@PYTHONPATH@@')
 import sys; sys.path.append ('@@PYTHONPATH@@')
 import isc.util.process
 import isc.util.process
 
 
 isc.util.process.rename()
 isc.util.process.rename()
 
 
-VERSION_NUMBER = 'bind10'
+VERSION_STRING = 'b10-cmdctl-usermgr @PACKAGE_VERSION@'
 DEFAULT_FILE = 'cmdctl-accounts.csv'
 DEFAULT_FILE = 'cmdctl-accounts.csv'
 
 
 def gen_password_hash(password):
 def gen_password_hash(password):
@@ -42,16 +46,16 @@ def username_exist(name, filename):
     exist = False
     exist = False
     csvfile = None
     csvfile = None
     try:
     try:
-        csvfile = open(filename)        
+        csvfile = open(filename)
         reader = csv.reader(csvfile)
         reader = csv.reader(csvfile)
         for row in reader:
         for row in reader:
             if name == row[0]:
             if name == row[0]:
-                exist = True               
+                exist = True
                 break
                 break
     except Exception:
     except Exception:
         pass
         pass
-            
+
-    if csvfile:    
+    if csvfile:
         csvfile.close()
         csvfile.close()
     return exist
     return exist
 
 
@@ -62,35 +66,19 @@ def save_userinfo(username, pw, salt, filename):
     csvfile.close()
     csvfile.close()
     print("\n create new account successfully! \n")
     print("\n create new account successfully! \n")
 
 
-def usage():
+def set_options(parser):
-    print('''Usage: usermgr [options]
+    parser.add_option("-f", "--file",
-           -h, --help \t Show this help message and exit
+                      dest="output_file", default=DEFAULT_FILE,
-           -f, --file \t Specify the file to append user name and password
+                      help="Specify the file to append user name and password"
-           -v, --version\t Get version number
+                     )
-           ''')           
 
 
 def main():
 def main():
-    filename = DEFAULT_FILE
+    parser = OptionParser(version = VERSION_STRING)
-    try: 
+    set_options(parser)
-        opts, args = getopt.getopt(sys.argv[1:], 'f:hv', 
+    (options, _) = parser.parse_args()
-                                   ['file=', 'help', 'version']) 
+
-    except getopt.GetoptError as err: 
+    filename = options.output_file
-        print(err) 
+
-        usage() 
-        sys.exit(2)
-    for op, param in opts:        
-        if op in ('-h', '--help'): 
-            usage()
-            sys.exit()
-        elif op in ('-v', '--version'): 
-            print(VERSION_NUMBER)
-            sys.exit()                     
-        elif op in ('-f', "--file"):
-            filename = param
-        else: 
-            assert False, 'unknown option' 
-            usage()
-    
     try:
     try:
         while True :
         while True :
             name = input("Desired Login Name:")
             name = input("Desired Login Name:")
@@ -109,15 +97,15 @@ def main():
                     print("password is not same, please input again")
                     print("password is not same, please input again")
                 else:
                 else:
                     break;
                     break;
-            
+
             salt, pw = gen_password_hash(pwd1)
             salt, pw = gen_password_hash(pwd1)
             save_userinfo(name, pw, salt, filename)
             save_userinfo(name, pw, salt, filename)
             inputdata = input('continue to create new account by input \'y\' or \'Y\':')
             inputdata = input('continue to create new account by input \'y\' or \'Y\':')
             if inputdata not in ['y', 'Y']:
             if inputdata not in ['y', 'Y']:
-                break                
+                break
-                
+
     except KeyboardInterrupt:
     except KeyboardInterrupt:
-        pass                
+        pass
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':

+ 40 - 9
src/bin/usermgr/tests/b10-cmdctl-usermgr_test.py

@@ -13,8 +13,10 @@
 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
 
+import os
 import unittest
 import unittest
 import subprocess
 import subprocess
+import imp
 
 
 def run(command):
 def run(command):
     """
     """
@@ -28,6 +30,23 @@ def run(command):
 
 
 class TestUserMgr(unittest.TestCase):
 class TestUserMgr(unittest.TestCase):
     TOOL = '../b10-cmdctl-usermgr'
     TOOL = '../b10-cmdctl-usermgr'
+    OUTPUT_FILE = 'test_users.csv'
+
+    def setUp(self):
+        self.delete_output_file()
+
+    def tearDown(self):
+        self.delete_output_file()
+
+    def delete_output_file(self):
+        if os.path.exists(self.OUTPUT_FILE):
+            os.remove(self.OUTPUT_FILE)
+
+    def check_output_file(self, expected_content):
+        self.assertTrue(os.path.exists(self.OUTPUT_FILE))
+        with open(self.OUTPUT_FILE, 'r') as f:
+            content = f.readlines()
+        self.assertEqual(expected_content, content)
 
 
     def run_check(self, expected_returncode, expected_stdout, expected_stderr, command):
     def run_check(self, expected_returncode, expected_stdout, expected_stderr, command):
         """
         """
@@ -46,16 +65,28 @@ class TestUserMgr(unittest.TestCase):
         if expected_stderr is not None:
         if expected_stderr is not None:
             self.assertEqual(expected_stderr, stderr.decode())
             self.assertEqual(expected_stderr, stderr.decode())
 
 
-    def test_bad_options(self):
+    def test_help(self):
-        self.run_check(2,
+        self.run_check(0,
-                       'option -a not recognized\n'
+'''Usage: b10-cmdctl-usermgr [options]
-                       'Usage: usermgr [options]\n'
-                       '           -h, --help 	 Show this help message and exit\n'
-                       '           -f, --file 	 Specify the file to append user name and password\n'
-                       '           -v, --version	 Get version number\n'
-                       '           \n',
-                       '', [self.TOOL, '-a'])
 
 
+Options:
+  --version             show program's version number and exit
+  -h, --help            show this help message and exit
+  -f OUTPUT_FILE, --file=OUTPUT_FILE
+                        Specify the file to append user name and password
+''',
+                       '',
+                       [self.TOOL, '-h'])
+
+    def test_default_file(self):
+        """
+        Check the default file is the correct one.
+        Only checks the internal variable, as we don't want to overwrite
+        the actual file here
+        """
+        # Hardcoded path .. should be ok since this is run from make check
+        usermgr = imp.load_source('usermgr', '../b10-cmdctl-usermgr.py')
+        self.assertEqual('cmdctl-accounts.csv', usermgr.DEFAULT_FILE)
 
 
 if __name__== '__main__':
 if __name__== '__main__':
     unittest.main()
     unittest.main()