rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
cmd.Cmd.default(self, line)
try: parse.execute_command(cmd, args, global_dict, local_dict) except SystemExit: raise except Exception, e: print '\nERROR: %s\n' % (str(e),)
def default(self, line): "Called when unknown command is executed."
title = p.tags("title").next()
title = None if p.get_tag("title"): title = p.get_compressed_text()
def get_title(self): p = pullparser.PullParser(StringIO(self.get_page())) title = p.tags("title").next() return title
if module_file.endswith(".ptl"): outfile = outfile[0:outfile.rfind('.')] + ".ptl"
if module_file.endswith(".zip"): outfile = outfile[0:outfile.rfind('.')] + ".zip"
def build_module(self, module, module_file, package): if type(package) is StringType: package = string.split(package, '.') elif type(package) not in (ListType, TupleType): raise TypeError, \ "'package' must be a string (dot-separated), list, or tuple"
local_dict = {} local_dict['__url__'] = commands.browser.url()
locals_dict['__url__'] = commands.browser.url()
def execute_file(filename, **kw): """ Execute commands from a file. """ finished = 0 # initialize new local dictionary & get global + current local namespaces.new_local_dict() globals_dict, locals_dict = namespaces.get_twill_glocals() local_dict = {} local_dict['__url__'] = commands.browser.url() # reset browser com...
local_dict['__url__'] = commands.browser.url()
locals_dict['__url__'] = commands.browser.url()
def execute_file(filename, **kw): """ Execute commands from a file. """ finished = 0 # initialize new local dictionary & get global + current local namespaces.new_local_dict() globals_dict, locals_dict = namespaces.get_twill_glocals() local_dict = {} local_dict['__url__'] = commands.browser.url() # reset browser com...
val = eval(arg, globals_dict, locals_dict)
try: val = eval(arg, globals_dict, locals_dict) except NameError: val = arg
def process_args(args, globals_dict, locals_dict): """ Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*'). Return a new list. """ newargs = [] for arg in args: # strip quotes from quoted strings. # don't use string.strip, which will remove mor...
val = eval(arg[1:], globals_dict, locals_dict)
try: val = eval(arg[1:], globals_dict, locals_dict) except NameError: val = arg
def process_args(args, globals_dict, locals_dict): """ Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*'). Return a new list. """ newargs = [] for arg in args: # strip quotes from quoted strings. # don't use string.strip, which will remove mor...
def clicked(self, form, field): def choose_this_form(test_form, this_form=form): if test_form is this_form: return True return False self._browser.select_form(predicate=choose_this_form)
def clicked(self, form, control): if self._browser.form != form: def choose_this_form(test_form, this_form=form): if test_form is this_form: return True return False self._browser.select_form(predicate=choose_this_form) self._last_submit = None if isinstance(control, ClientForm.SubmitControl): self._last_submit...
def clicked(self, form, field): # construct a function to choose a particular form; select_form # can use this to pick out a precise form. def choose_this_form(test_form, this_form=form): if test_form is this_form: return True return False
ctl = self.get_form_field(self._browser.form, fieldname)
if not fieldname: if self._last_submit: ctl = self._last_submit else: ctl = None else: ctl = self.get_form_field(self._browser.form, fieldname)
def submit(self, fieldname): assert self._browser.form ctl = self.get_form_field(self._browser.form, fieldname) #### @CTB ARGH. There's no way, currently, to select a specific #### control if you've already got one in mind, because the #### 'predicate' function doesn't get passed through Browser.click(). control = ...
def submit(submit_button="0"):
def submit(submit_button=None):
def submit(submit_button="0"): """ >> submit [<buttonspec>] Submit the current form (the one last clicked on) by clicking on the n'th submission button. If no "buttonspec" is given, submit the current form by using the last clicked submit button. """ state.submit(submit_button)
state.clicked(form, control) if control.readonly: return set_form_control_value(control, value)
if control: state.clicked(form, control) if control.readonly: return set_form_control_value(control, value) else: print 'NO SUCH FIELD FOUND'
def formvalue(formname, fieldname, value): """ >> formvalue <formname> <field> <value> Set value of a form field. There are some ambiguities in the way formvalue deals with lists: 'set' will *add* the given value to a multilist. Formvalue ignores read-only fields completely; if they're readonly, nothing is done. Av...
def _all_the_same_control(self, matches):
def _all_the_same_checkbox(self, matches): """ Check whether all these controls are actually the the same checkbox. Hidden controls can combine with checkboxes, to allow form processors to ensure a False value is returned even if user does not check the checkbox. Without the hidden control, no value would be returned....
def _all_the_same_control(self, matches): name = None value = None for match in matches: if match.type not in ['submit', 'hidden']: return False if name is None: name = match.name value = match.value else: if match.name != name or match.value!= value: return False return True
def build_https_handler(): try: from mechanize._urllib2_support import HTTPSHandler except ImportError: HTTPSHandler = None return HTTPSHandler
def build_https_handler(): try: from mechanize._urllib2_support import HTTPSHandler except ImportError: HTTPSHandler = None return HTTPSHandler
self.handler_classes['https'] = build_https_handler()
def __init__(self, *args, **kwargs):
print '==> at', self.get_url()
if success: print '==> at', self.get_url() else: raise BrowserStateError("cannot go to '%s'" % (url,))
def go(self, url): """ Visit given URL. """ url = url.replace(' ', '%20')
print self.get_url()
def reload(self): """ Tell the browser to reload the current page. """ print self.get_url() self._last_result = journey(self._browser.reload) print '==> reloaded'
print 'BACK ATTR ERROR', str(e)
def back(self): """ Return to previous page, if possible. """ back_url = self._browser.back try: self._last_result = journey(back_url) except AttributeError, e: print 'BACK ATTR ERROR', str(e) self._last_result = None except BrowserStateError, e: print 'BACK STATE ERROR', str(e) self._last_result = None if self._last_...
print 'BACK STATE ERROR', str(e)
def back(self): """ Return to previous page, if possible. """ back_url = self._browser.back try: self._last_result = journey(back_url) except AttributeError, e: print 'BACK ATTR ERROR', str(e) self._last_result = None except BrowserStateError, e: print 'BACK STATE ERROR', str(e) self._last_result = None if self._last_...
return eval(eval_str, globals_dict, locals_dict)
return result
def execute_command(cmd, args, globals_dict, locals_dict): """ Actually execute the command. Side effects: __args__ is set to the argument tuple, __cmd__ is set to the command. """ # execute command. locals_dict['__cmd__'] = cmd locals_dict['__args__'] = args eval_str = "%s(*__args__)" % (cmd,) # set __url__ locals_...
sys.stderr.write(str(e)) raise
sys.stderr.write("\nError message: '%s'\n" % (str(e).strip(),)) sys.stderr.write("\n") return
def execute_file(filename, **kw): """ Execute commands from a file. """ finished = 0 # initialize new local dictionary & get global + current local namespaces.new_local_dict() globals_dict, locals_dict = namespaces.get_twill_glocals() local_dict = {} local_dict['__url__'] = commands.state.url() # reset browser comma...
global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = m.group() return current_url
if m.groups(): match_str = m.group(1) else: match_str = m.group(0) global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = match_str return match_str
def url(should_be): """ >> url <regexp> Check to make sure that the current URL matches the regexp. The local variable __match__ is set to the matching part of the URL. """ regexp = re.compile(should_be) current_url = browser.get_url() m = None if current_url is not None: m = regexp.search(current_url) if not m: ra...
global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = m.group()
if m.groups(): match_str = m.group(1) else: match_str = m.group(0) global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = match_str
def find(what, flags=''): """ >> find <regexp> [<flags>] Succeed if the regular expression is on the page. Sets the local variable __match__ to the matching text. Flags is a string consisting of the following characters: * i: ignorecase * m: multiline * s: dotall For explanations of these, please see the Python re...
global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = m.group() return title
if m.groups(): match_str = m.group(1) else: match_str = m.group(0) global_dict, local_dict = get_twill_glocals() local_dict['__match__'] = match_str return match_str
def title(what): """ >> title <regexp> Succeed if the regular expression is in the page title. """ regexp = re.compile(what) title = browser.get_title() print>>OUT, "title is '%s'." % (title,) m = regexp.search(title) if not m: raise TwillAssertionError("title does not contain '%s'" % (what,)) global_dict, local_di...
if not self._browser._forms:
if not self._browser.forms():
def submit(self, fieldname): if not self._browser._forms: raise Exception("no forms on this page!") ctl = None form = self._browser.form if form is None: if len(self._browser._forms) == 1: form = self._browser._forms[0] else: raise Exception("more than one form; you must select one (use 'fv') before submitting")
if len(self._browser._forms) == 1: form = self._browser._forms[0]
if len(self._browser.forms()) == 1: form = self._browser.forms()[0]
def submit(self, fieldname): if not self._browser._forms: raise Exception("no forms on this page!") ctl = None form = self._browser.form if form is None: if len(self._browser._forms) == 1: form = self._browser._forms[0] else: raise Exception("more than one form; you must select one (use 'fv') before submitting")
def __len__(self): return len(self._history) def __getitem__(self, i): return self._history[i]
def __len__(self): return len(self._history)
Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*').
Take a list of string arguments parsed via pyparsing and evaluate the special variables ('__*').
def process_args(args, globals_dict, locals_dict): """ Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*'). Return a new list. """ newargs = [] for arg in args: # strip quotes from quoted strings. # don't use string.strip, which will remove mor...
if arg[0] == arg[-1] and arg[0] in "\"'": newargs.append(arg[1:-1])
def process_args(args, globals_dict, locals_dict): """ Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*'). Return a new list. """ newargs = [] for arg in args: # strip quotes from quoted strings. # don't use string.strip, which will remove mor...
elif arg.startswith('__'):
if arg.startswith('__'):
def process_args(args, globals_dict, locals_dict): """ Take a list of string arguments parsed via pyparsing, unquote those that are quoted, and evaluate the special variables ('__*'). Return a new list. """ newargs = [] for arg in args: # strip quotes from quoted strings. # don't use string.strip, which will remove mor...
cmd = res[0] args = process_args(res[1:], globals_dict, locals_dict) return (cmd, args)
args = process_args(res.arguments.asList(), globals_dict, locals_dict) return (res.command, args)
def parse_command(line, globals_dict, locals_dict): """ Parse command. """ res = full_command.parseString(line) if res: if _print_commands: print "twill: executing cmd '%s'" % (line.strip(),) cmd = res[0] args = process_args(res[1:], globals_dict, locals_dict) return (cmd, args) return None, None #...
new_result = ResultWrapper(e.code)
new_result = ResultWrapper(e.code, e.url, e.read())
def journey(func, *args, **kwargs): """ Wrap 'func' so that HTTPErrors and other things are captured when 'func' is executed as func(*args, **kwargs). Convert result from the various confusing options (exceptions, etc.) into a 'ResultWrapper'. This function may be more than a bit ugly & confusing, my apologies. Idea...
currentData = ''.join(self.currentData)
currentData = ''.join(str(self.currentData))
def endData(self, containerClass=NavigableString): if self.currentData: currentData = ''.join(self.currentData) if currentData.endswith('<') and self.convertHTMLEntities: currentData = currentData[:-1] + '&lt;' if not currentData.strip(): if '\n' in currentData: currentData = '\n' else: currentData = ' ' self.currentDa...
parse.execute_command(cmd, args, global_dict, local_dict)
parse.execute_command(cmd, args, global_dict, local_dict, "<shell>")
def do_cmd(self, rest_of_line, cmd=command): global_dict, local_dict = namespaces.get_twill_glocals()
parse.execute_command(cmd, args, global_dict, local_dict)
parse.execute_command(cmd, args, global_dict, local_dict, "<shell>")
def default(self, line): "Called when unknown command is executed."
raise
def do_cmd(rest_of_line, cmd=cmd): global_dict, local_dict = namespaces.get_twill_glocals()
"REMOTE_ADDRESS" : '127.0.0.1',
"REMOTE_ADDR" : '127.0.0.1',
def make_environ(inp, host, port, script_name): """ Take 'inp' as if it were HTTP-speak being received on host:port, and parse it into a WSGI-ok environment dictionary. Return the dictionary. Set 'SCRIPT_NAME' from the 'script_name' input, and, if present, remove it from the beginning of the PATH_INFO variable. """ #...
except ControlNotFoundError:
except (ControlNotFoundError, AmbiguityError):
def add_to_form(self, form): assert self._form is None or form == self._form, ( "can't add control to more than one form") self._form = form try: control = form.find_control(self.name, self.type) except ControlNotFoundError: Control.add_to_form(self, form) else: control.merge_control(self)
Stops the given job. @param jobId: jobId to stop @type jobId: int or uuid @raise: rMakeError: If job is already stopped.
Deletes the given jobs. @param jobIdList: list of jobIds to delete @type jobIdList: int or uuid list
def deleteJobs(self, jobIdList): """ Stops the given job.
if (key in conaryConfig and conaryConfig[key] is not conaryConfig.getDefaultValue(key)):
if key not in conaryConfig: continue if strictMode and key not in self._strictOptions: continue if conaryConfig[key] is not conaryConfig.getDefaultValue(key):
def __init__(self, readConfigFiles=False, root='', conaryConfig=None, serverConfig=None): # we default the value of these items to whatever they # are set to on the local system's conaryrc. conarycfg.ConaryConfiguration.__init__(self) if conaryConfig: for key in self.iterkeys(): if (key in conaryConfig and conaryConfig...
def getTrovesToBuild(conaryclient, troveSpecList, limitToHosts=None, message=None): toBuild = [] toFind = {} groupsToFind = [] repos = conaryclient.getRepos() cfg = conaryclient.cfg cfg.limitToHosts = limitToHosts cfg.buildTroveSpecs = []
def getResolveTroveTups(cfg, repos):
def getTrovesToBuild(conaryclient, troveSpecList, limitToHosts=None, message=None): toBuild = [] toFind = {} groupsToFind = [] repos = conaryclient.getRepos() cfg = conaryclient.cfg cfg.limitToHosts = limitToHosts cfg.buildTroveSpecs = [] # get resolve troves - use installLabelPath and install flavor # for these sin...
resolveTroves.append(lst)
def getTrovesToBuild(conaryclient, troveSpecList, limitToHosts=None, message=None): toBuild = [] toFind = {} groupsToFind = [] repos = conaryclient.getRepos() cfg = conaryclient.cfg cfg.limitToHosts = limitToHosts cfg.buildTroveSpecs = [] # get resolve troves - use installLabelPath and install flavor # for these sin...
cfg.resolveTroveTups = resolveTroves
return resolveTroves def getTrovesToBuild(conaryclient, troveSpecList, limitToHosts=None, message=None): toBuild = [] toFind = {} groupsToFind = [] repos = conaryclient.getRepos() cfg = conaryclient.cfg cfg.resolveTroveTups = getResolveTroveTups(cfg, repos) cfg.limitToHosts = limitToHosts cfg.buildTroveSpecs = []
def getTrovesToBuild(conaryclient, troveSpecList, limitToHosts=None, message=None): toBuild = [] toFind = {} groupsToFind = [] repos = conaryclient.getRepos() cfg = conaryclient.cfg cfg.limitToHosts = limitToHosts cfg.buildTroveSpecs = [] # get resolve troves - use installLabelPath and install flavor # for these sin...
elif not os.access(os.path.dirname(self.socketPath), os.W_OK) and :
elif not os.access(os.path.dirname(self.socketPath), os.W_OK):
def sanityCheck(self): currUser = pwd.getpwuid(os.getuid()).pw_name
return self.args[0]
return self.args
def __freeze__(self): return self.args[0]
def server_pidDied(self, pid, status):
def server_pidDied(self, server, pid, status):
def server_pidDied(self, pid, status): """ Called when the server collects a child process that has died. """ pass
self.troveListIndex = 0
self.troveListsIndex = 0
def __init__(self, cfg, db, troveLists): self.installLabelPath = cfg.installLabelPath self.searchByLabelPath = False self.troveListIndex = 0 self.troveLists = troveLists self.depList = None resolve.DepResolutionMethod.__init__(self, cfg, db)
self.troveLists[self.troveListIndex],
self.troveLists[self.troveListsIndex],
def resolveDependencies(self): intraDepSuggs = self._resolveIntraTroveDeps(self.intraDeps)
limitToHosts=limitToHosts)
limitToHosts=limitToHosts, recurseGroups=recurseGroups)
def buildTroves(self, troveSpecList, limitToHosts=None, recurseGroups=False): """ Display the current build configuration for this helper.
def __init__(self): self.conaryVersion = [int(x) for x in constants.version.split('.')]
def __init__(self, conaryVersion=None): if conaryVersion is None: conaryVersion = constants.version self.conaryVersion = [int(x) for x in conaryVersion.split('.')]
def __init__(self): self.conaryVersion = [int(x) for x in constants.version.split('.')] self.majorVersion = self.conaryVersion[0:2] self.minorVersion = self.conaryVersion[2] self.isOneOne = self.majorVersion == (1,1)
log.setVerbosity(log.WARNING)
log.setVerbosity(log.DEBUG)
def _findBestSolution(trove, (name, versionSpec, flavorSpec), solutions): """Given a trove, a buildRequirement troveSpec, and a set of troves that may match that buildreq, find the best trove. """ if len(solutions) == 1: return solutions[0] # flavorSpec _should_ have been handled by findTroves. # However, in some cases...
log.warning('nonstandard conary version "%s". Assuming latest "%s".' % (conaryVersion, constants.version))
if not self._warnedUser: log.warning('nonstandard conary version "%s". Assuming latest "%s".' % (conaryVersion, self.maxKnownVersion)) ConaryVersion._warnedUser = True
def __init__(self, conaryVersion=None): if conaryVersion is None: conaryVersion = constants.version
for x in constants.version.split('.') ]
for x in self.maxKnownVersion.split('.') ]
def __init__(self, conaryVersion=None): if conaryVersion is None: conaryVersion = constants.version
intraDeps.setdefault(depSet, {}).setdefault(dep, []).append(troveToGet)
l = suggsByDep.setdefault(dep, []) l.append(troveToGet) intraDeps.setdefault(depSet, {}).setdefault(dep, l)
def _getIntraTroveDeps(self, depList): intraDeps = {} for troveTup, depSet in depList: pkgName = troveTup[0].split(':', 1)[0] for dep in depSet.iterDepsByClass(deps.TroveDependencies): if (dep.name.startswith(pkgName) and dep.name.split(':', 1)[0] == pkgName): troveToGet = (dep.name, troveTup[1], troveTup[2]) intraDeps...
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough'], [';just_any_old_semicolon-starting-string', 'a ball of string'])))
'this string is way way too long and should overflow onto the next line eventually if I keep typing for long enough', ';just_any_old_semicolon-starting-string'], ['a string with a final quote"', 'a string with a " and a safe\';', 'a string with a final \''])))
def setUp(self): """Write out a file, then read it in again""" # fill up the block with stuff items = (('_item_1','Some data'), ('_item_2','Some_underline_data'), ('_item_3','34.2332'), ('_item_4','Some very long data which we hope will overflow the single line and force printing of another line aaaaa bbbbbb cccccc ddd...
names = ('_item_name_1','_item_name values = ((1,2,3,4),('hello','good_bye','a space',' (15.462, -99.34,10804,0.0001))
names = (('_item_name_1','_item_name values = (((1,2,3,4),('hello','good_bye','a space',' (15.462, -99.34,10804,0.0001)),)
def testTupleComplexSet(self): """Test setting multiple names in loop"""
self.failUnless(tuple(map(float, self.cf[names[0]])) == values[0]) self.failUnless(tuple(self.cf[names[1]]) == values[1]) self.failUnless(tuple(map(float, self.cf[names[2]])) == values[2])
self.failUnless(tuple(map(float, self.cf[names[0][0]])) == values[0][0]) self.failUnless(tuple(self.cf[names[0][1]]) == values[0][1]) self.failUnless(tuple(map(float, self.cf[names[0][2]])) == values[0][2])
def testTupleComplexSet(self): """Test setting multiple names in loop"""
except CifFile.CifError: pass
except (StarFile.StarError,CifFile.CifError): pass
def testTooLongSet(self): """test setting overlong data names""" dataname = '_a_long_long_'*7 try: self.cf[dataname] = 1.0 except CifFile.CifError: pass else: self.fail()
self.cf[(dataname,)] = ((1.0,2.0,3.0),) except CifFile.CifError: pass
self.cf[dataname] = (1.0,2.0,3.0) except (StarFile.StarError,CifFile.CifError): pass
def testTooLongLoopSet(self): """test setting overlong data names in a loop""" dataname = '_a_long_long_'*7 try: self.cf[(dataname,)] = ((1.0,2.0,3.0),) except CifFile.CifError: pass else: self.fail()
except CifFile.CifError: pass else: self.Fail()
except StarFile.StarError: pass else: self.fail()
def testBadStringSet(self): """test setting values with bad characters""" dataname = '_name_is_ok' try: self.cf[dataname] = "eca234\f\vaqkadlf" except CifFile.CifError: pass else: self.Fail()
except CifFile.CifError: pass
except StarFile.StarError: pass
def testBadNameSet(self): """test setting names with bad characters""" dataname = "_this_is_not ok" try: self.cf[dataname] = "nnn" except CifFile.CifError: pass else: self.Fail()
except CifFile.CifError: pass
except StarFile.StarError: pass
def testMoreBadStrings(self): dataname = "_name_is_ok" val = "so far, ok, but now we have a " + chr(128) try: self.cf[dataname] = val except CifFile.CifError: pass else: self.Fail()
self.names = ('_item_name_1','_item_name self.values = ((1,2,3,4),('hello','good_bye','a space',' (15.462, -99.34,10804,0.0001))
self.names = (('_item_name_1','_item_name self.values = (((1,2,3,4),('hello','good_bye','a space',' (15.462, -99.34,10804,0.0001)),)
def setUp(self): self.cf = CifFile.CifBlock()
results = self.cf.GetLoop(self.names[2]) for (key,value) in results: self.failUnless(key in self.names) self.failUnless(tuple(value) == self.values[list(self.names).index(key)])
results = self.cf.GetLoop(self.names[0][2]) for key in results.keys(): self.failUnless(key in self.names[0]) self.failUnless(tuple(results[key]) == self.values[0][list(self.names[0]).index(key)])
def testLoop(self): """Check GetLoop returns values and names in right order""" results = self.cf.GetLoop(self.names[2])
self.cf.RemoveCifItem(self.names[1])
self.cf.RemoveCifItem(self.names[0][1])
def testLoopRemove(self): """Check item deletion inside loop""" self.cf.RemoveCifItem(self.names[1]) try: a = self.cf[self.names[1]] except KeyError: pass else: self.Fail()
a = self.cf[self.names[1]]
a = self.cf[self.names[0][1]]
def testLoopRemove(self): """Check item deletion inside loop""" self.cf.RemoveCifItem(self.names[1]) try: a = self.cf[self.names[1]] except KeyError: pass else: self.Fail()
for name in self.names: self.cf.RemoveCifItem(name) self.failUnless(len(self.cf.block["loops"])==0, `self.cf.block["loops"]`)
for name in self.names[0]: self.cf.RemoveCifItem(name) self.failUnless(len(self.cf.loops)==0, `self.cf.loops`)
def testFullLoopRemove(self): """Check removal of all loop items""" for name in self.names: self.cf.RemoveCifItem(name) self.failUnless(len(self.cf.block["loops"])==0, `self.cf.block["loops"]`)
newkeys = map(lambda a:a[0],self.cf.GetLoop('_item_name
newkeys = self.cf.GetLoop('_item_name
def testAddToLoop(self): """Test adding to a loop""" adddict = {'_address':['1 high street','2 high street','3 high street','4 high st'], '_address2':['Ecuador','Bolivia','Colombia','Mehico']} self.cf.AddToLoop('_item_name#2',adddict) newkeys = map(lambda a:a[0],self.cf.GetLoop('_item_name#2')) self.failUnless(adddict....
except CifFile.CifError:
except StarFile.StarLengthError:
def testBadAddToLoop(self): """Test incorrect loop addition""" adddict = {'_address':['1 high street','2 high street','3 high street'], '_address2':['Ecuador','Bolivia','Colombia']} try: self.cf.AddToLoop('_no_item',adddict) except KeyError: pass else: self.Fail() try: self.cf.AddToLoop('_item_name#2',adddict) except C...
else: self.Fail()
else: self.fail()
def testBlockName(self): """Make sure long block names cause errors""" df = CifFile.CifBlock() cf = CifFile.CifFile() try: cf['a_very_long_block_name_which_should_be_rejected_out_of_hand123456789012345678']=df except CifFile.CifError: pass else: self.Fail()
self.df = CifFile.CifFile('test.cif')['testblock']
self.ef = CifFile.CifFile('test.cif') self.df = self.ef['testblock']
def setUp(self): """Write out a file, then read it in again. Non alphabetic ordering to check order preservation.""" # fill up the block with stuff items = (('_item_1','Some data'), ('_item_3','34.2332'), ('_item_4','Some very long data which we hope will overflow the single line and force printing of another line aaaa...
for key,value in olditems:
for key,value in olditems.items():
def testLoopDataInOut(self): """Test writing in and out loop data""" olditems = self.cf.GetLoop('_item_5') for key,value in olditems: self.failUnless(tuple(map(str,value))==tuple(self.df[key])) # save frame test olditems = self.cfs.GetLoop('_sitem_5') for key,value in olditems: self.failUnless(tuple(map(str,value))==tu...
olditems = self.cfs.GetLoop('_sitem_5')
olditems = self.cfs.GetLoop('_sitem_5').items()
def testLoopDataInOut(self): """Test writing in and out loop data""" olditems = self.cf.GetLoop('_item_5') for key,value in olditems: self.failUnless(tuple(map(str,value))==tuple(self.df[key])) # save frame test olditems = self.cfs.GetLoop('_sitem_5') for key,value in olditems: self.failUnless(tuple(map(str,value))==tu...
for key,value in olditems:
for key,value in olditems.items():
def testLoopStringInOut(self): """Test writing in and out string loop data""" olditems = self.cf.GetLoop('_string_1') newitems = self.df.GetLoop('_string_1') for key,value in olditems: compstringa = map(lambda a:re.sub('\n','',a),value) compstringb = map(lambda a:re.sub('\n','',a),self.df[key]) self.failUnless(compstri...
self.assertRaises(CifFile.CifError,CifFile.merge_dic,[self.offdic,self.adic],mergemode="strict")
self.assertRaises(StarFile.StarError,CifFile.merge_dic,[self.offdic,self.adic],mergemode="strict")
def testAStrict(self): self.assertRaises(CifFile.CifError,CifFile.merge_dic,[self.offdic,self.adic],mergemode="strict")
else: self.Fail()
else: self.fail()
def testTooLongSet(self): """test setting overlong data names""" dataname = '_a_long_long_'*7 try: self.cf[dataname] = 1.0 except CifFile.CifError: pass else: self.Fail()
else: self.Fail()
else: self.fail()
def testTooLongLoopSet(self): """test setting overlong data names in a loop""" dataname = '_a_long_long_'*7 try: self.cf[(dataname,)] = ((1.0,2.0,3.0),) except CifFile.CifError: pass else: self.Fail()
self.cf.AddSaveFrame("test_save_frame",self.save_block)
self.cf["saves"]["test_save_frame"] = self.save_block
def setUp(self): """Write out a file, then read it in again""" # fill up the block with stuff items = (('_item_1','Some data'), ('_item_2','Some_underline_data'), ('_item_3','34.2332'), ('_item_4','Some very long data which we hope will overflow the single line and force printing of another line aaaaa bbbbbb cccccc ddd...
self.cf.AddSaveFrame("some_name",bb)
self.cf["saves"]["some_name"]=bb ddl1dic = CifFile.CifDic("dictionaries/cif_core.dic") class DictTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testnum_and_esd(self): """Test conversion of numbers with esds""" testnums = ["5.65","-76.24(3)","8(2)","6.24(3)e3","55.2(2)d4"] res = ...
def testAddSaveFrame(self): """Test adding a save frame""" s_items = (('_sitem_1','Some save data'), ('_sitem_2','Some_underline_data'), ('_sitem_3','34.2332'), ('_sitem_4','Some very long data which we hope will overflow the single line and force printing of another line aaaaa bbbbbb cccccc dddddddd eeeeeeeee ffffffff...
self.ddl1dic = CifFile.CifFile("dictionaries/cif_core.dic") self.validcif = CifFile.ValidCifFile("tests/C13H22O3.cif",diclist=[self.ddl1dic])
def setUp(self):
bl = CifFile.CifBlock() self.cf = CifFile.ValidCifFile(dic=ddl1dic) self.cf["test_block"] = bl self.cf["test_block"].AddCifItem(("_atom_site_label", ["C1","Cr2","H3","U4"]))
def setUp(self):
del self.validcif del self.ddl1dic
del self.cf def testItemType(self): """Test that types are correctly checked and reported""" self.cf["test_block"]["_diffrn_radiation_wavelength"] = "0.75" try: self.cf["test_block"]["_diffrn_radiation_wavelength"] = "moly" except CifFile.ValidCifError: pass def testItemEsd(self): """Test that non-esd items are not ...
def tearDown(self): del self.validcif
self.validcif.check_and_report()
CifFile.validate_report(CifFile.validate("tests/C13H2203_with_errors.cif",dic=ddl1dic)) class FakeDicTestCase(unittest.TestCase): def setUp(self): self.testcif = CifFile.CifFile("dictionaries/novel_test.cif") def testTypeConstruct(self): self.assertRaises(CifFile.ValidCifError,CifFile.ValidCifFile, diclist=["diction...
def testReport(self):
def OpenLogFile(self, event): subDirName = self.GetProcessNameFromHwnd(event.Window) subDirName = re.sub(r':?\\',r'__',subDirName) WindowName = re.sub(r':?\\',r'__',str(event.WindowName)) try: os.makedirs(os.path.join(self.rootLogDir, subDirName), 0777) except OSError, detail: if(detail.errno==17): pass else: print ...
self.systemlog = open(r"C:\Temp\logdir\systemlog.txt", 'a')
def __init__(self, rootLogDir=r"C:\Temp\logdir", debug=False): self.debug = debug self.rootLogDir = os.path.normpath(rootLogDir) try: os.mkdir(self.rootLogDir, 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass else: print "OSError:", detail self.writeTarget = "...
return
return True
def OpenLogFile(self, event): if self.options.oneFile != None: if self.writeTarget == "": self.writeTarget = os.path.join(os.path.normpath(self.options.dirName), os.path.normpath(self.options.oneFile)) try: self.log = open(self.writeTarget, 'a') except OSError, detail: if(detail.errno==17): #if file already exists, s...
print "OSError:", repr(detail)
print "OSError:", detail
def __init__(self, rootLogDir=r"C:\Temp\logdir", debug=False): self.debug = debug self.rootLogDir = os.path.normpath(rootLogDir) try: os.mkdir(self.rootLogDir, 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass else: print "OSError:", repr(detail) self.writeTarg...
self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName)
subDirName = self.GetProcessNameFromHwnd(event.Window) subDirName = re.sub(r':?\\',r'__',subDirName) WindowName = re.sub(r':?\\',r'__',str(event.WindowName))
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777)
os.makedirs(os.path.join(self.rootLogDir, subDirName), 0777)
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
self.filename = time.strftime('%Y%m%d') + "_" + str(event.Window) + "_" + str(event.WindowName) + ".txt"
filename = time.strftime('%Y%m%d') + "_" + str(event.Window) + "_" + WindowName + ".txt"
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
if self.writeTarget != os.path.join(self.rootLogDir, self.subDirName, self.filename):
if self.writeTarget != os.path.join(self.rootLogDir, subDirName, filename):
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
self.writeTarget = os.path.join(self.rootLogDir, self.subDirName, self.filename)
self.writeTarget = os.path.join(self.rootLogDir, subDirName, filename)
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
self.log = open(os.path.join(self.rootLogDir, self.subDirName, self.filename), 'a')
self.log = open(self.writeTarget, 'a')
def OpenLogFile(self, event): self.subDirName = self.GetProcessNameFromHwnd(event.Window) self.subDirName = re.sub(r':?\\',r'__',self.subDirName) try: os.makedirs(os.path.join(self.rootLogDir, self.subDirName), 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass e...
if self.debug: print "(threadid, processid)", threadpid, procpid
def GetProcessNameFromHwnd(self, hwnd): threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd) if self.debug: print "(threadid, processid)", threadpid, procpid # PROCESS_QUERY_INFORMATION (0x0400) or PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF) mypyproc = win32api.OpenProcess(win32con.PROCESS_...
print "OSError:", detail
self.PrintDebug(sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") except: self.PrintDebug("Unexpected error: " + sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n")
def __init__(self, options): self.options = options self.options.dirName = os.path.normpath(self.options.dirName) try: os.makedirs(self.options.dirName, 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass else: print "OSError:", detail self.filter = re.compile(r...
self.systemlog = open(os.path.join(os.path.normpath(self.options.dirName), self.options.systemLog), 'a')
try: self.systemlog = open(os.path.join(self.options.dirName, self.options.systemLog), 'a') except OSError, detail: if(detail.errno==17): pass else: self.PrintDebug(sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") except: self.PrintDebug("Unexpected error: " + sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n")
def __init__(self, options): self.options = options self.options.dirName = os.path.normpath(self.options.dirName) try: os.makedirs(self.options.dirName, 0777) except OSError, detail: if(detail.errno==17): #if directory already exists, swallow the error pass else: print "OSError:", detail self.filter = re.compile(r...
self.OpenLogFile(event)
loggable = self.OpenLogFile(event) if not loggable: self.PrintDebug("some error occurred when opening the log file. we cannot log this event. check systemlog (if specified) for details.\n") return
def WriteToLogFile(self, event): loggable = self.TestForNoLog(event) if not loggable: # if the program is in the no-log list, we return without writing to log. if self.options.debug: self.PrintDebug("not loggable, we are outta here\n") return if self.options.debug: self.PrintDebug("loggable, le...
self.log = open(self.writeTarget, 'a')
try: self.log = open(self.writeTarget, 'a') except OSError, detail: if(detail.errno==17): pass else: self.PrintDebug(sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False except: self.PrintDebug("Unexpected error: " + sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False
def OpenLogFile(self, event): if self.options.oneFile != None: if self.writeTarget == "": self.writeTarget = os.path.join(os.path.normpath(self.options.dirName), os.path.normpath(self.options.oneFile)) self.log = open(self.writeTarget, 'a') self.PrintDebug("writing to: " + self.writeTarget + "\n") return
except OSError, detail: if(detail.errno==17): pass else: print "OSError:", detail
except OSError, detail: if(detail.errno==17): pass else: self.PrintDebug(sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False except: self.PrintDebug("Unexpected error: " + sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False
def OpenLogFile(self, event): if self.options.oneFile != None: if self.writeTarget == "": self.writeTarget = os.path.join(os.path.normpath(self.options.dirName), os.path.normpath(self.options.oneFile)) self.log = open(self.writeTarget, 'a') self.PrintDebug("writing to: " + self.writeTarget + "\n") return
filename = filename[0:200] + ".txt"
if len(os.path.join(self.options.dirName, subDirName, filename)) > 255: if len(os.path.join(self.options.dirName, subDirName)) > 250: self.PrintDebug("root log dir + subdirname is longer than 250. cannot log.") return False else: filename = filename[0:255-len(os.path.join(self.options.dirName, subDirName))-4] + ".txt"
def OpenLogFile(self, event): if self.options.oneFile != None: if self.writeTarget == "": self.writeTarget = os.path.join(os.path.normpath(self.options.dirName), os.path.normpath(self.options.oneFile)) self.log = open(self.writeTarget, 'a') self.PrintDebug("writing to: " + self.writeTarget + "\n") return
self.log = open(self.writeTarget, 'a')
try: self.log = open(self.writeTarget, 'a') except OSError, detail: if(detail.errno==17): pass else: self.PrintDebug(sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False except: self.PrintDebug("Unexpected error: " + sys.exc_info()[0] + ", " + sys.exc_info()[1] + "\n") return False return True
def OpenLogFile(self, event): if self.options.oneFile != None: if self.writeTarget == "": self.writeTarget = os.path.join(os.path.normpath(self.options.dirName), os.path.normpath(self.options.oneFile)) self.log = open(self.writeTarget, 'a') self.PrintDebug("writing to: " + self.writeTarget + "\n") return
for path in noLog: if os.stat(path) == os.stat(subDirName): if self.debug: print "we dont log this" return False
if noLog != None: for path in noLog: if os.stat(path) == os.stat(subDirName): if self.debug: print "we dont log this" return False
def OpenLogFile(self, event, noLog): filter=r"[\\\/\:\*\?\"\<\>\|]+" #regexp filter for the non-allowed characters in windows filenames. subDirName = self.GetProcessNameFromHwnd(event.Window) #our subdirname is the full path of the process owning the hwnd. for path in noLog: #check our options ...