How to use test_logs method in localstack

Best Python code snippet using localstack_python

unit6_lesson_02_understanding_decorators.py

Source:unit6_lesson_02_understanding_decorators.py Github

copy

Full Screen

1__author__ = 'Kalyan'23notes = '''4 Decorators are higher order functions that add behavior to other functions. Python provides a simple syntax that makes5 it easy to use decorators on existing functions. This makes it easy to define higher order behaviors that can applied6 to other functions without repeating the same behavior in every function.78 To get an idea of how python folks introduces language features and spec them out read the PEP:9 http://legacy.python.org/dev/peps/pep-0318/1011 Review all the previous function lessons including nested functions if required and remember that12 functions are first class objects in python!13'''1415from placeholders import *1617# This is a function that adds enter log to another function by wrapping18# the func call with additional log behavior.19def log(func):20 # the inner function has access to outer func locals and they are bound at definition21 # time via a closure.22 def inner():23 print(("Entering func", func.__name__))24 return func()25 return inner # returns a new func.2627# This is how you would do it, without any help from python.28def test_decorators_old_way():29 # A dummy method for testing.30 def get_hello():31 return "hello"3233 assert __ == get_hello.__name__34 assert __ == get_hello()3536 # Check that there is no log statement from the above invocation to get_hello in the pytest output and then37 # remove the assert. Logs are not shown for passing tests to reduce output verbosity.38 assert False3940 # now we are creating a new version of get_hello by invoking log.41 # now get_hello is bound to a new function returned by log!42 get_hello = log(get_hello)4344 #while the variable name is get_hello, the actual function is something else now!45 assert __ == get_hello.__name__46 # the result is same47 assert __ == get_hello()4849 # check the pytest output now and remove the assert after that. Search for "Captured stdout call"...50 assert False5152 # we can use the same log method to decorate any number of functions53 # Thus promoting reusable behavior that can be applied to any function5455 # Another dummy method for testing.56 def get_bye():57 return "bye"5859 assert __ == get_bye.__name__60 assert __ == get_bye()6162 # Note that we could have held the return value in a new name.63 # By binding it to the original function name, we augment the functionality for the users64 # of get_hello or get_bye.65 dummy = log(get_bye)6667 #nothing changes so far.68 assert __ == get_bye.__name__69 assert __ == get_bye()7071 #if we rebind get_bye then stuff changes and we get logging behavior72 get_bye = dummy # same as get_bye = log(get_bye)73 assert __ == get_bye.__name__74 assert __ == get_bye()7576 # remove after verifying that get_bye is now logging.77 assert False787980def test_decorators_syntax():81 # Note this new syntax which does exactly what we did in previous test.82 # (ie) invocation of log with get_hello and reassigning the result func to get_hello83 @log84 def get_hello():85 return "hello"8687 assert __ == get_hello.__name__88 assert __ == get_hello()8990 # check pytest output and then remove the assert.91 assert False;9293def test_decorators_promote_reuse():9495 def get_hello():96 return "hello"9798 def get_bye():99 return "hello"100101 def get_sorry():102 return "sorry"103104 # decorate all those 3 methods with log behavior. Note that we have augmented functionality of all functions105 # with the same decorator.106 assert "inner" == get_hello.__name__107 assert "inner" == get_bye.__name__108 assert "inner" == get_sorry.__name__109110 #while they have same name, they are not the same method (why?)111 get_hello()112 get_bye()113 get_sorry()114115 # check log output to see different log statements from each and then remove assert!116 assert False117118119def test_decorators_func_arguments():120 # to make testing easy we are going to append logs to this list instead of printing them!121 test_logs = []122 # how can we write decorators for functions which take arguments?123 # what do we do when we don't know arguments before hand?124 def log(func):125 def inner(__):126 # keeping log_stmt simple for testing, we can print argument values etc.127 # to make it useful for real.128 log_stmt = "Entered: " + func.__name__129 test_logs.append(log_stmt)130 return func(__)131132 return inner133134 # Note that we want to apply the same decorator to many functions135 @log136 def add(a, b):137 return a + b138139 @log140 def sub(a, b):141 return a - b142143 @log144 def increment(a):145 return a+1146147 test_logs = []148 assert __ == add(10, 20)149 assert [__] == test_logs150151 test_logs = []152 assert __ == sub(30, 25)153 assert [__] == test_logs154155 test_logs = []156 assert ___ == increment(12)157 assert [__] == test_logs158159160def test_decorator_chaining():161 def pass_through1(func):162 def inner1():163 test_logs.append("pt1")164 return func()165 return inner1166167 def pass_through2(func):168 def inner2():169 test_logs.append("pt2")170 return func()171 return inner2172173 @pass_through1174 @pass_through2175 def add(a,b):176 return a + b177178 test_logs = []179 assert __ == add(10,20)180 assert __ == add.__name__181 assert [__] == test_logs182183 # reverse order of decorators, what happens?184 @pass_through2185 @pass_through1186 def increment(a):187 return a+1188189 test_logs = []190 assert __ == increment(10)191 assert __ == increment.__name__192 assert [__] == test_logs193194def test_decorators_arguments():195 # Some times we want to parameterize the decorators. In that case196 # you write a decorator generator that is then applied on the function!197198 # Write a decorator generator which can be used to decorate test methods so that199 # they run only if a particular environment variable is defined, else they are skipped.200 # This sort of functionality is common in any testing framework to run certain tests on certain platforms only201202 import os203 # Define this decorator generator to work for arbitrary environment variables, see the usage to see how it is used204 def runif(variable):205 pass206207 # run this only if MY_LINUX env variable is present208 @runif("MY_LINUX")209 def linux_test():210 test_logs.append("linux_test called!")211212 # run this only if MY_WINDOWS env variable is present213 @runif("MY_WINDOWS")214 def windows_test():215 test_logs.append("windows_test called!")216217 # if you have defined runif correctly, these tests should pass.218219 test_logs = []220 # first no variables are defined.221 linux_test()222 windows_test()223 assert [] == test_logs224225 os.environ["MY_LINUX"] = "1"226 test_logs = []227 linux_test()228 windows_test()229 assert ["linux_test called!"] == test_logs230231 os.environ["MY_WINDOWS"] = "1"232 test_logs =[]233 linux_test()234 windows_test()235 assert ["linux_test called!", "windows_test called!"] == test_logs236237def test_decorators_wraps():238 # NOTE: some of these decorators have common bugs, fix them as you go along :-)239240 def pass_through1(func):241 def inner(*args, **kwargs):242 func(*args, **kwargs)243 return inner244245 @pass_through1246 def add(a, b):247 "adds 2 numbers"248 return a + b249250 # Note that we have lost useful information like documentation and name, which are used by251 # code inspection tools and help generators.252 assert __ == add.__name__253 assert __ == add.__doc__254 assert __ == add(10,20) # execution works fine255256 # preserving these is a common usecase. We can modify our decorators to preserves these.257 # modify this decorator to preserve func_name and func_doc by copying them over to the wrapper function.258 def pass_through2(func):259 def inner(*args, **kwargs):260 func(*args, **kwargs)261 return inner262263 @pass_through2264 def sub(a, b):265 "subtracts 2 numbers"266 return a - b267268 # these should have actual values now!269 assert __ == sub.__name__270 assert __ == sub.__doc__271 assert __ == sub(20, 10)272273 # since this behavior is commonly required. python gives an out of box feature to preserve these and274 # other function attributes. See https://docs.python.org/2/library/functools.html#functools.wraps275 import functools276 def pass_through3(func):277 @functools.wraps(func)278 def inner(*args, **kwargs):279 func(*args, **kwargs)280 return inner281282 @pass_through3283 def mult(a,b):284 return a*b285286 assert __ == mult.__name__287 assert __ == mult.__doc__288 assert __ == mult(10,20)289290# As a final exercise try to create your own version of wraps decorator generator that preserves just these291# 2 attributes and see if you understood the whole thing :)!292def test_decorators_custom_wrap():293 # This is your own implementation of wraps.294 def wraps(__):295 pass296297 # fix any bugs in the decorator just like before298 def pass_through(func):299 @wraps(__)300 def inner(*args, **kwargs):301 func(*args, **kwargs)302 return inner303304 @pass_through305 def add(a, b):306 'adds 2 numbers'307 return a + b308309 assert 'add' == add.__name__310 assert 'adds 2 numbers' == add.__doc__311 assert 30 == add(10, 20)312313314three_things_i_learnt = """315-316-317- ...

Full Screen

Full Screen

test_utilslogger.py

Source:test_utilslogger.py Github

copy

Full Screen

1import unittest2import os3import glob4import json5import yaml6from unittest.mock import patch, mock_open, builtins7from outfit import Outfit 8from outfit import Logger9from outfit import merge_dict10from consul import Consul11from outfit.hashicorp.consul_config import ConsulCon12from outfit.utils.io import convert_yaml13from .assets.logging_b import logging_b14from .assets.logging import logging15class TestLogger(unittest.TestCase):16 def setUp(self):17 if not os.path.exists('tests/test_logs'):18 os.mkdir('tests/test_logs')19 curr_dir = os.path.dirname(__file__)20 file_path = 'assets/logging.yaml'21 # get the yaml file22 with open(os.path.join(curr_dir,file_path), 'r') as stream:23 try:24 self.normal_content = yaml.safe_load(stream)25 except yaml.YAMLError as err:26 Logger.error('error load yaml file ' + str(err))27 28 def test_setup_log_json(self):29 self.delete_all_log_files()30 Outfit.setup('./tests/assets/config-log-json.yaml')31 Logger.info('test_info')32 with open('tests/test_logs/info.log', 'r') as finfo:33 temp_info = finfo.readlines()34 last_line = temp_info[len(temp_info) - 1]35 self.assertTrue('test_info' in last_line)36 Logger.debug('test_debug')37 with open('tests/test_logs/debug.log', 'r') as fdebug:38 temp_debug = fdebug.readlines()39 last_line = temp_debug[len(temp_debug) - 1]40 self.assertTrue('test_debug' in last_line)41 Logger.error('test_error')42 with open('tests/test_logs/errors.log', 'r') as ferrors:43 temp_errors = ferrors.readlines()44 last_line = temp_errors[len(temp_errors) - 1]45 self.assertTrue('test_error' in last_line)46 Logger.critical('test_critical')47 with open('tests/test_logs/errors.log', 'r') as fcritical:48 temp_critical = fcritical.readlines()49 last_line = temp_critical[len(temp_critical) - 1]50 self.assertTrue('test_critical' in last_line)51 def test_setup_log_yaml(self):52 self.delete_all_log_files()53 Outfit.setup('./tests/assets/config.yaml')54 Logger.info('test_info')55 with open('tests/test_logs/info.log', 'r') as finfo:56 temp_info = finfo.readlines()57 last_line = temp_info[len(temp_info) - 1]58 self.assertTrue('test_info' in last_line)59 Logger.debug('test_debug')60 with open('tests/test_logs/debug.log', 'r') as fdebug:61 temp_debug = fdebug.readlines()62 last_line = temp_debug[len(temp_debug) - 1]63 self.assertTrue('test_debug' in last_line)64 Logger.error('test_error')65 with open('tests/test_logs/errors.log', 'r') as ferrors:66 temp_errors = ferrors.readlines()67 last_line = temp_errors[len(temp_errors) - 1]68 self.assertTrue('test_error' in last_line)69 Logger.critical('test_critical')70 with open('tests/test_logs/errors.log', 'r') as fcritical:71 temp_critical = fcritical.readlines()72 last_line = temp_critical[len(temp_critical) - 1]73 self.assertTrue('test_critical' in last_line)74 75 def test_setup_log_py(self):76 self.delete_all_log_files()77 Outfit.setup('./tests/assets/config-log-py.yaml')78 Logger.info('test_info')79 with open('tests/test_logs/info.log', 'r') as finfo:80 temp_info = finfo.readlines()81 last_line = temp_info[len(temp_info) - 1]82 self.assertTrue('test_info' in last_line)83 Logger.debug('test_debug')84 with open('tests/test_logs/debug.log', 'r') as fdebug:85 temp_debug = fdebug.readlines()86 last_line = temp_debug[len(temp_debug) - 1]87 self.assertTrue('test_debug' in last_line)88 Logger.error('test_error')89 with open('tests/test_logs/errors.log', 'r') as ferrors:90 temp_errors = ferrors.readlines()91 last_line = temp_errors[len(temp_errors) - 1]92 self.assertTrue('test_error' in last_line)93 Logger.critical('test_critical')94 with open('tests/test_logs/errors.log', 'r') as fcritical:95 temp_critical = fcritical.readlines()96 last_line = temp_critical[len(temp_critical) - 1]97 self.assertTrue('test_critical' in last_line)98 99 @patch.object(ConsulCon, 'get_kv')100 def test_setup_log_consulkv(self, mock_kv):101 self.delete_all_log_files()102 103 from outfit.utils.io import load_yaml104 mock_kv.return_value = logging105 #result = convert_yaml(self.normal_content)106 Outfit.setup('./tests/assets/config-log-kv.yaml')107 108 m = minfo = mock_open(read_data='INFO:test_utilslogger.py(50)> test_info')109 mdebug = mock_open(read_data = 'ERROR:test_utilslogger.py(62)> test_debug')110 merror = mock_open(read_data = 'ERROR:test_utilslogger.py(62)> test_error')111 mcritical = mock_open(read_data = 'ERROR:test_utilslogger.py(62)> test_critical')112 m.side_effect = [minfo.return_value, mdebug.return_value, merror.return_value, mcritical.return_value]113 with patch('builtins.open', m):114 115 Logger.info('test_info')116 with open('tests/test_logs/info.log', 'r') as finfo:117 temp_info = finfo.read()118 last_line = temp_info[len(temp_info) - 1]119 self.assertTrue('test_info' in temp_info)120 Logger.debug('test_debug')121 with open('tests/test_logs/debug.log', 'r') as fdebug:122 temp_debug = fdebug.readlines()123 last_line = temp_debug[len(temp_debug) - 1]124 self.assertTrue('test_debug' in last_line)125 Logger.error('test_error')126 with open('tests/test_logs/errors.log', 'r') as ferrors:127 temp_errors = ferrors.readlines()128 last_line = temp_errors[len(temp_errors) - 1]129 self.assertTrue('test_error' in last_line)130 Logger.critical('test_critical')131 with open('tests/test_logs/errors.log', 'r') as fcritical:132 temp_critical = fcritical.readlines()133 last_line = temp_critical[len(temp_critical) - 1]134 self.assertTrue('test_critical' in last_line)135 @patch.object(ConsulCon, 'get_kv')136 def test_setup_log_consulkv_failed(self, mock_kv):137 self.delete_all_log_files()138 139 from outfit.utils.io import load_yaml140 mock_kv.return_value = logging141 Outfit.setup('./tests/assets/config-log-kv.yaml')142 143 Logger.info('test_info')144 with open('tests/test_logs/info.log', 'r') as finfo:145 temp_info = finfo.readlines()146 print(temp_info)147 print(len(temp_info))148 last_line = temp_info[len(temp_info) - 1]149 self.assertTrue('test_info' in last_line)150 Logger.debug('test_debug')151 with open('tests/test_logs/debug.log', 'r') as fdebug:152 temp_debug = fdebug.readlines()153 last_line = temp_debug[len(temp_debug) - 1]154 self.assertTrue('test_debug' in last_line)155 Logger.error('test_error')156 with open('tests/test_logs/errors.log', 'r') as ferrors:157 temp_errors = ferrors.readlines()158 last_line = temp_errors[len(temp_errors) - 1]159 self.assertTrue('test_error' in last_line)160 Logger.critical('test_critical')161 with open('tests/test_logs/errors.log', 'r') as fcritical:162 temp_critical = fcritical.readlines()163 last_line = temp_critical[len(temp_critical) - 1]164 self.assertTrue('test_critical' in last_line)165 def delete_all_log_files(self):166 filelist = glob.glob(os.path.join('tests/test_logs', '*'))167 for f in filelist:168 os.remove(f) 169if __name__ == '__main__':...

Full Screen

Full Screen

test_logs.py

Source:test_logs.py Github

copy

Full Screen

1import os2import json3import pytest4from panini.test_client import TestClient, get_logger_files_path5from panini import app as panini_app6testing_logs_directory_path = get_logger_files_path(7 "test_logger_logs", remove_if_exist=True8)9def run_panini():10 app = panini_app.App(11 service_name="test_logs",12 host="127.0.0.1",13 port=4222,14 logger_required=True,15 logger_in_separate_process=False,16 )17 log = app.logger18 @app.listen("test_logs.foo")19 async def subject_for_requests(msg):20 log.info(f"Got subject: {msg.subject}", message=msg.data)21 return {"success": True}22 @app.listen("test_logs.foo.*.bar")23 async def composite_subject_for_requests(msg):24 log.error(f"Got subject: {msg.subject}", message=msg.data)25 return {"success": True}26 app.start()27@pytest.fixture(scope="module")28def client():29 client = TestClient(run_panini, logger_files_path=testing_logs_directory_path)30 client.start()31 yield client32 client.stop()33def test_simple_log(client):34 response = client.request("test_logs.foo", {"data": 1})35 assert response["success"] is True36 with open(os.path.join(testing_logs_directory_path, "test_logs.log"), "r") as f:37 data = json.loads(f.read())38 assert data["name"] == "test_logs"39 assert data["levelname"] == "INFO"40 assert data["message"] == "Got subject: test_logs.foo"41 assert data["extra"]["message"]["data"] == 142def test_listen_composite_subject_with_response(client):43 subject = "test_logs.foo.some.bar"44 response = client.request(subject, {"data": 2})45 assert response["success"] is True46 with open(os.path.join(testing_logs_directory_path, "errors.log"), "r") as f:47 for last_line in f:48 pass49 data = json.loads(last_line)50 assert data["name"] == "test_logs"51 assert data["levelname"] == "ERROR"52 assert data["message"] == f"Got subject: {subject}"...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful