def test_simple_undecorate(): decorated = decorate(f) assert decorated(None) == ('original', 'd') assert decorated(None, 3) == ('original', 'd') assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_warntimer_sets_thread_name(self): setup_cvar("roundtimelimit", "180") patch(time.sleep, lambda _int: None) undecorated(self.warner.warntimer)(self.warner) assert_that(self.warner.warner_thread_name, any_(str))
def test_warntimer_waits_until_30_seconds_before_roundtimelimit(self): setup_cvar("roundtimelimit", "180") patch(time.sleep, lambda _int: None) undecorated(self.warner.warntimer)(self.warner) verify(time).sleep(150)
def test_handle_round_end_winning_streak_triggers_teams_callback_already_called_multiple_times( self): mocked_balance_plugin = mock() mocked_balance_plugin.callback_teams = lambda: None Plugin._loaded_plugins["balance"] = mocked_balance_plugin # pylint: disable=protected-access setup_game_in_progress(game_type="ca", roundlimit=8, red_score=4, blue_score=3) red_player1 = fake_player(123, "Red Player1", "red") red_player2 = fake_player(456, "Red Player2", "red") blue_player1 = fake_player(246, "Blue Player1", "blue") blue_player2 = fake_player(975, "Blue Player2", "blue") connected_players(red_player1, red_player2, fake_player(42, "Spec Player", "spectator"), blue_player1, blue_player2) self.plugin.winning_teams = [ "blue", "blue", "blue", "red", "red", "red", "red" ] undecorated(self.plugin.handle_round_end)(self.plugin, { "TEAM_WON": "RED" }) players = { p.steam_id: "ca" for p in [red_player1, red_player2, blue_player1, blue_player2] } verify(mocked_balance_plugin, times=0).add_request(players, mocked_balance_plugin.callback_teams, minqlx.CHAT_CHANNEL)
def test_thrice_decorated(): decorated = decorate_with_params(2)( decorate( decorate_with_params(1)(f))) assert decorated(0, 0) == ('original', 1, 'd', 2) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_plays_sound_when_round_still_running(self): warner_thread_name = "test_plays_sound_when_round_still_running1" setup_game_in_progress(game_type="ca") self.warner.warner_thread_name = warner_thread_name undecorated(self.warner.play_thirty_second_warning)(self.warner, warner_thread_name) assert_plugin_played_sound(any_(str))
def test_plays_no_sound_when_next_round_started(self): calling_round_number = 4 setup_game_in_progress(game_type="ca") self.warner.timer_round_number = calling_round_number + 1 undecorated(self.warner.play_thirty_second_warning)( self.warner, calling_round_number) assert_plugin_played_sound(any_(str), times=0)
def test_params_to_decorator_are_functions(): def foo(): pass decorated = decorate_with_params(foo)(decorate_with_params(foo, foo)(f)) assert decorated(0) == ('original', foo, foo, foo) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_simple_method(): class A(object): def foo(self, a, b): return a, b decorated = decorate_with_params('dp')(decorate(A.foo)) assert decorated(A(), 1, 2) == (1, 2, 'd', 'dp') assert undecorated(decorated) == A.foo assert undecorated(decorated)(A(), 1, 2) == (1, 2)
def test_params_to_decorator_are_functions(): def foo(): pass decorated = decorate_with_params(foo)( decorate_with_params(foo, foo)(f)) assert decorated(0) == ('original', foo, foo, foo) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_decorator_without_wraps(): def lame_decorator(f): def decorator(*args, **kwargs): f(*args, **kwargs) return decorator decorated = lame_decorator(f) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_builtin(): # given a builtin decorated with a sample decorator decorated = decorate(tuple) # which changes its return value by appending a marker assert decorated() == tuple() + DECORATE_MARKER # when calling undecorated on the decorated builtin # then the returned function will be and behave like the original builtin assert undecorated(decorated) is tuple assert undecorated(decorated)() == tuple()
def test_simple_undecorate(): # given our original function f, decorated with a simple decorator decorated = decorate(f) # which appends a marker to the return value of our original function assert decorated(None) == f(None) + DECORATE_MARKER assert decorated(None, 3) == f(None, 3) + DECORATE_MARKER # when calling udnecorated on the decorated function # then the returned function will be and behave like the original # function f assert undecorated(decorated) is f assert undecorated(decorated)(None) == f(None)
def exec_command(commandString, logCriticalEnable=True, logAllEnable=False, logTimeEnable=False): fh = None if logAllEnable: logging.info("{}".format(commandString)) if logTimeEnable == False: out, err = undecorated(subProcessWrapper)(commandString, fh, False) else: out, err = subProcessWrapper(commandString, fh, False) # Combine std out and std err commandData = out + err if logAllEnable: logging.info("{}".format(commandData)) elif logCriticalEnable: # TODO: currently FW does not output these messages. Make FW do this: if ("Abort" in commandData) or ("ABORT_REQ" in commandData): logging.info("{}".format(commandString)) logging.info("{}".format(commandData)) # TODO: currently FW does not output these messages. Make FW do this: if "Interrupted system call" in str(commandData): raise Exception("NVME Host Command Timeout") return commandData
def test_with_params(): # given a sample function `f` decorated with some arbitrary params test_args = 'a' test_kwargs = {'kwarg1': 'b'} decorated = decorate_with_params(*test_args, **test_kwargs)(f) # which will change its return value (appending our arbitrary params) assert (decorated(1, 2) == f(1, 2) + (test_args, ) + tuple(test_kwargs.items())) # when we undecorate the function # then the returned function will be and behave like the original # function f assert undecorated(decorated) is f assert undecorated(decorated)(None) == f(None)
def reset_cached_api(request, apiurl): """ This admin call gets the url of the original api that we wish to reset, backwards resolves that original function and gets its data back into cache :param request: :param apiurl: :return: """ from undecorated import undecorated # from importlib import import_module try: match = resolve("/api/{}".format(apiurl)) #mod = import_module(".".join(match.view_name.split(".")[:-1])) Dont actually need this, resolve gets us the func itself #func = mod.__getattribute__(match.func.func_name) if "django_cache" in match.func.func_dict: api_view = undecorated(match.func) redecorated_api_view = scache.django_cache( action="reset")(api_view) redecorated_api_view(request, *match.args, **match.kwargs) return HttpResponseRedirect("/api/{}".format(apiurl)) else: raise Http404("API not in cache") except Resolver404 as re: logger.warn(u"Attempted to reset invalid url") raise Http404() except Exception as e: logger.warn(u"Unable to reset cache for {}".format(apiurl)) raise Http404()
def test_class_decorator(): def decorate(cls): def dec(): ins = cls() ins.decorated = True return ins return dec class A(object): decorated = False decorated = decorate(A) assert decorated().decorated is True assert undecorated(decorated) is A assert undecorated(decorated)().decorated is False
def reset_cached_api(request, apiurl): """ This admin call gets the url of the original api that we wish to reset, backwards resolves that original function and gets its data back into cache :param request: :param apiurl: :return: """ from undecorated import undecorated # from importlib import import_module try: match = resolve("/api/{}".format(apiurl)) #mod = import_module(".".join(match.view_name.split(".")[:-1])) Dont actually need this, resolve gets us the func itself #func = mod.__getattribute__(match.func.func_name) if "django_cache" in match.func.func_dict: api_view = undecorated(match.func) redecorated_api_view = scache.django_cache(action="reset")(api_view) redecorated_api_view(request, *match.args, **match.kwargs) return HttpResponseRedirect("/api/{}".format(apiurl)) else: raise Http404("API not in cache") except Resolver404 as re: logger.warn("Attempted to reset invalid url") raise Http404() except Exception as e: logger.warn("Unable to reset cache for {}".format(apiurl)) raise Http404()
def test_infinite_recursion(): def recursive_decorator(f): @wraps(f) def decorator(*args, **kwargs): decorator.foo() return f(*args, **kwargs) decorator.foo = lambda: None return decorator decorated = recursive_decorator(f) assert decorated(None) == ('original', ) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def _conduct_test_and_write_stats(cipher_obj: Cipher) -> bool: """ The cipher object to run encryption and then decryption. Write to a file detailing the statistics of encryption and decryption. :param cipher_obj: (_cipher.Cipher) The cipher object to encrypt and decrypt with :return: (bool) THe success or failure of the encryption and decryption """ # Setup for encrypting/decrypting with profiling lp = LineProfiler() # Set up the line-profiler object module_name = str(type(cipher_obj)).split(".")[ -2] # Get the name of the module that cipher_obj uses class_name = str(type(cipher_obj)).split(".")[-1][ 0:-2] # Get the class that cipher_obj is functions = eval("inspect.getmembers({}.{}, " "predicate=inspect.isfunction)".format( module_name, class_name)) functions = [item[0] for item in functions ][1:] # Only want names. Also, ignore first element (init) functions.remove("encrypt_plaintext") functions.remove("decrypt_ciphertext") functions.remove("write_statistics") # Add all function/method to profile lp.add_function(undecorated.undecorated(cipher_obj.encrypt_plaintext)) lp.add_function(undecorated.undecorated(cipher_obj.decrypt_ciphertext)) for function in functions: exec("lp.add_function(undecorated.undecorated({}.{}.{}))".format( module_name, class_name, function)) # Encrypt and decrypt. Also, profile TODO lp_wrapped = lp(cipher_obj.encrypt_plaintext) # Wrap encrypt_plaintext() lp_wrapped() lp_wrapped = lp(cipher_obj.decrypt_ciphertext) # Wrap decrypt_ciphertext() lp_wrapped() lp.print_stats() # Generate file name and write to that file containing the statistics of the encryption and decryption cipher_name = str(type(cipher_obj)) cipher_name = cipher_name[cipher_name.rfind(".") + 1:-2] stats_file_path = "Resources/Files_Logs/{}__{}"\ .format(cipher_name, datetime.datetime.now().strftime("%Y-%m-%d_%Hh%Mm%Ss")) cipher_obj.write_statistics(stats_file_path) # Return the correctness of the encryption and decryption return cipher_obj.original_plaintext == cipher_obj.plaintext
def test_closure(): # given a closure outer_scope_var = 'outer_scope_var' def closure(): return (outer_scope_var, ) # decorated with a sample decorator decorated = decorate(closure) # which changes its return value by appending a marker assert decorated() == closure() + DECORATE_MARKER # when calling undecorated on the decorated closure # then the returned function will be and behave like the original closure assert undecorated(decorated) is closure assert undecorated(decorated)() == closure()
def test_not_decorated(): # given a function which is not decorated def foo(self, a, b): return a, b # when calling undecorated on it # then the result will be the original function f assert undecorated(foo) is foo
def test_handle_round_end_suggestion_threshold_not_met(self): setup_game_in_progress(roundlimit=8, red_score=4, blue_score=3) return_code = undecorated(self.plugin.handle_round_end)( self.plugin, { "TEAM_WON": "RED" }) assert_that(return_code, is_(minqlx.RET_NONE))
def test_handle_round_end_no_game_running(self): setup_no_game() return_code = undecorated(self.plugin.handle_round_end)( self.plugin, { "TEAM_WON": "RED" }) assert_that(return_code, is_(minqlx.RET_NONE))
def test_func_closure(reason='favor no-wraps decorators; see undecorated.py'): # given a closure over a function def outer_scope_func(): pass def closure(): return (outer_scope_func, ) # decorated with a sample decorator decorated = decorate(closure) # which changes its return value by appending a marker assert decorated() == closure() + DECORATE_MARKER # when calling undecorated on the decorated closure # then the returned function will be and behave like the original closure assert undecorated(closure) is closure assert undecorated(closure)() == closure()
def test_driver(self): """ driver function should create method which allow to init any driver. """ query = MagicMock() result = driver(query) result = undecorated(result) assert result(dbsession=sentinel.dbsession) == query.return_value query.assert_called_once_with(sentinel.dbsession)
def test_handle_round_end_wrong_gametype(self): setup_game_in_progress(game_type="rr") return_code = undecorated(self.plugin.handle_round_end)( self.plugin, { "TEAM_WON": "RED" }) assert_that(return_code, is_(minqlx.RET_NONE))
def test_params_to_decorator_are_functions(): # given a sample function f, decorated with a decorator which # accepts functions as parameter def foo(): pass decorate_params = (foo, foo) decorated = decorate_with_params(*decorate_params)(f) # and which causes the decorated function to append the parameters # to the decorator to the return value of the decorated function assert decorated(0) == f(0) + (foo, foo) # when we undecorate the function # then the returned function will be and behave like the original # function f assert undecorated(decorated) is f assert undecorated(decorated)(None) == f(None)
def test_simple_method(): # given a sample class method A.foo class A(object): def foo(self, a, b): return a, b # which is decorated with our test decorator decorated = decorate(A.foo) # and which appends the parameters to the return value of its # decorated function assert decorated(A(), 1, 2) == A().foo(1, 2) + DECORATE_MARKER # when we undecorate the method # then the returned method will be the same and behave like the # original method assert undecorated(decorated) == A.foo assert undecorated(decorated)(A(), 1, 2) == (1, 2)
def test_in_not_color(self, mock_input): capturedOutput = io.StringIO() sys.stdout = capturedOutput color = mock_input() function = undecorated(colors_valid) result = function(color) sys.stdout = sys.__stdout__ self.assertEqual(capturedOutput.getvalue(), "Not a valid color and continue the loop.\n") self.assertTrue(result)
def test_exit_color(self, mock_input): capturedOutput = io.StringIO() sys.stdout = capturedOutput color = mock_input() color = mock_input() function = undecorated(colors_valid) result = function(color) sys.stdout = sys.__stdout__ self.assertEqual(capturedOutput.getvalue(), "bye\n") self.assertFalse(result)
def get_api_method(app, rule): """Return the original Flask-Classy method as the user first wrote it This means without any decorators applied. :app: a Flask app object :rule: a werkzeug.routing.Rule object """ return undecorated(app.view_functions[rule.endpoint])
def test_thrice_decorated(): # given a sample function f, decorated thrice: # with an decorator which takes 1 as a parameter decorated = decorate_with_params(1)(f) # with our normal test decorator decorated = decorate(decorated) # and with another decorator which takes 1 as a parameter decorated = decorate_with_params(2)(decorated) # this will append one element to the return value of f for each of # the decorators called assert decorated(0, 0) == f(0, 0) + (1, ) + DECORATE_MARKER + (2, ) # when we undecorate the function # then the returned function will be and behave like the original # function f assert undecorated(decorated) is f assert undecorated(decorated)(None) == f(None)
def test_decorator_without_wraps(): # given a sample function f, decorated with a decorator which does # not use the functools.wraps function def lame_decorator(f): def decorator(*args, **kwargs): return f(*args, **kwargs) + DECORATE_MARKER return decorator decorated = lame_decorator(f) # and which appends a marker to the return value of its decorated # function assert decorated(0) == f(0) + DECORATE_MARKER # when we undecorate the function # then the returned function will be and behave like the original # function f assert undecorated(decorated) is f assert undecorated(decorated)(None) == f(None)
def test_with_params(): decorated = decorate_with_params('a', kwarg1='b')(f) assert decorated(1, 2) == ('original', 'a', ('kwarg1', 'b')) assert undecorated(decorated) is f assert undecorated(decorated)(None) == ('original', )
def test_not_decorated(): def foo(self, a, b): return a, b assert undecorated(f) is f