def process(self, spill_in): """ Process a spill, get slab hits via get_slab_hits @param self Object reference. @param spill Current spill. @returns list of JSON documents. If the the spill count is divisible by the current refresh rate then a list of 3 histogram JSON documents are returned. Otherwise a single list with the input spill is returned. @throws ValueError if "slab_hits" and "space_points" information is missing from the spill. """ # the mergers now process MAUS::Data # the output are images in json strings # check if input is Data, # if it's not data, load json and convert to data # note that online celery/mongo returns json string def_doc = {"maus_event_type":"Spill"} if spill_in.__class__.__name__ == 'MAUS::Data': spill_data = spill_in del spill_in else: try: json_doc = json.loads(spill_in.rstrip()) except Exception, e: # pylint:disable=W0703 def_doc = ErrorHandler.HandleException(def_doc, self) return unicode(json.dumps(def_doc)) try: spill_data = maus_cpp.converter.data_repr(json_doc) json_doc = None except Exception: # pylint:disable=W0703 def_doc = ErrorHandler.HandleException(def_doc, self) return unicode(json.dumps(def_doc))
def ms_get_image_data(self, byteImage): try: r = requests.post(ms_cognitive_url, params=ms_cognitive_params, headers=ms_cognitive_headers_byteimg, data=byteImage) faces = json.loads(r.text, object_hook=lambda d: Namespace(**d)) if r.status_code == 200 and len(faces) > 0: self.currentMood.divide_all_by( 2) # decrease importance of previous mood for face in faces: evaluate_face(face, self.currentMood) self.currentMood.divide_all_by(len(faces)) #print(self.currentMood) return True elif r.status_code == 200: print("No faces found") return False else: ErrorHandler.handle_error_response(r, "MS Cognitive Services") return False except ConnectionError: print("connection error") return False
def Add(self): """ Add a user """ if (User.GetByUsername(self.username) != None): raise ErrorHandler.ErrorHandler( message="user with that username already exists", status_code=400) allUsers = User.GetAll() for user in allUsers: if user.email_address == self.email_address: raise ErrorHandler.ErrorHandler( message="user with that email address already exists", status_code=400) if (not self.first_name or not self.password or not self.username): raise ErrorHandler.ErrorHandler( message="one or more required fields are missing", status_code=400) # encrypt the password self.password = User.EncryptPassword(self.password) # Default to standard role, start with 0 points self.role_id = app.config["STANDARD_ROLE_ID"] self.points = 0 db.session.add(self) db.session.commit() return True
def main(filename): # get the root of the parse tree of the input file parseTreeRoot = parseFile(filename) # the errorHandler which will group all of the errors errorHandler = ErrorHandler(filename) try: # create an AST an attach it to a listener so the listener can fill in the tree abstractSyntaxTree = buildAST(parseTreeRoot) firstPassDecoration(abstractSyntaxTree) # create a symbol table and symbol table filler, fill in the table and check if everything is declared before it is used in the c file symbolTable = SymbolTable() scopeCheck(abstractSyntaxTree, errorHandler, symbolTable) # do the type checking typeCheck(abstractSyntaxTree, errorHandler) output(str(abstractSyntaxTree)) output(str(symbolTable)) # generate code if not errorHandler.errorCount(): generateCode(abstractSyntaxTree, symbolTable) except Exception as e: ex_type, ex, tb = sys.exc_info() traceback.print_exception(ex_type, ex, tb) if errorHandler.errorCount() or errorHandler.warningCount(): print(str(errorHandler.errorCount()) + " error" + ("s" if errorHandler.errorCount() != 1 else "")) print(str(errorHandler.warningCount()) + " warning" + ("s" if errorHandler.warningCount() != 1 else "")) errorHandler.printErrors()
def process(self, json_string): """ Update the histogram with data from the current spill and output the histogram. @param self Object reference. @param json_string String with current JSON document. @returns JSON document containing current histogram. """ # Load and validate the JSON document. try: json_doc = json.loads(json_string.rstrip()) except Exception: # pylint:disable=W0703 json_doc = {} ErrorHandler.HandleException(json_doc, self) return unicode(json.dumps(json_doc)) self.spill_count = self.spill_count + 1 # Process spill and update histograms. try: result = self._update_histograms(json_doc) except Exception: # pylint:disable=W0703 ErrorHandler.HandleException(json_doc, self) return unicode(json.dumps(json_doc)) image_list = [image['image'] for image in result] # Convert results to strings. return json.dumps({ "maus_event_type": "Image", "image_list": image_list })
def get_auth_token(self): try: r = requests.post(spotify_auth_url, headers=spotify_auth_header, params=spotify_auth_params) if r.status_code == 200: self.authToken = r.json()['access_token'] else: ErrorHandler.handle_error_response(r, "Spotify Authorization") except ConnectionError: print("error connecting to spotify auth")
def process(self, spill): """ Update the histogram with data from the current spill and output the histogram. @param self Object reference. @param json_string String with current JSON document. @returns JSON document containing current histogram. """ # Load and validate the JSON document. def_doc = {"maus_event_type": "Image", "image_list": []} # the mergers now process MAUS::Data # the output are images in json strings # check if input is Data, # if it's not data, load json and convert to data # note that online celery/mongo returns json string if spill.__class__.__name__ == 'MAUS::Data': spill_data = spill del spill else: try: json_doc = json.loads(spill.rstrip()) except Exception: # pylint:disable=W0703 def_doc = ErrorHandler.HandleException(def_doc, self) return unicode(json.dumps(def_doc)) try: spill_data = maus_cpp.converter.data_repr(json_doc) json_doc = None del spill except Exception: # pylint:disable=W0703 def_doc = ErrorHandler.HandleException(def_doc, self) return unicode(json.dumps(def_doc)) self.spill_count = self.spill_count + 1 # Process spill and update histograms. try: result = self._update_histograms(spill_data) except Exception: # pylint:disable=W0703 def_doc = ErrorHandler.HandleException(def_doc, self) return unicode(json.dumps(def_doc)) image_list = [image['image'] for image in result] # delete references to data if any try: maus_cpp.converter.del_data_repr(spill) except: # pylint: disable=W0702 pass # Convert results to strings. return json.dumps({ "maus_event_type": "Image", "image_list": image_list })
def process_image(filename, image_type): # Check for a valid file extension check_file_extension(filename=filename, image_type=image_type) # Start internal function timer configuration.log_debug_out( configuration.inspect.stack()[0][3], "Processing {0}{1}".format( filename, "-" * (150 - len("Processing {0}".format(filename))))) start = timeit.default_timer() configuration.log_debug_out( configuration.inspect.stack()[0][3], "Processing image type: {0}".format(image_type)) # Handle the image type accordingly if image_type == "case": if "case3" in filename: configuration.log_debug_out(configuration.inspect.stack()[0][3], "ENTERING CASE MODE") cases.process_cases(filename=filename) else: configuration.logging.warn( "Waiting for third case file to process cases") ErrorHandler.sys_exit(configuration.EXIT_STATUS.WAITING_FOR_CASES) elif image_type == "guitar": configuration.log_debug_out(configuration.inspect.stack()[0][3], "ENTERING GUITAR MODE") guitar_process.process_guitar(filename=filename) else: configuration.log_debug_out(configuration.inspect.stack()[0][3], "Could not determine image type") ErrorHandler.sys_exit(configuration.EXIT_STATUS.BAD_TYPE) # Stop internal function timer and log the info stop = timeit.default_timer() # If we are not testing we want to remove the source image if not configuration.TESTING: try: os.remove(filename) except: configuration.log_debug_out( configuration.inspect.stack()[0][3], "Failed to remove file {0}".format(filename)) configuration.log_debug_out( configuration.inspect.stack()[0][3], "It took {0} seconds to process image{1}\n".format( stop - start, "-" * (150 - len( "It took {0} seconds to process image".format(stop - start)))))
def test_cpp_error(self): #pylint: disable = R0201 """ Test CppError type works okay """ my_error = ErrorHandler.CppError("Some message") assert (my_error.args == ("Some message", )) assert (repr(my_error) == "Some message")
def test_handle_exception_on_error(self): """Check that we handle the exception correctly (raise, halt, etc)""" error_handler = ErrorHandler.ErrorHandler() doc = {} error_handler.on_error = 'halt' try: raise RuntimeError("Test error 1") except RuntimeError: try: doc = error_handler.HandleException(doc, self) except SystemExit: assert (sys.exc_info()[0] == type(SystemExit())) error_handler.on_error = 'raise' try: raise RuntimeError("Test error 1") except RuntimeError: try: doc = error_handler.HandleException(doc, self) except RuntimeError: assert (sys.exc_info()[0] == type(RuntimeError())) error_handler.on_error = 'none' try: raise RuntimeError("Test error 1") except RuntimeError: doc = error_handler.HandleException(doc, self) error_handler.on_error = 'BAD_STRING' try: raise RuntimeError("Test error 1") except RuntimeError: with self.assertRaises(KeyError): error_handler.HandleException(doc, self)
def parseFile(self, filename): input_file = FileStream(filename) lexer = CLexer(input_file) stream = CommonTokenStream(lexer) parser = CParser(stream) programContext = parser.program() if parser._syntaxErrors > 0: raise Exception("error parsing file " + filename) walker = ParseTreeWalker() abstractSyntaxTree = AbstractSyntaxTree(); self.errorHandler = ErrorHandler(filename) listener = Listener(abstractSyntaxTree) walker.walk(listener, programContext) decorator = VisitorDecorator() decorator.visitProgramNode(abstractSyntaxTree.root) symbolTable = SymbolTable() functionFiller = VisitorSymbolTableFiller(symbolTable, self.errorHandler) functionFiller.visitProgramNode(abstractSyntaxTree.root) tableFiller = VisitorDeclarationProcessor(symbolTable, self.errorHandler) tableFiller.visitProgramNode(abstractSyntaxTree.root) typeCheck = VisitorTypeChecker(self.errorHandler) typeCheck.visitProgramNode(abstractSyntaxTree.root) if self.errorHandler.errorCount() == 0: pFilename = os.path.splitext(filename)[0] + ".p" codeGenerator = VisitorCodeGenerator(symbolTable, pFilename) codeGenerator.visitProgramNode(abstractSyntaxTree.root)
def play(): print('Play button was pressed!') try: import ArduinoMaster from random import randint # Reads the playing state from JSON file with open('playstate.json') as infile: cur_state = json.load(infile) cur_state = cur_state['playing'] # If the tune hasn't been played before song = randint( 1, 3 ) # You must know how many songs you managed to gram into Arduino if cur_state == False: ArduinoMaster.playbuzzer(song) lastplayed = True dump = {"playing": lastplayed} with open('playstate.json', 'w') as outfile: json.dump(dump, outfile) return render_template('play.html') # "Now Playing" # Else if it has been played before else: ArduinoMaster.playbuzzer(song) return render_template('play.html') # "Replaying" except Exception as e: logging.exception(e) return ErrorHandler.app_error(e)
def stop(): try: import ArduinoMaster with open('playstate.json') as infile: cur_state = json.load(infile) cur_state = cur_state['playing'] # If the tune is playing if cur_state == True: print('Stop button was pressed!') ArduinoMaster.playbuzzer() lastplayed = False # Dumps in not playing state, which is false dump = {"playing": lastplayed} with open('playstate.json', 'w') as outfile: json.dump(dump, outfile) return render_template('stop.html') # "Stopping" # Else if it is not playing else: return render_template('notplaying.html') # "Already stopped" # Error handling except Exception as e: logging.exception(e) return ErrorHandler.app_error(e)
def death(self): """ Death the group by invoking death on all members. @param self Object reference. @return True if all members return True else return False. @throws MapPyGroupDeathException if any member's death function threw an exception and the ErrorHandler is set to raise exceptions. """ death_ok = True exceptions = [] # List of exceptions from each member. for worker in self._workers: try: # Because None is also considered a pass, we can't # simply use 'and' here. worker_death_ok = worker.death() if (worker_death_ok is None): worker_death_ok = True death_ok = death_ok and worker_death_ok except: # pylint:disable = W0702 # Record the exception and continue. exceptions.append(worker.__class__.__name__ + ": " + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])) death_ok = False if (not death_ok): if (len(exceptions) != 0): try: raise MapPyGroupDeathException(exceptions) except: # pylint:disable = W0702 # ErrorHandler has the final say as to whether # an exception is thrown. ErrorHandler.HandleException({}, self) return False return True
def get_space_points(self, doc): """ get the TOF space points """ try: spill = json.loads(doc) if 'space_points' not in spill: return False if spill['space_points'] is None: return False space_points = spill['space_points'] if 'tof0' not in space_points: return False self._sp_tof0 = space_points['tof0'] if 'tof1' not in space_points: return False self._sp_tof1 = space_points['tof1'] if 'tof2' not in space_points: return False self._sp_tof2 = space_points['tof2'] except Exception: #pylint: disable=W0703 ErrorHandler.HandleException({}, self) return True
def test_config_to_error_handler(self): """ Test error handler setup from configuration """ config_test = { 'verbose_level': 0, 'errors_to_stderr': None, 'errors_to_json': True, 'on_error': 'none' } error_handler = ErrorHandler.ErrorHandler() error_handler.ConfigurationToErrorHandler(config_test) self.assertTrue(error_handler.error_to_stderr) config_test['verbose_level'] = 4 error_handler.ConfigurationToErrorHandler(config_test) self.assertFalse(error_handler.error_to_stderr) self.assertTrue(error_handler.error_to_json) self.assertEqual(error_handler.on_error, 'none') config_test = { 'verbose_level': 4, 'errors_to_stderr': True, 'errors_to_json': False, 'on_error': 'raise' } error_handler.ConfigurationToErrorHandler(config_test) self.assertTrue(error_handler.error_to_stderr) self.assertFalse(error_handler.error_to_json) self.assertEqual(error_handler.on_error, 'raise')
def test_handle_exception_json(self): """Check the flag that controls sending errors to json works""" error_handler = ErrorHandler.ErrorHandler() error_handler.error_to_json = True doc = {} try: raise RuntimeError("Test error 1") except RuntimeError: doc = error_handler.HandleException(doc, self) self.assertEqual( doc["errors"]["ErrorHandlerTestCase"], "<type 'exceptions.RuntimeError'>: Test error 1", ) error_handler.error_to_json = False try: raise RuntimeError("Test error 2") except RuntimeError: doc = error_handler.HandleException(doc, self) self.assertEqual( doc["errors"]["ErrorHandlerTestCase"], "<type 'exceptions.RuntimeError'>: Test error 1", ) error_handler.error_to_json = True try: raise RuntimeError("Test error 3") except RuntimeError: doc = error_handler.HandleException(doc, self) self.assertEqual( doc["errors"]["ErrorHandlerTestCase"], "<type 'exceptions.RuntimeError'>: Test error 3", )
def birth(self, json_configuration): """ Sets up birth. Places variables and parameters in ConfigurationDefaults """ try: json_configuration = unicode(json_configuration) config_doc = json.loads(json_configuration) if config_doc: keys = [] keys.append("ckov_position_threshold") keys.append("ckov_pulse_area_threshold") keys.append("ckov_window_min") keys.append("ckov_window_max") for i in range(len(keys)): if keys[i] in config_doc: self._position_threshold = config_doc[str(keys[0])] self._pulse_area_threshold = config_doc[str(keys[1])] self._window_min = config_doc[str(keys[2])] self._window_max = config_doc[str(keys[3])] return True except Exception: #pylint:disable=W0703 ErrorHandler.HandleException({}, self) return False
def birth(self, config_document="{}"): """ birth() opens the json file based on datacards @param json_config json string holding a dict of json parameters - input_json_file_name datacard controls file name to open - input_json_file_type datacard controls file type (either 'text' or 'gzip' @returns True on success, False on failure If self._file is opens self._file file. """ try: if self._file == None: config = json.loads(config_document) fname = config["input_json_file_name"] if config["input_json_file_type"] == "gzip": self._file = gzip.GzipFile(fname, 'r') elif config["input_json_file_type"] == "text": self._file = open(fname, 'r') else: raise IOError('Did not recognise input_json_file_type '+\ str(config["input_json_file_type"])) return True except Exception: #pylint: disable=W0703 ErrorHandler.HandleException({}, self) return False
def test_birth_death_exception(self): """ Test calling birth where one worker's birth function throws an exception and other worker's death functions also throw exceptions. @param self Object reference. """ ErrorHandler.DefaultHandler().on_error = 'raise' # Create worker that fails on death. class TestWorker: # pylint:disable = C0111, W0232 def birth(self, json_document): pass def process(self, spill): pass def death(self): # pylint:disable = R0201 raise ValueError("Test") workers = [MapPyDoNothing(), TestWorker(), MapPyTestMap()] group = MapPyGroup(workers) # Force 3rd worker to fail on birth. with self.assertRaisesRegexp(MapPyGroupBirthException, ".*"): group.birth("""{"birth_result":%s}""" % \ MapPyTestMap.EXCEPTION)
def tearDown(self): # pylint: disable=C0103, C0202 """ Destructor """ ErrorHandler.DefaultHandler().on_error = self.on_error_standard self.output.death() maus_cpp.globals.death(self.cards)
def ResetPassword(self, new_password=None, new_password_verify=None): """ Updates a user's password without old password verification """ if (not new_password or not new_password_verify): raise ErrorHandler.ErrorHandler( message="password or password verification was empty", status_code=400) if new_password == new_password_verify: new_password = User.EncryptPassword(new_password) self.password = new_password db.session.commit() return True else: raise ErrorHandler.ErrorHandler(message="passwords do not match", status_code=400)
def setUp(self): # pylint: disable=C0103, C0202 """ Define cards and initialise Output """ self.output = MAUS.OutputCppRoot() self.outdir = os.environ["MAUS_ROOT_DIR"]+"/tmp/test_output_cpp_root/" self.outfile = self.outdir+"test_outputCppRoot.root" try: os.mkdir(self.outdir) except OSError: pass try: os.mkdir(self.outdir+"/end_of_run/") except OSError: pass self.on_error_standard = ErrorHandler.DefaultHandler().on_error #ref = {"$ref":"#test_branch/double_by_value"} self.test_data = { "scalars":{}, "spill_number":1, "run_number":1, "daq_event_type":"physics_event", "recon_events":[], "mc_events":[], "maus_event_type":"Spill", } self.test_job_header = { "start_of_job":{"date_time":"1976-04-04T00:00:00.000000"}, "bzr_configuration":"", "bzr_revision":"", "bzr_status":"", "maus_version":"", "json_configuration":"output cpp root test", "maus_event_type":"JobHeader", } self.test_run_header = { "run_number":1, "maus_event_type":"RunHeader" } self.test_run_footer = { "run_number":-1, "maus_event_type":"RunFooter" } self.test_job_footer = { "end_of_job":{"date_time":"1977-04-04T00:00:00.000000"}, "maus_event_type":"JobFooter", } self.cards = Configuration.Configuration().getConfigJSON() self.cards = json.loads(self.cards) self.cards["output_root_file_name"] = self.outfile self.cards["output_root_file_mode"] = "one_big_file" self.cards["end_of_run_output_root_directory"] = \ self.outdir+"/end_of_run/" self.cards["verbose_level"] = 2 self.cards = json.dumps(self.cards) if maus_cpp.globals.has_instance(): maus_cpp.globals.death() maus_cpp.globals.birth(self.cards) self.output.birth(self.cards)
def test_error_handler(self): #pylint: disable=R0201 """ Test initialisation of the error handler """ error_handler = ErrorHandler.ErrorHandler() assert (error_handler.error_to_stderr == True) assert (error_handler.error_to_json == True) assert (error_handler.on_error == 'none')
def lex_file(self, path): try: with open(path, 'r') as f: data = f.read() except: raise ErrorHandler.FileError(path) return None return self.lex(data)
def birth(self, json_configuration): """birth: check json doc""" try: config_doc = json.loads(json_configuration) if config_doc: return True except Exception: #pylint: disable=W0703 ErrorHandler.HandleException({}, self) return False
def homepage(): try: # Attempts to launch the serial communication module - ArduinoMaster import ArduinoMaster print("Hello, motherfuckers!") return render_template('index.html') except Exception as e: logging.exception(e) return ErrorHandler.app_error(e)
def UpdatePassword(self, new_password=None, new_password_verify=None, old_password=None): """ Updates a user's password """ if new_password == new_password_verify: if self.VerifyPassword(old_password): new_password = User.EncryptPassword(new_password) self.password = new_password db.session.commit() return True else: raise ErrorHandler.ErrorHandler( message="old password does not match stored password", status_code=400) else: raise ErrorHandler.ErrorHandler(message="passwords do not match", status_code=400)
def setUp(self): """ Reset the ErrorHandler to "none". @param self Object reference. """ ErrorHandler.DefaultHandler().on_error = 'none' if not maus_cpp.globals.has_instance(): maus_cpp.globals.birth( Configuration.Configuration().getConfigJSON())
def logException(): out = cStringIO.StringIO() ErrorHandler.logError(out) errorTags = [frame.executable.dt._error_tag for frame in Component.componentStack if isinstance(frame.executable, Executables.STMLExecutable) if hasattr(frame.executable.dt, '_error_tag')] if errorTags: out.write('Tag traceback (most recent tag last):\n') for tag in errorTags: if tag: out.write(' File "%s", line %s\n' % (tag._name, tag._lineno)) out.write(' %s\n' % tag.tag) else: out.write(' File ??, line??\n') x = out.getvalue() Logs.ERROR(x) return x
def EncryptPassword(password_to_encrypt): """ Encode, encrypt, and return the hashed password""" if (not password_to_encrypt): raise ErrorHandler.ErrorHandler(message="password cannot be empty", status_code=400) password_to_encrypt = password_to_encrypt.encode('utf-8') password_to_encrypt = bcrypt.hashpw(password_to_encrypt, bcrypt.gensalt(12)).decode('utf-8') return password_to_encrypt
def logException(): out = cStringIO.StringIO() ErrorHandler.logError(out) errorTags = [ frame.executable.dt._error_tag for frame in Component.componentStack if isinstance(frame.executable, Executables.STMLExecutable) if hasattr(frame.executable.dt, '_error_tag') ] if errorTags: out.write('Tag traceback (most recent tag last):\n') for tag in errorTags: if tag: out.write(' File "%s", line %s\n' % (tag._name, tag._lineno)) out.write(' %s\n' % tag.tag) else: out.write(' File ??, line??\n') x = out.getvalue() Logs.ERROR(x) return x
def parse(self, tokens): try: if type(tokens) is LexedItem: tokens = tokens.as_raw() self.reset() for tok in tokens: if tok.type not in ('SPACE'): self.tokens.append(tok) self.next_token() return ParsedItem(self.clean(self.expression())) except: if ErrorHandler.DEBUG: raise ErrorHandler.ParserError()
def open_file(): print("\nPlease select the XML file containing your class data.\n") gradebook_list = os.listdir(save_path) for gradebook in gradebook_list: if gradebook.__contains__('.xml'): print('\t>', gradebook.replace('.xml', ''), '\n') FILE_NAME = os.path.join(save_path, str(input("> ")) + '.xml') if ErrorHandler.is_file_type('xml', FILE_NAME): global FILE_NAME main_menu() else: print("\nInvalid file type. Please choose another.") open_file()
def view_menu(): end_prompt = "Press any key to continue" print("\nYou are using the file {!s}\n".format(FILE_NAME)) print("Choose an option by typing the number and pressing RETURN") print("\t[1] View class report.") print("\t[2] View student report.") print("\t[3] View class statistics.") print("\t[4] Back to main menu.") choice = input("> ") if choice == '1': ParseXML.print_all_grades(FILE_NAME) input(end_prompt) view_menu() elif choice == '2': print("List of students:\n") ParseXML.list_students(FILE_NAME) print("\nEnter the name of a student, then press RETURN.") name = input("> \n") if ErrorHandler.is_a_student(name, FILE_NAME): ParseXML.one_student_grades(FILE_NAME, name) input(end_prompt) view_menu() else: print("{!s} is not a student. Press RETURN to go back to" " menu.".format(name)) input("") view_menu() elif choice == '3': pass # TODO (CREATE STATISTICS) elif choice == '4': main_menu() else: print("Invalid selection.") view_menu()
# # config - pointer to current configuration object # yes, no, true, false - various boolean values ns_dict['config'] = self for y in ( 'yes', 'true', 'YES', 'TRUE', 'Yes', 'True' ): ns_dict[y] = 1 for n in ( 'no', 'false', 'NO', 'FALSE', 'No', 'False' ): ns_dict[n] = 0 ns = ns_dict.copy() try: exec code in ns except: trace = ErrorHandler.readError() raise SkunkStandardError, 'cannot parse config file %s :\n%s' % \ ( realfile, trace ) for k, v in ns.items(): if type(v) not in (types.ModuleType, types.FunctionType) and \ k not in [ '__builtins__' ] + ns_dict.keys() and k[0] != '_': # Check that it's not set on the command line if self.has_key(k) and self._dict[k].isSetCmdLine(): continue self[k] = v # Get rid of the _dir in path if we added it there if chdir and _dir: del sys.path[sys.path.index(_dir)]
class ASTTest(): def setUp(self): self.errorHandler = None def parseFile(self, filename): input_file = FileStream(filename) lexer = CLexer(input_file) stream = CommonTokenStream(lexer) parser = CParser(stream) programContext = parser.program() if parser._syntaxErrors > 0: raise Exception("error parsing file " + filename) walker = ParseTreeWalker() abstractSyntaxTree = AbstractSyntaxTree(); self.errorHandler = ErrorHandler(filename) listener = Listener(abstractSyntaxTree) walker.walk(listener, programContext) decorator = VisitorDecorator() decorator.visitProgramNode(abstractSyntaxTree.root) symbolTable = SymbolTable() functionFiller = VisitorSymbolTableFiller(symbolTable, self.errorHandler) functionFiller.visitProgramNode(abstractSyntaxTree.root) tableFiller = VisitorDeclarationProcessor(symbolTable, self.errorHandler) tableFiller.visitProgramNode(abstractSyntaxTree.root) typeCheck = VisitorTypeChecker(self.errorHandler) typeCheck.visitProgramNode(abstractSyntaxTree.root) if self.errorHandler.errorCount() == 0: pFilename = os.path.splitext(filename)[0] + ".p" codeGenerator = VisitorCodeGenerator(symbolTable, pFilename) codeGenerator.visitProgramNode(abstractSyntaxTree.root) def generateErrorsAndCompare(self, filename): self.parseFile(filename + ".c") self.assertTrue(self.errorHandler.errorCount() or self.errorHandler.warningCount()) # if there is error output generated, compare with txt file try: with open(filename + ".txt", "r") as myfile: correctOutputOriginal = myfile.read() except: with open(filename + ".txt", "w") as myfile: correctOutputOriginal = "" errorMessage = self.errorHandler.errorsToString() errorMessageWithWhitespace = copy.copy(errorMessage) # remove all whitespace errorMessage = re.sub("[ \t\n\r]", "", errorMessage) correctOutput = re.sub("[ \t\n\r]", "", correctOutputOriginal) # expectedOutputFound = errorMessage.find(correctOutput) != -1 expectedOutputFound = errorMessage == correctOutput if setTxtFiles and not expectedOutputFound: f = open(filename + ".txt", "w") f.write(errorMessageWithWhitespace) f.close() if not expectedOutputFound: print("\nEXPECTED:\n" + correctOutputOriginal + "\nGOT:\n" + errorMessageWithWhitespace + "\n\n\n\n") self.assertTrue(expectedOutputFound) def generateNoError(self, filename): self.parseFile(filename + ".c") self.assertTrue(self.errorHandler.errorCount() == 0) # open the newly generated p code file try: with open(filename + ".p", "r") as myfile: pCodeGeneratedOriginal = myfile.read() except: with open(filename + ".p", "w") as myfile: pCodeGeneratedOriginal = "" # open the file with the correct p code try: with open(filename + ".p_correct", "r") as myfile: pCodeCorrectOriginal = myfile.read() except: with open(filename + ".p_correct", "w") as myfile: pCodeCorrectOriginal = "" # remove all whitespace pCodeGenerated = re.sub("[ \t\n\r]", "", pCodeGeneratedOriginal) pCodeCorrect = re.sub("[ \t\n\r]", "", pCodeCorrectOriginal) # expectedOutputFound = errorMessage.find(correctOutput) != -1 expectedCodeFound = pCodeGenerated == pCodeCorrect if setPCode and not expectedCodeFound: f = open(filename + ".p_correct", "w") f.write(pCodeGeneratedOriginal) f.close() if not expectedCodeFound: print("\nEXPECTED:\n" + pCodeGeneratedOriginal + "\nGOT:\n" + pCodeCorrectOriginal + "\n\n\n\n") # os.system("gcc -std=c99 " + filename + ".c -w -o " + filename + ".testbin") self.assertTrue(expectedCodeFound)