def simple_require_condition(): """ This function demonstrates the simplest use of the require_condition function. This function can be used any time a state invariant needs to be asserted. Unlike the built-in assert keyword, require_condition will be in effect in both live and debug modes. """ print("Demonstrating simple require_condition example") Buzz.require_condition(True, 'This condition should always pass') Buzz.require_condition(False, 'This condition should always fail')
def test_nested_handler(self): """ This test verifies that a handler that is nested inside another buzz catching mechanism properly sanitizes the final error string so that format arguments in the outside mechanism don't get caught up in curly braces in the final error string """ with pytest.raises(Buzz) as err_info: with Buzz.handle_errors("outside handler"): with Buzz.handle_errors("inside handler"): raise Exception("this has {curlies}") assert 'this has {curlies}' in err_info.value.message
def complex_require_condition(): """ This function demonstrates a more complex usage of the require_condition function. It shows argument interpolation and handling a more complex boolean expression """ print("Demonstrating complex require_condition example") val = 64 Buzz.require_condition(is_even(val), 'This condition should pass') val = 81 Buzz.require_condition(is_even(val), 'Value {val} is not even', val=val)
def test_formatting(self): with pytest.raises(Buzz) as err_info: raise Buzz('fail message with no formatting') assert 'fail message with no formatting' in str(err_info.value) with pytest.raises(Buzz) as err_info: raise Buzz('fail message with {}', 'arg formatting') assert 'fail message with arg formatting' in str(err_info.value) with pytest.raises(Buzz) as err_info: raise Buzz('fail message with {fmt}', fmt='kwarg formatting') assert 'fail message with kwarg formatting' in str(err_info.value)
def test_handle_errors__with_do_finally(self): check_list = [] with Buzz.handle_errors( 'no errors should happen here, but do_finally should be called', do_finally=lambda: check_list.append(1)): pass assert check_list == [1] check_list = [] with pytest.raises(Buzz) as err_info: with Buzz.handle_errors('intercepted exception', do_finally=lambda: check_list.append(1)): raise Exception("there was a problem") assert 'there was a problem' in str(err_info.value) assert 'intercepted exception' in str(err_info.value) assert check_list == [1]
def test_handle_errors__with_do_else(self): check_list = [] with Buzz.handle_errors( 'no errors should happen here, but do_else should be called', do_else=lambda: check_list.append(1)): pass assert check_list == [1]
def test_handle_errors__basic_handling(self): with pytest.raises(Buzz) as err_info: with Buzz.handle_errors('intercepted exception'): raise ValueError("there was a problem") assert 'there was a problem' in str(err_info.value) assert 'intercepted exception' in str(err_info.value) assert 'ValueError' in str(err_info.value)
def arguments(argv): parser = argparse.ArgumentParser() mutexgroup = parser.add_mutually_exclusive_group() mutexgroup.add_argument('-i', '--init', action='store_true', default=False, help='Create a sample config file at ~/.config/dynpaper/config or specify your own location') mutexgroup.add_argument('-f', '--file', action='store') args = parser.parse_args(argv[1:]) Buzz.require_condition(any(args.__dict__.values()), 'No arguments provided.') args = load_args(args) return args
def test_handle_errors__without_reraise(self): check_list = [] with Buzz.handle_errors( 'intercepted exception', re_raise=False, do_except=lambda e, m, t: check_list.append(m), ): raise Exception("there was a problem") assert len(check_list) == 1 assert 'there was a problem' in check_list[0]
def test_handle_errors__with_specific_exception_class(self): class SpecialError(Exception): pass with pytest.raises(Exception) as err_info: with Buzz.handle_errors( 'there was a problem', exception_class=SpecialError, ): raise Exception("there was a problem") assert err_info.type == Exception with pytest.raises(Exception) as err_info: with Buzz.handle_errors( 'there was a problem', exception_class=SpecialError, ): raise SpecialError("there was a problem") assert err_info.type == Buzz
def make_foo(cls, **kwargs): if cls is Foo: foo_type_id = kwargs.pop('foo_type_id', None) entity_type = kwargs.pop('foo_type', None) Buzz.require_condition( ((foo_type is not None and foo_type_id is None) or (foo_type_id is not None and foo_type is None)), "Must have foo_type xor foo_type_id", ) target_class = cls.fetch_class_from_foo_type(foo_type_id or foo_type.id) return target_class(**kwargs) else: Buzz.require_condition( 'foo_type' not in props and 'foo_type_id' not in props, "May not have foo_type or foo_type_id", ) return super()(**kwargs)
def test_handle_errors__with_do_except(self): check_list = [] with Buzz.handle_errors( 'no errors should happen here, so do_except should not be called', do_except=lambda e, m, t: check_list.append(m), ): pass assert check_list == [] check_list = [] with pytest.raises(Buzz) as err_info: with Buzz.handle_errors( 'intercepted exception', do_except=lambda e, m, t: check_list.append(m), ): raise Exception("there was a problem") assert 'there was a problem' in str(err_info.value) assert 'intercepted exception' in str(err_info.value) assert len(check_list) == 1 assert 'there was a problem' in check_list[0]
def fetch_class_from_foo_type(cls, foo_type_id): foo_type_name = FooType.query.get(foo_type_id).name try: target_class = cls.__mapper__.polymorphic_map[foo_type_name].class_ except KeyError: raise Buzz( "No foo subclass found for foo_type_id({}) named: {}", foo_type_id, foo_type_name, ) return target_class
def load_args(args): if args.file: with open(os.path.expanduser(args.file), 'r') as fp: args = yaml.load(fp) try: args = validate_config(args) except Exception as e: errors = ['Configuration file is wrong, make sure:','\'Files\' element is a list of elements.','\'Template\' element is a dictionary/mapping.','The listed files exist.','Time value is in format HH:mm'] raise Exception('\n\t - '.join(errors)) return args elif args.init: if not os.path.exists(DEFAULT_PATH): os.makedirs(DEFAULT_PATH[:DEFAULT_PATH.rindex('config')]) with open(DEFAULT_PATH, 'w') as fp: yaml.dump(DEFAULT_CONFIG, fp, default_flow_style=False) raise Buzz( 'We have created a new file here: {DEFAULT_PATH}, please update it and run dynpaper again.', DEFAULT_PATH=DEFAULT_PATH) else: raise Buzz('Unknown message occured.')
def test_accumulate_errors(self): with pytest.raises(Buzz) as err_info: with Buzz.accumulate_errors('there will be errors') as checker: checker += True checker += False checker += 1 == 2 checker += 'cooooooool' checker += 0 err_msg = err_info.value.message assert 'there will be errors' in err_msg assert '`checker += True` resolved as false' not in err_msg assert '`checker += False` resolved as false' in err_msg assert '`checker += 1 == 2` resolved as false' in err_msg assert '`checker += \'cooooooool\' resolved as false' not in err_msg assert '`checker += 0` resolved as false' in err_msg
#!/usr/bin/env python import cgitb cgitb.enable() from buzz import Buzz import time import traceback, sys, os buzz = Buzz() #buzz.startBlink(15, 0.5) buzz.setLights(15) def printResult(result): print("Content-Type: text/json") print(""" %s """ % result) buzz.readController(timeout=5000) printResult(buzz.getButtons())
def check_number(n): with Buzz.check_expressions( main_message="Some checks failed for {}".format(n)) as check: check(is_int(n), "number must be even") check(is_power_of_2(n), "number must be a power of 2") check(is_prime(n), "number must be prime")
def test_handle_errors__error_formatting_message(self): with pytest.raises(Buzz) as err_info: with Buzz.handle_errors('{format_arg1}', format_arg2='foo'): raise ValueError("there was a problem") assert err_info.type == Buzz assert 'Failed while formatting message' in str(err_info.value)
from buzz import Buzz from pynput.keyboard import Key, Controller import time import traceback, sys, os buzz = Buzz() #buzz.startBlink(15, 0.5) buzz.setLights(1) keyboard = Controller() while True: r = buzz.readController(timeout=500) if r != None: if buzz.getButtons()[0]['red'] == True: keyboard.press('a') keyboard.release('a') elif buzz.getButtons()[0]['blue'] == True: keyboard.press('b') keyboard.release('b') elif buzz.getButtons()[0]['orange'] == True: keyboard.press('c') keyboard.release('c') elif buzz.getButtons()[0]['green'] == True: keyboard.press('d') keyboard.release('d') elif buzz.getButtons()[0]['yellow'] == True: keyboard.press('e') keyboard.release('e')
def check_number(n): with Buzz.accumulate_errors("Some checks failed for {}", n) as acc: acc += is_int(n) acc += is_even(n) acc += is_power_of_2(n) acc += is_prime(n)
def test_require_condition(self): Buzz.require_condition(True, 'should not fail') with pytest.raises(Buzz) as err_info: Buzz.require_condition(False, 'fail message with {}', 'formatting') assert 'fail message with formatting' in str(err_info.value)
def test_handle_errors__no_exceptions(self): with Buzz.handle_errors('no errors should happen here'): pass