Little refactor and add test cases to conf.py
authorHuang Hao <hao.h.huang@intel.com>
Fri, 7 Sep 2012 12:06:08 +0000 (20:06 +0800)
committerHuang Hao <hao.h.huang@intel.com>
Mon, 10 Sep 2012 06:25:25 +0000 (14:25 +0800)
- change BrainConfigParser.read() to read_one() since the code only
    use this function to read one config file. It's simpler.
- remove BrainConfigParser.check_opt() since no code use it.
- remove else branch in ConfigMgr.get() since the code can still
    work if val is empty string. Also add a test case for it.
- remove ConfigMgr.set() since no code use it. passwdx set back
    in _check_passwd(), and we will not use this set() function to
    add option into config file.
- change implementation of Fixture class, it doesn't call start()
    and stop() methods which introduced by mock0.7
- add more test cases for conf.py

Change-Id: I598f8943f98f067aa584fa4be811492c70226f23

gitbuildsys/conf.py
tests/test_config.py
tests/test_passwdx.py [new file with mode: 0644]
tests/test_profile.py
tests/testdata/ini/bad_passwdx.ini [new file with mode: 0644]
tests/testdata/ini/empty_passwdx.ini [new file with mode: 0644]
tests/testdata/ini/normal_passwdx.ini [new file with mode: 0644]
tests/testdata/ini/passwdx.ini [new file with mode: 0644]
tests/testdata/ini/plain_passwd.ini [new file with mode: 0644]
tests/testdata/ini/plain_passwd2.ini [new file with mode: 0644]
tests/testdata/ini/without_section_header.ini [new file with mode: 0644]

index dc4bcfbb4ba6865e2a9e1e35eed6956a7c85dff4..018832af65ddad67d6bc56c8bb2f808ce2dba85f 100644 (file)
@@ -101,18 +101,9 @@ class BrainConfigParser(SafeConfigParser):
 
     SECTCRE = SectionPattern()
 
-    def read(self, filenames):
-        """Limit the read() only support one input file. It's enough for
-        current case.
-        If the input list has multiple values, use the last one.
-        """
-
-        if not isinstance(filenames, basestring) and len(filenames) > 1:
-            msger.warning('Will not support multiple config files, '
-                          'only read in the last one.')
-            filenames = filenames[-1:]
-
-        return SafeConfigParser.read(self, filenames)
+    def read_one(self, filename):
+        """only support one input file"""
+        return SafeConfigParser.read(self, filename)
 
     def _read(self, fptr, fname):
         """Parse a sectioned setup file.
@@ -311,7 +302,7 @@ distconf = $build__distconf
         for fpath in fpaths:
             cfgparser = BrainConfigParser()
             try:
-                cfgparser.read(fpath)
+                cfgparser.read_one(fpath)
             except MissingSectionHeaderError, err:
                 raise errors.ConfigError('config file error:%s' % err)
             self._cfgparsers.append(cfgparser)
@@ -430,13 +421,6 @@ distconf = $build__distconf
             raise errors.ConfigError('no opt: %s in section %s' \
                                      % (opt, str(section)))
 
-    def check_opt(self, opt, section='general'):
-        if section in self.DEFAULTS and \
-           opt in self.DEFAULTS[section]:
-            return True
-        else:
-            return False
-
     def options(self, section='general'):
         'merge and return options of certain section from multi-levels'
         sect_found = False
@@ -460,35 +444,14 @@ distconf = $build__distconf
     def get(self, opt, section='general'):
         'get item value. return plain text of password if item is passwd'
         if opt == 'passwd':
-            opt = 'passwdx'
-            val = self._get(opt, section)
-            if val:
-                try:
-                    return decode_passwdx(val)
-                except (TypeError, IOError), err:
-                    raise errors.ConfigError('passwdx:%s' % err)
-            else:
-                return val
+            val = self._get('passwdx', section)
+            try:
+                return decode_passwdx(val)
+            except (TypeError, IOError), err:
+                raise errors.ConfigError('passwdx:%s' % err)
         else:
             return self._get(opt, section)
 
-    def set(self, opt, val, section='general'):
-        if opt.endswith('passwd'):
-            val = encode_passwd(val)
-            opt += 'x'
-
-        for cfgparser in self._cfgparsers:
-            if cfgparser.has_option(section, opt):
-                return cfgparser.set(section, opt, val)
-
-        # Option not found, add a new key to the first cfg file that has
-        # the section
-        for cfgparser in self._cfgparsers:
-            if cfgparser.has_section(section):
-                return cfgparser.set(section, opt, val)
-
-        raise errors.ConfigError('invalid section %s' % (section))
-
     def update(self):
         'update changed values into files on disk'
         for cfgparser in self._cfgparsers:
index 87f799af3df7df08f4b0fbcd0be878ce345cc374..624a25e7defa97daa9d57f8297cda56f32d3aa25 100644 (file)
 """Functional tests for GBS config"""
 
 import os
-import functools
 import unittest
 
 from mock import patch
 
-from gitbuildsys import errors
+from gitbuildsys.errors import ConfigError
 import gitbuildsys.conf
 
 
@@ -77,26 +76,9 @@ class Fixture(object):
             patch('gitbuildsys.conf.os.path.abspath', self.fake_abspath),
             patch('ConfigParser.open', self.fake_open, create=True),
             ]
-
-        @functools.wraps(func)
-        def wrapper(*args, **kw):
-            '''setup mock objects and tear down them finally'''
-            for patcher in reversed(patchers):
-                patcher.start()
-
-            # configmgr is a global variable, reload to recreate it
-            # otherwise fixtures only take effect in the first time
-            reload(gitbuildsys.conf)
-
-            try:
-                return func(*args, **kw)
-            except:
-                raise
-            finally:
-                for patcher in patchers:
-                    patcher.stop()
-
-        return wrapper
+        for patcher in patchers:
+            func = patcher(func)
+        return func
 
 
 class ConfigGettingTest(unittest.TestCase):
@@ -105,18 +87,21 @@ class ConfigGettingTest(unittest.TestCase):
     @staticmethod
     def get(section, option):
         '''get section.option from config'''
+        # configmgr is a global variable, reload to recreate it
+        # otherwise fixtures only take effect in the first time
+        reload(gitbuildsys.conf)
         return gitbuildsys.conf.configmgr.get(option, section)
 
     @Fixture(project='project1.ini')
     def test_no_such_section(self):
         '''test no such section'''
-        self.assertRaises(errors.ConfigError,
+        self.assertRaises(ConfigError,
                           self.get, 'not_exists_section', 'key')
 
     @Fixture(project='project1.ini')
     def test_no_such_option(self):
         '''test no such option'''
-        self.assertRaises(errors.ConfigError,
+        self.assertRaises(ConfigError,
                           self.get, 'section', 'not_exists_option')
 
     @Fixture(project='project1.ini')
@@ -152,15 +137,25 @@ class ConfigGettingTest(unittest.TestCase):
     @Fixture(project='project1.ini')
     def test_no_such_named_section(self):
         '''test no such section'''
-        self.assertRaises(errors.ConfigError,
+        self.assertRaises(ConfigError,
                           self.get, ('profile', 'NOT_EXISTS'), 'key')
 
     @Fixture(project='project1.ini')
     def test_no_such_option_in_named_section(self):
         '''test no such section'''
-        self.assertRaises(errors.ConfigError,
+        self.assertRaises(ConfigError,
                           self.get, ('profile', 'rsa'), 'not_exists_option')
 
+    @Fixture(home='home1.ini')
+    def test_default_value(self):
+        'test get hardcode default value '
+        self.assertEquals('/var/tmp', self.get('general', 'tmpdir'))
+
+    @Fixture(home='without_section_header.ini')
+    def test_invalid_ini(self):
+        'test invalid ini'
+        self.assertRaises(ConfigError, reload, gitbuildsys.conf)
+
 
 if __name__ == '__main__':
     unittest.main()
\ No newline at end of file
diff --git a/tests/test_passwdx.py b/tests/test_passwdx.py
new file mode 100644 (file)
index 0000000..8b4474b
--- /dev/null
@@ -0,0 +1,133 @@
+#!/usr/bin/python -tt
+# vim: ai ts=4 sts=4 et sw=4
+#
+# Copyright (c) 2012 Intel, Inc.
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by the Free
+# Software Foundation; version 2 of the License
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc., 59
+# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+"""Functional tests for setting passwdx back to config"""
+import unittest
+from StringIO import StringIO
+
+from mock import patch
+
+from test_config import Fixture
+import gitbuildsys.conf
+from gitbuildsys.errors import ConfigError
+
+
+class FakeFile(object):
+    'Fake file used to get updated config file'
+
+    def __init__(self):
+        self.buffer = StringIO()
+
+    def write(self, data):
+        'write data into fake file'
+        self.buffer.write(data)
+
+    def close(self):
+        'do not close buffer, then call getvalue() to retrieve the content'
+
+    def getvalue(self):
+        'get content of fake file'
+        return self.buffer.getvalue()
+
+
+@patch('gitbuildsys.conf.open', create=True)
+class PasswdxTest(unittest.TestCase):
+    'Test for setting passwdx'
+
+    @Fixture(home='plain_passwd.ini')
+    def test_one_file(self, fake_open):
+        'test passwdx set back to one file'
+        conf = FakeFile()
+        fake_open.return_value = conf
+
+        reload(gitbuildsys.conf)
+
+        self.assertEquals('''[remotebuild]
+build_server = https://api
+passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+
+[build]
+repo1.url = https://repo1
+repo1.passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+''', conf.getvalue())
+
+
+    @Fixture(home='plain_passwd.ini', project='plain_passwd2.ini')
+    def test_two_files(self, fake_open):
+        'test passwdx set back to two files'
+        confs = [FakeFile(), FakeFile()]
+        bak = confs[:]
+        fake_open.side_effect = lambda *args, **kw: bak.pop()
+
+        reload(gitbuildsys.conf)
+
+        self.assertEquals('''[remotebuild]
+build_server = https://api
+passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+
+[build]
+repo1.url = https://repo1
+repo1.passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+''', confs[0].getvalue())
+
+        self.assertEquals('''[remotebuild]
+build_server = https://api
+user = test
+passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+
+[build]
+repo1.url = https://repo1
+repo1.user = test
+repo1.passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
+''', confs[1].getvalue())
+
+
+    @Fixture(home='normal_passwdx.ini')
+    def test_get_passwdx(self, _fake_open):
+        'test get decode passwd'
+        reload(gitbuildsys.conf)
+
+        pwd = gitbuildsys.conf.configmgr.get('passwd', 'remotebuild')
+        self.assertEquals('secret', pwd)
+
+    @Fixture(home='plain_passwd.ini')
+    def test_get_passwd(self, _fake_open):
+        'test get decode passwd'
+        reload(gitbuildsys.conf)
+
+        pwd = gitbuildsys.conf.configmgr.get('passwd', 'remotebuild')
+        self.assertEquals('secret', pwd)
+
+    @Fixture(home='bad_passwdx.ini')
+    def test_bad_passwdx(self, _fake_open):
+        'test bad passwdx'
+        reload(gitbuildsys.conf)
+
+        self.assertRaises(ConfigError, gitbuildsys.conf.configmgr.get,
+                          'passwd', 'remotebuild')
+
+    @Fixture(home='empty_passwdx.ini')
+    def test_empty_passwdx(self, _fake_open):
+        'test empty passwdx'
+        reload(gitbuildsys.conf)
+
+        pwd = gitbuildsys.conf.configmgr.get('passwd', 'remotebuild')
+        self.assertEquals('', pwd)
+
+
+if __name__ == '__main__':
+    unittest.main()
\ No newline at end of file
index bdf6f1d46bb34dd1ca715050115d14593e350a8a..b53cb3835405f31795af37476a4b22e08ddf442b 100644 (file)
@@ -24,6 +24,7 @@ from test_config import Fixture
 
 def get_profile():
     '''get current profile to test'''
+    reload(gitbuildsys.conf)
     return gitbuildsys.conf.configmgr.get_current_profile()
 
 
diff --git a/tests/testdata/ini/bad_passwdx.ini b/tests/testdata/ini/bad_passwdx.ini
new file mode 100644 (file)
index 0000000..b16c961
--- /dev/null
@@ -0,0 +1,3 @@
+[remotebuild]
+build_server = https://api
+passwdx = secret
\ No newline at end of file
diff --git a/tests/testdata/ini/empty_passwdx.ini b/tests/testdata/ini/empty_passwdx.ini
new file mode 100644 (file)
index 0000000..cc63375
--- /dev/null
@@ -0,0 +1,3 @@
+[remotebuild]
+build_server = https://api
+passwdx =
\ No newline at end of file
diff --git a/tests/testdata/ini/normal_passwdx.ini b/tests/testdata/ini/normal_passwdx.ini
new file mode 100644 (file)
index 0000000..1eeafe3
--- /dev/null
@@ -0,0 +1,3 @@
+[remotebuild]
+build_server = https://api
+passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
\ No newline at end of file
diff --git a/tests/testdata/ini/passwdx.ini b/tests/testdata/ini/passwdx.ini
new file mode 100644 (file)
index 0000000..1eeafe3
--- /dev/null
@@ -0,0 +1,3 @@
+[remotebuild]
+build_server = https://api
+passwdx = QlpoOTFBWSZTWYfNdxYAAAIBgAoAHAAgADDNAMNEA24u5IpwoSEPmu4s
\ No newline at end of file
diff --git a/tests/testdata/ini/plain_passwd.ini b/tests/testdata/ini/plain_passwd.ini
new file mode 100644 (file)
index 0000000..8693a6c
--- /dev/null
@@ -0,0 +1,7 @@
+[remotebuild]
+build_server = https://api
+passwd = secret
+
+[build]
+repo1.url = https://repo1
+repo1.passwd = secret
diff --git a/tests/testdata/ini/plain_passwd2.ini b/tests/testdata/ini/plain_passwd2.ini
new file mode 100644 (file)
index 0000000..46db241
--- /dev/null
@@ -0,0 +1,9 @@
+[remotebuild]
+build_server = https://api
+user = test
+passwd = secret
+
+[build]
+repo1.url = https://repo1
+repo1.user = test
+repo1.passwd = secret
\ No newline at end of file
diff --git a/tests/testdata/ini/without_section_header.ini b/tests/testdata/ini/without_section_header.ini
new file mode 100644 (file)
index 0000000..dfb28b1
--- /dev/null
@@ -0,0 +1 @@
+key = value
\ No newline at end of file