~ubuntu-branches/ubuntu/utopic/dogtail/utopic

« back to all changes in this revision

Viewing changes to dogtail/config.py

  • Committer: Bazaar Package Importer
  • Author(s): Daniel Holbach
  • Date: 2006-12-21 13:33:47 UTC
  • mfrom: (1.2.1 upstream)
  • mto: This revision was merged to the branch mainline in revision 5.
  • Revision ID: james.westby@ubuntu.com-20061221133347-xo9jg11afp5plcka
Tags: upstream-0.6.1
ImportĀ upstreamĀ versionĀ 0.6.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
1
"""
3
2
The configuration module.
4
3
"""
9
8
import locale
10
9
 
11
10
def _scriptName():
12
 
        return os.path.basename(sys.argv[0]).replace('.py','')
 
11
    return os.path.basename(sys.argv[0]).replace('.py','')
13
12
 
14
13
def _encoding():
15
 
        return locale.getpreferredencoding().lower()
 
14
    return locale.getpreferredencoding().lower()
16
15
 
17
16
class _Config(object):
18
 
        """
19
 
        Contains configuration parameters for the dogtail run.
20
 
 
21
 
        ensureSensitivity (boolean):
22
 
        Should we check that ui nodes are sensitive (not 'greyed out') before
23
 
        performing actions on them? If this is True (the default) it will raise
24
 
        an exception if this happens. Can set to False as a workaround for apps
25
 
        and toolkits that don't report sensitivity properly.
26
 
 
27
 
        searchBackoffDuration (float):
28
 
        Time in seconds for which to delay when a search fails.
29
 
 
30
 
        searchWarningThreshold (int):
31
 
        Number of retries before logging the individual attempts at a search.
32
 
 
33
 
        searchCutoffCount (int):
34
 
        Number of times to retry when a search fails.
35
 
        
36
 
        debugSearching (boolean):
37
 
        Whether to write info on search backoff and retry to the debug log.
38
 
        
39
 
        debugSleep (boolean):
40
 
        Whether to log whenever we sleep to the debug log.
41
 
        
42
 
        defaultDelay (float):
43
 
        Default time in seconds to sleep when delaying.
44
 
        
45
 
        absoluteNodePaths (boolean):
46
 
        Whether we should identify nodes in the logs with long 'abcolute paths', or
47
 
        merely with a short 'relative path'. FIXME: give examples
48
 
        
49
 
        debugSearchPaths (boolean):
50
 
        Whether we should write out debug info when running the SearchPath
51
 
        routines.
52
 
        
53
 
        debugTranslation (boolean):
54
 
        Whether we should write out debug information from the translation/i18n
55
 
        subsystem.
56
 
 
57
 
        blinkOnActions (boolean):
58
 
        Whether we should blink a rectangle around a Node when an action is 
59
 
        performed on it.
60
 
        """
61
 
        __scriptName = staticmethod(_scriptName)
62
 
        __encoding = staticmethod(_encoding)
63
 
        
64
 
        defaults = {
65
 
                # Storage
66
 
                'scratchDir' : '/tmp/dogtail/',
67
 
                'dataDir' : '/tmp/dogtail/data/',
68
 
                'logDir' : '/tmp/dogtail/logs/',
69
 
                'scriptName' : _scriptName(),
70
 
                'encoding' : _encoding(),
71
 
                'configFile' : None,
72
 
                'baseFile' : None,
73
 
                
74
 
                # Timing
75
 
                'actionDelay' : 1.0,
76
 
                'runInterval' : 0.5,
77
 
                'runTimeout' : 30,
78
 
                'searchBackoffDuration' : 0.5,
79
 
                'searchWarningThreshold' : 3,
80
 
                'searchCutoffCount' : 20,
81
 
                'defaultDelay' : 0.5,
82
 
 
83
 
                # Debug
84
 
                'debugSearching' : False,
85
 
                'debugSleep' : False,
86
 
                'debugSearchPaths' : False,
87
 
                'absoluteNodePaths' : False,
88
 
                'ensureSensitivity' : False,
89
 
                'debugTranslation' : False,
90
 
                'blinkOnActions' : False
91
 
        }
92
 
        
93
 
        options = {}
94
 
        
95
 
        invalidValue = "__INVALID__"
96
 
 
97
 
        def __init__(self):
98
 
                scriptName = _scriptName()
99
 
                encoding = _encoding()
100
 
                _Config.__createDir(_Config.defaults['scratchDir'])
101
 
                _Config.__createDir(_Config.defaults['logDir'])
102
 
                _Config.__createDir(_Config.defaults['dataDir'])
103
 
 
104
 
        def __setattr__(self, name, value):
105
 
                try:
106
 
                        if _Config.defaults[name] != value or _Config.options.get(name, _Config.invalidValue) != value:
107
 
                                if "Dir" in name: _Config.__createDir(value)
108
 
                                _Config.options[name] = value
109
 
                except KeyError: raise KeyError, name + " is not a valid option."
110
 
        
111
 
        def __getattr__(self, name):
112
 
                try: return _Config.options[name]
113
 
                except KeyError:
114
 
                        try: return _Config.defaults[name]
115
 
                        except KeyError: raise KeyError, name + " is not a valid option."
116
 
 
117
 
        def __createDir(cls, dirName):
118
 
                """
119
 
                Creates a directory (if it doesn't currently exist), creating any parent directories it needs.
120
 
                """
121
 
                dirName = os.path.abspath(dirName)
122
 
                #print "Checking for %s ..." % dirName,
123
 
                if not os.path.isdir(dirName): 
124
 
                        #print "Not found."
125
 
                        parentDirName = os.path.sep + os.path.sep.join(os.path.split(dirName + os.path.sep)[0].split(os.path.sep)[1:-1])
126
 
                        #print "Checking for parent %s ..." % parentDirName,
127
 
                        if not os.path.isdir(parentDirName): 
128
 
                                #print "Not found."
129
 
                                #print "Parent %s ..." % parentDirName
130
 
                                _Config.__createDir(parentDirName)
131
 
                                print "Creating %s ..." % dirName
132
 
                                os.mkdir(dirName)
133
 
                        else:
134
 
                                #print "Found."
135
 
                                print "Creating %s ..." % dirName
136
 
                                os.mkdir(dirName)
137
 
                #else: print "Found."
138
 
        __createDir = classmethod(__createDir)
139
 
        
140
 
        def load(self, dict):
141
 
                """
142
 
                Loads values from dict, preserving any options already set that are not overridden.
143
 
                """
144
 
                _Config.options.update(dict)
145
 
        
146
 
        def     reset(self):
147
 
                """
148
 
                Resets all settings to their defaults.
149
 
                """
150
 
                _Config.options = {}
 
17
    """
 
18
    Contains configuration parameters for the dogtail run.
 
19
 
 
20
    scratchDir(str):
 
21
    Directory where things like screenshots are stored.
 
22
 
 
23
    dataDir(str):
 
24
    Directory where related data files are located.
 
25
 
 
26
    logDir(str):
 
27
    Directory where dogtail.tc.TC*-generated logs are stored.
 
28
 
 
29
    scriptName(str) [Read-Only]:
 
30
    The name of the script being run.
 
31
    
 
32
    encoding(str)
 
33
    The encoding for text, used by dogtail.tc.TCString .
 
34
 
 
35
    actionDelay(float):
 
36
    The delay after an action is executed.
 
37
 
 
38
    typingDelay(float):
 
39
    The delay after a character is typed on the keyboard.
 
40
 
 
41
    runInterval(float):
 
42
    The interval at which dogtail.utils.run() and dogtail.procedural.run() 
 
43
    check to see if the application has started up.
 
44
 
 
45
    runTimeout(int):
 
46
    The timeout after which dogtail.utils.run() and dogtail.procedural.run()
 
47
    give up on looking for the newly-started application.
 
48
    
 
49
    searchBackoffDuration (float):
 
50
    Time in seconds for which to delay when a search fails.
 
51
 
 
52
    searchWarningThreshold (int):
 
53
    Number of retries before logging the individual attempts at a search.
 
54
 
 
55
    searchCutoffCount (int):
 
56
    Number of times to retry when a search fails.
 
57
 
 
58
    defaultDelay (float):
 
59
    Default time in seconds to sleep when delaying.
 
60
 
 
61
    debugSearching (boolean):
 
62
    Whether to write info on search backoff and retry to the debug log.
 
63
 
 
64
    debugSleep (boolean):
 
65
    Whether to log whenever we sleep to the debug log.
 
66
 
 
67
    debugSearchPaths (boolean):
 
68
    Whether we should write out debug info when running the SearchPath
 
69
    routines.
 
70
 
 
71
    absoluteNodePaths (boolean):
 
72
    Whether we should identify nodes in the logs with long 'abcolute paths', or
 
73
    merely with a short 'relative path'. FIXME: give examples
 
74
 
 
75
    ensureSensitivity (boolean):
 
76
    Should we check that ui nodes are sensitive (not 'greyed out') before
 
77
    performing actions on them? If this is True (the default) it will raise
 
78
    an exception if this happens. Can set to False as a workaround for apps
 
79
    and toolkits that don't report sensitivity properly.
 
80
 
 
81
    debugTranslation (boolean):
 
82
    Whether we should write out debug information from the translation/i18n
 
83
    subsystem.
 
84
 
 
85
    blinkOnActions (boolean):
 
86
    Whether we should blink a rectangle around a Node when an action is
 
87
    performed on it.
 
88
 
 
89
    fatalErrors (boolean):
 
90
    Whether errors encountered in dogtail.procedural should be considered
 
91
    fatal. If True, exceptions will be raised. If False, warnings will be 
 
92
    passed to the debug logger.
 
93
 
 
94
    useIconLogger (boolean):
 
95
    Whether we should place an icon in the notification area and print debug
 
96
    messages to it.
 
97
 
 
98
    logDebugToFile (boolean):
 
99
    Whether to write debug output to a log file.
 
100
    """
 
101
    __scriptName = staticmethod(_scriptName)
 
102
    __encoding = staticmethod(_encoding)
 
103
 
 
104
    defaults = {
 
105
            # Storage
 
106
            'scratchDir' : '/tmp/dogtail/',
 
107
            'dataDir' : '/tmp/dogtail/data/',
 
108
            'logDir' : '/tmp/dogtail/logs/',
 
109
            'scriptName' : _scriptName(),
 
110
            'encoding' : _encoding(),
 
111
            'configFile' : None,
 
112
            'baseFile' : None,
 
113
 
 
114
            # Timing
 
115
            'actionDelay' : 1.0,
 
116
            'typingDelay' : 0.075,
 
117
            'runInterval' : 0.5,
 
118
            'runTimeout' : 30,
 
119
            'searchBackoffDuration' : 0.5,
 
120
            'searchWarningThreshold' : 3,
 
121
            'searchCutoffCount' : 20,
 
122
            'defaultDelay' : 0.5,
 
123
 
 
124
            # Debug
 
125
            'debugSearching' : False,
 
126
            'debugSleep' : False,
 
127
            'debugSearchPaths' : False,
 
128
            'absoluteNodePaths' : False,
 
129
            'ensureSensitivity' : False,
 
130
            'debugTranslation' : False,
 
131
            'blinkOnActions' : False,
 
132
            'fatalErrors' : False,
 
133
 
 
134
            # Logging
 
135
            'useIconLogger' : False,
 
136
            'logDebugToFile' : True
 
137
    }
 
138
 
 
139
    options = {}
 
140
 
 
141
    invalidValue = "__INVALID__"
 
142
 
 
143
    def __init__(self):
 
144
        scriptName = _scriptName()
 
145
        encoding = _encoding()
 
146
        _Config.__createDir(_Config.defaults['scratchDir'])
 
147
        _Config.__createDir(_Config.defaults['logDir'])
 
148
        _Config.__createDir(_Config.defaults['dataDir'])
 
149
 
 
150
    def __setattr__(self, name, value):
 
151
        if not config.defaults.has_key(name):
 
152
            raise AttributeError, name + " is not a valid option."
 
153
 
 
154
        elif _Config.defaults[name] != value or \
 
155
                _Config.options.get(name, _Config.invalidValue) != value:
 
156
            if 'Dir' in name:
 
157
                _Config.__createDir(value)
 
158
                if value[-1] != '/': value = value + '/'
 
159
            elif name == 'useIconLogger':
 
160
                import logging
 
161
                if value == True:
 
162
                    logging.Logger.iconLogger = logging.IconLogger()
 
163
                elif value == False:
 
164
                    del logging.Logger.iconLogger
 
165
                    logging.Logger.iconLogger = None
 
166
                else: raise ValueError, value
 
167
            _Config.options[name] = value
 
168
 
 
169
    def __getattr__(self, name):
 
170
        try: return _Config.options[name]
 
171
        except KeyError:
 
172
            try: return _Config.defaults[name]
 
173
            except KeyError: raise AttributeError, name + " is not a valid option."
 
174
 
 
175
    def __createDir(cls, dirName):
 
176
        """
 
177
        Creates a directory (if it doesn't currently exist), creating any parent directories it needs.
 
178
        """
 
179
        dirName = os.path.abspath(dirName)
 
180
        #print "Checking for %s ..." % dirName,
 
181
        if not os.path.isdir(dirName):
 
182
            #print "Not found."
 
183
            parentDirName = os.path.sep + os.path.sep.join(os.path.split(dirName + os.path.sep)[0].split(os.path.sep)[1:-1])
 
184
            #print "Checking for parent %s ..." % parentDirName,
 
185
            if not os.path.isdir(parentDirName):
 
186
                #print "Not found."
 
187
                #print "Parent %s ..." % parentDirName
 
188
                _Config.__createDir(parentDirName)
 
189
                print "Creating %s ..." % dirName
 
190
                os.mkdir(dirName)
 
191
            else:
 
192
                #print "Found."
 
193
                print "Creating %s ..." % dirName
 
194
                os.mkdir(dirName)
 
195
        #else: print "Found."
 
196
    __createDir = classmethod(__createDir)
 
197
 
 
198
    def load(self, dict):
 
199
        """
 
200
        Loads values from dict, preserving any options already set that are not overridden.
 
201
        """
 
202
        _Config.options.update(dict)
 
203
 
 
204
    def     reset(self):
 
205
        """
 
206
        Resets all settings to their defaults.
 
207
        """
 
208
        _Config.options = {}
151
209
 
152
210
 
153
211
config = _Config()
154
212
 
155
213
if __name__ == '__main__':
156
 
        anyFailed = False
157
 
        def failOrPass(failure, description):
158
 
                if failure: 
159
 
                        anyFailed = True
160
 
                        print "FAILED: " + description
161
 
                else: print "PASSED: " + description
162
 
        
163
 
        # BEGIN tests
164
 
        
165
 
        failure = True
166
 
        for option in config.defaults.keys():
167
 
                #print failure, getattr(config, option), config.defaults[option]
168
 
                failure = not failure and ( getattr(config, option) == config.defaults[option])
169
 
        failOrPass(failure, "Reading all default values")
170
 
        
171
 
        failure = True
172
 
        failure = config.ensureSensitivity != True
173
 
        config.ensureSensitivity = False
174
 
        failure = failure or config.ensureSensitivity == True
175
 
        config.ensureSensitivity = True
176
 
        failure = failure or config.ensureSensitivity != True
177
 
        failOrPass(failure, "Setting ensureSensitivity")
178
 
 
179
 
        failure = True
180
 
        failure = not os.path.isdir(config.defaults['scratchDir'])
181
 
        failure = failure or not os.path.isdir(config.defaults['logDir'])
182
 
        failure = failure or not os.path.isdir(config.defaults['dataDir'])
183
 
        failOrPass(failure, "Looking for default directories")
184
 
 
185
 
        failure = True
186
 
        config.scratchDir = '/tmp/dt'
187
 
        failure = not os.path.isdir('/tmp/dt')
188
 
        config.logDir = '/tmp/dt_log/'
189
 
        failure = failure or not os.path.isdir('/tmp/dt_log/')
190
 
        config.dataDir = '/tmp/dt_data'
191
 
        failure = failure or not os.path.isdir('/tmp/dt_data')
192
 
        failOrPass(failure, "Changing default directories")
193
 
 
194
 
        # END tests
195
 
        
196
 
        if anyFailed: sys.exit(1)
 
214
    anyFailed = False
 
215
    def failOrPass(failure, description):
 
216
        if failure:
 
217
            anyFailed = True
 
218
            print "FAILED: " + description
 
219
        else: print "PASSED: " + description
 
220
 
 
221
    # BEGIN tests
 
222
 
 
223
    failure = True
 
224
    for option in config.defaults.keys():
 
225
        #print failure, getattr(config, option), config.defaults[option]
 
226
        failure = not failure and ( getattr(config, option) == config.defaults[option])
 
227
    failOrPass(failure, "Reading all default values")
 
228
 
 
229
    failure = True
 
230
    failure = config.ensureSensitivity != config.defaults['ensureSensitivity']
 
231
    config.ensureSensitivity = False
 
232
    failure = failure or config.ensureSensitivity == True
 
233
    config.ensureSensitivity = True
 
234
    failure = failure or config.ensureSensitivity != True
 
235
    failOrPass(failure, "Setting ensureSensitivity")
 
236
 
 
237
    failure = True
 
238
    failure = not os.path.isdir(config.defaults['scratchDir'])
 
239
    failure = failure or not os.path.isdir(config.defaults['logDir'])
 
240
    failure = failure or not os.path.isdir(config.defaults['dataDir'])
 
241
    failOrPass(failure, "Looking for default directories")
 
242
 
 
243
    failure = True
 
244
    config.scratchDir = '/tmp/dt'
 
245
    failure = not os.path.isdir('/tmp/dt')
 
246
    config.logDir = '/tmp/dt_log/'
 
247
    failure = failure or not os.path.isdir('/tmp/dt_log/')
 
248
    config.dataDir = '/tmp/dt_data'
 
249
    failure = failure or not os.path.isdir('/tmp/dt_data')
 
250
    failOrPass(failure, "Changing default directories")
 
251
 
 
252
    failure = True
 
253
    config.useIconLogger = True
 
254
    import logging
 
255
    try:
 
256
        if isinstance(logging.debugLogger.iconLogger, logging.IconLogger):
 
257
            failure = False
 
258
    except AttributeError: pass
 
259
    failOrPass(failure, "Setting useIconLogger")
 
260
 
 
261
    # END tests
 
262
 
 
263
    if anyFailed: sys.exit(1)