How to use setup_logging method in Testify

Best Python code snippet using Testify_python

test_plaintext_logging.py

Source:test_plaintext_logging.py Github

copy

Full Screen

...15def _readout_log(capsys):16 (out, _) = capsys.readouterr()17 return out18def test_should_log_something(capsys):19 setup_logging(stream=sys.stdout, plaintext=True)20 logging.info("something happened")21 log = _readout_log(capsys)22 assert "--- Logging error ---" not in log23 assert "something happened" in log24 assert "INFO" in log25 assert "process=" in log26 assert "thread=" in log27 assert re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}', log), "Missing or malformed timestamp"28def test_should_log_context(capsys):29 setup_logging(stream=sys.stdout, plaintext=True)30 with LogContext(trace_id=123):31 logging.info("something happened")32 log = _readout_log(capsys)33 assert "--- Logging error ---" not in log34 assert "something happened" in log35 assert "INFO" in log36 assert " [trace_id=123]" in log37def test_should_only_optionally_log_context(capsys):38 setup_logging(stream=sys.stdout, plaintext=True)39 logging.info("something happened")40 log = _readout_log(capsys)41 assert "--- Logging error ---" not in log42 assert "something happened" in log43 assert " [" not in log44def test_context_should_not_overwrite_existing_records(capsys):45 setup_logging(stream=sys.stdout, plaintext=True)46 with LogContext(created=123):47 logging.info("something happened")48 log = _readout_log(capsys)49 assert "--- Logging error ---" not in log50 assert "something happened" in log51 assert "created=123" not in log52def test_should_log_errors(capsys):53 setup_logging(stream=sys.stdout, plaintext=True)54 logging.error("error error!")55 log = _readout_log(capsys)56 assert "--- Logging error ---" not in log57 assert "error error!" in log58 assert "ERROR" in log59def test_should_log_exceptions(capsys):60 setup_logging(stream=sys.stdout, plaintext=True)61 # noinspection PyBroadException62 try:63 raise Exception("something horribly went wrong")64 except Exception:65 logging.exception("some error message")66 log = _readout_log(capsys)67 assert "--- Logging error ---" not in log68 assert "some error message" in log69 assert "Traceback (most recent call last):" in log70 assert 'raise Exception("something horribly went wrong")' in log71 assert "test_plaintext_logging.py" in log72def test_should_not_log_below_log_level(capsys):73 setup_logging(stream=sys.stdout, min_level=logging.WARNING, plaintext=True)74 logging.info("this should not be logged")75 logging.warning("warning should be logged")76 log = _readout_log(capsys)77 assert "--- Logging error ---" not in log78 assert "warning should be logged" in log79 assert "test_plaintext_logging.py" in log80 assert "WARNING" in log81 assert "INFO" not in log82 assert "this should not be logged" not in log83def test_should_handle_nested_context(capsys):84 setup_logging(stream=sys.stdout, plaintext=True)85 with LogContext(trace_id=123, foo="bar"):86 with LogContext(trace_id=42):87 logging.info("Something nested happened!")88 log = _readout_log(capsys)89 assert "--- Logging error ---" not in log90 assert "Something nested happened!" in log91 assert "trace_id=42" in log92 assert 'foo="bar"' in log93 assert "INFO" in log94@pytest.mark.asyncio95async def test_should_handle_async_context(capsys):96 setup_logging(stream=sys.stdout, plaintext=True)97 async def busywork(n):98 await asyncio.sleep(0.01)99 return n + 1100 async with LogContext(trace_id=123):101 result = await busywork(0) + await busywork(121)102 async with LogContext(result=result):103 logging.info("Hei!")104 log = _readout_log(capsys)105 assert "--- Logging error ---" not in log106 assert "Hei!" in log107 assert "result=123" in log108 assert "INFO" in log109def test_should_handle_multiple_threads_with_contexts(capsys):110 # This test runs a child thread with a log context while111 # (hopefully, depending on timing)112 # a parent thread is also using a log context to make sure that113 # thread-local variables actually work the way I think.114 # Also note that for some reason that isn't entirely clear to115 # me, this test doesn't run with output to std.stderr. (It116 # probably works fine in non-testing situations!)117 setup_logging(stream=sys.stdout, plaintext=True)118 def worker():119 with LogContext(tid="child"):120 logging.info("Hi from child!")121 time.sleep(0.03)122 t = threading.Thread(target=worker)123 t.start()124 time.sleep(0.01)125 with LogContext(tid="parent"):126 logging.info("Hi from parent!")127 t.join()128 (log, _) = capsys.readouterr()129 [child, parent] = log.split('\n')[0:2]130 assert 'tid="child"' in child131 assert "Hi from child!" in child132 assert 'tid="parent"' in parent133 assert "Hi from parent!" in parent134 child_tid = re.search(r'thread=(\d+)', child).group(1)135 parent_tid = re.search(r'thread=(\d+)', parent).group(1)136 assert child_tid != parent_tid137 assert "INFO" in child138 assert "INFO" in parent139 assert "--- Logging error ---" not in child140 assert "--- Logging error ---" not in parent141def test_should_handle_extra_parameters(capsys):142 setup_logging(stream=sys.stdout, plaintext=True)143 logging.info("Something extra happened!", extra={'xyzzy': 'qwerty'})144 log = _readout_log(capsys)145 assert "--- Logging error ---" not in log146 assert 'Something extra happened!' in log147 assert 'xyzzy="qwerty"' in log148def test_extra_parameters_should_override(capsys):149 setup_logging(stream=sys.stdout, plaintext=True)150 with LogContext(trace_id=123, foo='bar'):151 logging.info("Something extra happened!", extra={'foo': 'quux'})152 log = _readout_log(capsys)153 assert "--- Logging error ---" not in log154 assert 'Something extra happened!' in log155 assert 'trace_id=123' in log156 assert 'foo="quux"' in log157def test_should_work_with_nonroot_logger(capsys):158 setup_logging(stream=sys.stdout, plaintext=True)159 logger = logging.getLogger("nonroot")160 with LogContext(trace_id=123):161 logger.info("I'm not the root logger.")162 log = _readout_log(capsys)163 assert "--- Logging error ---" not in log164 assert "I'm not the root logger." in log165 assert "[trace_id=123]" in log166def test_should_read_environment_config(capsys, monkeypatch):167 monkeypatch.setenv('NIVACLOUD_PLAINTEXT_LOGS', '1')168 setup_logging(stream=sys.stdout)169 with LogContext(plaintexty="yes"):170 logging.info("Environment blah blah.")171 log = _readout_log(capsys)172 assert "--- Logging error ---" not in log173 assert "Environment blah blah." in log174 assert '[plaintexty="yes"]' in log175def test_should_override_propagation(capsys):176 logger = logging.getLogger('foo')177 logger.propagate = False178 setup_logging(override=True, plaintext=True, stream=sys.stdout)179 logger.info('Hei')180 log = _readout_log(capsys)181 assert "--- Logging error ---" not in log182 assert 'Hei' in log183def test_should_not_log_on_non_override(capsys):184 logger = logging.getLogger('foo')185 logger.propagate = False186 setup_logging(override=False, plaintext=True, stream=sys.stdout)187 logger.info('Hei')188 log = _readout_log(capsys)189 assert "--- Logging error ---" not in log190 assert 'Hei' not in log191def test_should_handle_multiple_setup_calls(capsys):192 setup_logging(plaintext=True, stream=sys.stdout)193 setup_logging(plaintext=True, stream=sys.stdout)194 logging.info('Once only!')195 log: str = _readout_log(capsys)196 assert "--- Logging error ---" not in log197 assert log.count('Once only!') == 1198def test_auto_context_should_only_add_requested_context(capsys):199 # noinspection PyUnusedLocal200 @auto_context("host", "user")201 def login(host, user, password):202 logging.info("Logging in")203 setup_logging(plaintext=True, stream=sys.stdout)204 login("ftp.example.com", "jane", "supersekrit")205 log = _readout_log(capsys)206 assert "--- Logging error ---" not in log207 assert 'host="ftp.example.com"' in log208 assert 'user="jane"' in log209 assert "supersekrit" not in log210def test_auto_context_should_log_all_parameters_by_default(capsys):211 # noinspection PyUnusedLocal212 @auto_context()213 def lookup(host, *servers):214 logging.info("Doing lookup...")215 setup_logging(plaintext=True, stream=sys.stdout)216 lookup("ftp.example.com", "1.1.1.1", "8.8.8.8")217 log = _readout_log(capsys)218 assert "--- Logging error ---" not in log219 assert 'host="ftp.example.com"' in log220 assert 'servers=["1.1.1.1", "8.8.8.8"]' in log221def test_auto_context_on_instance_methods(capsys):222 class MyClass:223 # noinspection PyUnusedLocal224 @auto_context()225 def my_method(self, a):226 logging.info("Hi!")227 setup_logging(plaintext=True, stream=sys.stdout)228 c = MyClass()229 c.my_method(42)230 log = _readout_log(capsys)231 assert "--- Logging error ---" not in log232 assert "a=42" in log233def test_should_handle_complex_context_data(capsys):234 setup_logging(plaintext=True, stream=sys.stdout)235 class Sample:236 pass237 thing = {238 'my_id': UUID('7118ad7e-6e26-483a-a120-7ec176331354'),239 'time': datetime(2019, 12, 24, 12, 34, 56, 0),240 'tupled': ("foo", {'complex': complex(12, 45)}, 1, 1.2, -4, 1.4e-10),241 'class': Sample,242 'instance': Sample(),243 'nan': math.nan,244 }245 with LogContext(thing=thing):246 logging.info("Hi, I have bunch of stuff.")247 log = _readout_log(capsys)248 assert "--- Logging error ---" not in log249 assert '"my_id": "7118ad7e-6e26-483a-a120-7ec176331354"' in log250 assert '"time": "2019-12-24T12:34:56"' in log251 assert '"tupled": ["foo", {"complex": {"imag": 45.0, "real": 12.0}}' in log252 assert '"nan": NaN' in log253def test_sigusr1_should_set_info_logging(capsys):254 setup_logging(min_level=logging.ERROR, plaintext=True, stream=sys.stdout)255 logging.info("Not logged")256 os.kill(os.getpid(), signal.SIGUSR1)257 logging.info("This is logged")258 log = _readout_log(capsys)259 assert "--- Logging error ---" not in log260 assert log.count('\n') == 1, "Expecting single line of logging output"261 assert "This is logged" in log262 assert "Not logged" not in log263def test_sigusr2_should_set_debug_logging(capsys):264 setup_logging(min_level=logging.INFO, plaintext=True, stream=sys.stdout)265 logging.debug("Not logged")266 os.kill(os.getpid(), signal.SIGUSR2)267 logging.debug("THIS is logged")268 log = _readout_log(capsys)269 assert "--- Logging error ---" not in log270 assert log.count('\n') == 1, "Expecting single line of logging output"271 assert "THIS is logged" in log272 assert "Not logged" not in log273def test_signal_handler_override_should_call_previous_handlers(capsys):274 myhandler_run_count = 0275 def myhandler(_s, _f):276 nonlocal myhandler_run_count277 myhandler_run_count += 1278 signal.signal(signal.SIGUSR2, myhandler)279 os.kill(os.getpid(), signal.SIGUSR2)280 setup_logging(min_level=logging.INFO, plaintext=True, stream=sys.stdout)281 os.kill(os.getpid(), signal.SIGUSR2)282 logging.debug("Debugged!")283 log = _readout_log(capsys)284 assert "--- Logging error ---" not in log285 assert 'Debugged!' in log286 assert log.count('\n') == 1, "Expecting single line of logging output"287 assert myhandler_run_count == 2288def test_should_add_commit_it_from_environment(capsys, monkeypatch):289 monkeypatch.setenv('GIT_COMMIT_ID', 'd22b929')290 setup_logging(plaintext=True, stream=sys.stdout)291 logging.info('Something committed')292 log = _readout_log(capsys)293 assert "--- Logging error ---" not in log294 assert "Something committed" in log295 assert '[git_commit_id="d22b929"]' in log296def test_should_add_commit_it_from_environment_to_all_threads(capsys, monkeypatch):297 monkeypatch.setenv('GIT_COMMIT_ID', 'deadbeef')298 setup_logging(stream=sys.stdout, plaintext=True)299 def worker():300 with LogContext(tid="child"):301 logging.info("Hi from child!")302 time.sleep(0.02)303 t = threading.Thread(target=worker)304 t.start()305 time.sleep(0.01)306 with LogContext(tid="parent"):307 logging.info("Hi from parent!")308 t.join()309 (log, _) = capsys.readouterr()310 [child, parent] = log.split('\n')[0:2]311 assert 'tid="child"' in child312 assert "Hi from child!" in child313 assert 'tid="parent"' in parent314 assert "Hi from parent!" in parent315 assert "--- Logging error ---" not in child316 assert "--- Logging error ---" not in parent317 assert 'git_commit_id="deadbeef"' in child318 assert 'git_commit_id="deadbeef"' in parent319def test_should_not_add_commit_id_context_on_missing_env(capsys, monkeypatch):320 monkeypatch.setenv('GIT_COMMIT_ID', '')321 setup_logging(plaintext=True, stream=sys.stdout)322 logging.info('Something committed')323 log = _readout_log(capsys)324 assert "--- Logging error ---" not in log325 assert "Something committed" in log326 assert 'git_commit_id' not in log327def test_local_should_override_global_context(capsys):328 setup_logging(plaintext=True, stream=sys.stdout)329 LogContext.set_default("attire", "barbecue suit")330 logging.info('Global')331 with LogContext(attire='grilldress'):332 logging.info('Local')333 (log, _) = capsys.readouterr()334 [global_, local] = log.split('\n')[0:2]335 assert "--- Logging error ---" not in log336 assert 'Global' in global_337 assert 'Local' in local338 assert 'attire="barbecue suit"' in global_339 assert 'attire="grilldress"' in local340def test_log_exceptions_context_should_log_exceptions(capsys):341 setup_logging(plaintext=True, stream=sys.stdout)342 with contextlib.suppress(Exception), LogContext(wtf='bbq'), log_exceptions():343 logging.info('In log context')344 raise Exception("In context manager")345 (log, _) = capsys.readouterr()346 [in_ctx, in_ctx_man] = log.split('\n')[0:2]347 assert "--- Logging error ---" not in log348 assert 'In log context' in in_ctx349 assert 'In context manager' in in_ctx_man350 assert 'wtf="bbq"' in in_ctx351 assert 'wtf="bbq"' in in_ctx_man352def test_log_exceptions_suppress(capsys):353 setup_logging(plaintext=True, stream=sys.stdout)354 with LogContext(wtf='bbq'), log_exceptions(suppress=True):355 logging.info('In log context')356 raise Exception("In context manager")357 (log, _) = capsys.readouterr()358 [in_ctx, in_ctx_man] = log.split('\n')[0:2]359 assert "--- Logging error ---" not in log360 assert 'In log context' in in_ctx361 assert 'In context manager' in in_ctx_man362 assert 'wtf="bbq"' in in_ctx...

Full Screen

Full Screen

test_structured_logging.py

Source:test_structured_logging.py Github

copy

Full Screen

...14def _readout_json(capsys):15 (out, _) = capsys.readouterr()16 return json.loads(out)17def test_should_log_jsons(capsys):18 setup_logging()19 logging.info("something happened")20 log_json = _readout_json(capsys)21 assert log_json["message"] == "something happened"22 assert log_json["filename"] == "test_structured_logging.py"23 assert log_json["lineno"] is not None24 assert log_json["timestamp"] is not None25 assert log_json["severity"] == "INFO"26def test_should_log_jsons_error(capsys):27 setup_logging()28 logging.error("error error!")29 log_json = _readout_json(capsys)30 assert log_json["message"] == "error error!"31 assert log_json["filename"] == "test_structured_logging.py"32 assert log_json["lineno"] is not None33 assert log_json["timestamp"] is not None34 assert log_json["severity"] == "ERROR"35def test_should_log_exceptions_as_json(capsys):36 setup_logging()37 # noinspection PyBroadException38 try:39 raise Exception("something horribly went wrong")40 except Exception:41 logging.exception("some error message")42 log_json = _readout_json(capsys)43 assert log_json["message"] == "some error message"44 assert "Traceback (most recent call last):" in log_json["exc_info"]45 assert 'raise Exception("something horribly went wrong")' in log_json["exc_info"]46 assert log_json["filename"] == "test_structured_logging.py"47 assert log_json["lineno"] is not None48 assert log_json["timestamp"] is not None49 assert log_json["severity"] == "ERROR"50def test_should_not_log_below_log_level(capsys):51 setup_logging(min_level=logging.WARNING)52 logging.info("this should not be logged")53 logging.warning("warning should be logged")54 log_json = _readout_json(capsys)55 assert log_json["message"] == "warning should be logged"56 assert log_json["filename"] == "test_structured_logging.py"57 assert log_json["severity"] == "WARNING"58 assert log_json["lineno"] is not None59 assert log_json["timestamp"] is not None60def test_should_include_context(capsys):61 setup_logging()62 with LogContext(trace_id=123):63 logging.info("Something mysterious happened!")64 log_json = _readout_json(capsys)65 assert log_json["message"] == "Something mysterious happened!"66 assert log_json["trace_id"] == 12367 assert log_json["severity"] == "INFO"68 assert log_json["lineno"] is not None69 assert log_json["timestamp"] is not None70def test_should_handle_nested_context(capsys):71 setup_logging()72 with LogContext(trace_id=123, foo="bar"):73 with LogContext(trace_id=42):74 logging.info("Something nested happened!")75 log_json = _readout_json(capsys)76 assert log_json["message"] == "Something nested happened!"77 assert log_json["trace_id"] == 4278 assert log_json["foo"] == "bar"79 assert log_json["severity"] == "INFO"80 assert log_json["lineno"] is not None81 assert log_json["timestamp"] is not None82def test_should_handle_extra_parameters(capsys):83 setup_logging()84 logging.info("Something extra happened!", extra={'foo': 'bar'})85 log_json = _readout_json(capsys)86 assert log_json['message'] == 'Something extra happened!'87 assert log_json['foo'] == 'bar'88def test_extra_parameters_should_override(capsys):89 setup_logging()90 with LogContext(trace_id=123, foo='bar'):91 logging.info("Something extra happened!", extra={'foo': 'quux'})92 log_json = _readout_json(capsys)93 assert log_json['message'] == 'Something extra happened!'94 assert log_json['trace_id'] == 12395 assert log_json['foo'] == 'quux'96def test_context_should_not_overwrite_existing_records(capsys):97 setup_logging()98 with LogContext(timestamp=123):99 logging.info("something happened")100 log_json = _readout_json(capsys)101 assert log_json['message'] == 'something happened'102 assert log_json['timestamp'] != 123103@pytest.mark.asyncio104async def test_should_handle_async_context(capsys):105 setup_logging()106 async def busywork(n):107 await asyncio.sleep(0.01)108 return n + 1109 async with LogContext(trace_id=123):110 result = await busywork(0) + await busywork(121)111 async with LogContext(result=result):112 logging.info("Hei!")113 log_json = _readout_json(capsys)114 assert log_json["message"] == "Hei!"115 assert log_json["result"] == 123116 assert log_json["severity"] == "INFO"117 assert log_json["lineno"] is not None118 assert log_json["timestamp"] is not None119def test_should_handle_multiple_threads_with_contexts(capsys):120 # This test runs a child thread with a log context while121 # (hopefully, depending on timing)122 # a parent thread is also using a log context to make sure that123 # thread-local variables actually work the way I think.124 setup_logging()125 def worker():126 with LogContext(tid="child"):127 logging.info("Hi from child!")128 time.sleep(0.02)129 t = threading.Thread(target=worker)130 t.start()131 time.sleep(0.01)132 with LogContext(tid="parent"):133 logging.info("Hi from parent!")134 t.join()135 (out, _) = capsys.readouterr()136 [child, parent] = [json.loads(s) for s in out.split("\n") if s]137 assert child["tid"] == "child"138 assert child["message"] == "Hi from child!"139 assert parent["tid"] == "parent"140 assert parent["message"] == "Hi from parent!"141 assert child["thread"] != parent["thread"]142 assert child["thread"] is not None143 assert child["process"] == parent["process"]144 assert child['process'] is not None145 assert child["severity"] == "INFO"146 assert parent["severity"] == "INFO"147 assert child['timestamp'] is not None148 assert parent['timestamp'] is not None149def test_should_work_with_nonroot_logger(capsys):150 setup_logging()151 logger = logging.getLogger("nonroot")152 with LogContext(trace_id=123):153 logger.info("I'm not the root logger.")154 log_json = _readout_json(capsys)155 assert log_json['message'] == "I'm not the root logger."156 assert log_json['trace_id'] == 123157 assert log_json['timestamp'] is not None158def test_should_read_environment_config(capsys, monkeypatch):159 monkeypatch.setenv('NIVACLOUD_PLAINTEXT_LOGS', '0')160 setup_logging()161 logging.info("Environment blah blah.")162 log_json = _readout_json(capsys)163 assert log_json['message'] == "Environment blah blah."164 assert log_json['timestamp'] is not None165def test_should_override_propagation(capsys):166 logger = logging.getLogger('foo')167 logger.propagate = False168 setup_logging(override=True)169 logger.info('Hei')170 log_json = _readout_json(capsys)171 assert log_json['message'] == 'Hei'172def test_should_not_log_on_non_override(capsys):173 logger = logging.getLogger('foo')174 logger.propagate = False175 setup_logging(override=False)176 logger.info('Hei')177 with pytest.raises(json.JSONDecodeError):178 _readout_json(capsys)179def test_should_handle_multiple_setup_calls(capsys):180 setup_logging()181 setup_logging()182 logging.info('Hei')183 # (Would throw exception if output was doubled.)184 log_json = _readout_json(capsys)185 assert log_json['message'] == 'Hei'186def test_auto_context_should_only_add_requested_context(capsys):187 # noinspection PyUnusedLocal188 @auto_context("host", "user")189 def login(host, user, password):190 logging.info("Logging in")191 setup_logging()192 login("ftp.example.com", "jane", "supersekrit")193 log_json = _readout_json(capsys)194 assert log_json["host"] == "ftp.example.com"195 assert log_json["user"] == "jane"196 assert "password" not in log_json197def test_auto_context_should_log_all_parameters_by_default(capsys):198 # noinspection PyUnusedLocal199 @auto_context()200 def lookup(host, *servers):201 logging.info("Doing lookup...")202 setup_logging()203 lookup("ftp.example.com", "1.1.1.1", "8.8.8.8")204 log_json = _readout_json(capsys)205 assert log_json["host"] == "ftp.example.com"206 assert log_json["servers"] == ["1.1.1.1", "8.8.8.8"]207def test_auto_context_on_instance_methods(capsys):208 class MyClass:209 # noinspection PyUnusedLocal210 @auto_context()211 def my_method(self, a):212 logging.info("Hi!")213 setup_logging()214 c = MyClass()215 c.my_method(42)216 log_json = _readout_json(capsys)217 assert log_json['a'] == 42218def test_should_handle_complex_context_data(capsys):219 setup_logging()220 class Sample:221 pass222 thing = {223 'my_id': UUID('7118ad7e-6e26-483a-a120-7ec176331354'),224 'time': datetime(2019, 12, 24, 12, 34, 56, 0),225 'tupled': ("foo", {'complex': complex(12, 45)}, 1, 1.2, -4, 1.4e-10),226 'class': Sample,227 'instance': Sample(),228 'nan': math.nan,229 }230 with LogContext(thing=thing):231 logging.info("Hi, I have bunch of stuff.")232 log_json = _readout_json(capsys)233 thing = log_json['thing']234 assert thing['my_id'] == '7118ad7e-6e26-483a-a120-7ec176331354'235 assert thing['time'] == '2019-12-24T12:34:56'236 assert ["foo", {"complex": {"real": 12.0, "imag": 45.0}}, 1, 1.2, -4, 1.4e-10] == thing["tupled"]237 assert math.isnan(thing['nan'])238def test_sigusr1_should_set_info_logging(capsys):239 setup_logging(min_level=logging.ERROR)240 logging.info("Not logged")241 os.kill(os.getpid(), signal.SIGUSR1)242 logging.info("This is logged")243 (out, _) = capsys.readouterr()244 outputs = [json.loads(s) for s in out.split("\n") if s]245 assert len(outputs) == 1, "Expecting single line of logging output"246 assert outputs[0]['message'] == 'This is logged'247def test_sigusr2_should_set_debug_logging(capsys):248 setup_logging(min_level=logging.INFO)249 logging.debug("Not logged")250 os.kill(os.getpid(), signal.SIGUSR2)251 logging.debug("THIS is logged")252 (out, _) = capsys.readouterr()253 outputs = [json.loads(s) for s in out.split("\n") if s]254 assert len(outputs) == 1, "Expecting single line of logging output"255 assert outputs[0]['message'] == 'THIS is logged'256def test_signal_handler_override_should_call_previous_handlers(capsys):257 myhandler_run_count = 0258 def myhandler(_s, _f):259 nonlocal myhandler_run_count260 myhandler_run_count += 1261 signal.signal(signal.SIGUSR2, myhandler)262 os.kill(os.getpid(), signal.SIGUSR2)263 setup_logging(min_level=logging.INFO)264 os.kill(os.getpid(), signal.SIGUSR2)265 logging.debug("Debugged!")266 log_json = _readout_json(capsys)267 assert log_json['message'] == 'Debugged!'268 assert myhandler_run_count == 2269def test_should_add_commit_it_from_environment(capsys, monkeypatch):270 monkeypatch.setenv('GIT_COMMIT_ID', 'd22b929')271 setup_logging()272 logging.info('Something committed')273 log_json = _readout_json(capsys)274 assert log_json['message'] == 'Something committed'275 assert log_json['git_commit_id'] == 'd22b929'276def test_should_add_commit_it_from_environment_to_all_threads(capsys, monkeypatch):277 monkeypatch.setenv('GIT_COMMIT_ID', 'deadbeef')278 setup_logging()279 def worker():280 with LogContext(tid="child"):281 logging.info("Hi from child!")282 time.sleep(0.02)283 t = threading.Thread(target=worker)284 t.start()285 time.sleep(0.01)286 with LogContext(tid="parent"):287 logging.info("Hi from parent!")288 t.join()289 (out, _) = capsys.readouterr()290 [child, parent] = [json.loads(s) for s in out.split("\n") if s]291 assert child["tid"] == "child"292 assert child["message"] == "Hi from child!"293 assert parent["tid"] == "parent"294 assert parent["message"] == "Hi from parent!"295 assert child["thread"] != parent["thread"]296 assert child["git_commit_id"] == "deadbeef"297 assert parent["git_commit_id"] == "deadbeef"298def test_should_not_add_commit_id_context_on_missing_env(capsys, monkeypatch):299 monkeypatch.setenv('GIT_COMMIT_ID', '')300 setup_logging()301 logging.info('Something committed')302 log_json = _readout_json(capsys)303 assert log_json['message'] == 'Something committed'304 assert 'git_commit_id' not in log_json305def test_local_should_override_global_context(capsys):306 setup_logging()307 LogContext.set_default("attire", "barbecue suit")308 logging.info('Global')309 with LogContext(attire='grilldress'):310 logging.info('Local')311 (out, _) = capsys.readouterr()312 [global_, local] = [json.loads(s) for s in out.split("\n") if s]313 assert global_["message"] == 'Global'314 assert local["message"] == 'Local'315 assert global_["attire"] == 'barbecue suit'316 assert local["attire"] == 'grilldress'317def test_log_exceptions_context_should_log_exceptions(capsys):318 setup_logging()319 with contextlib.suppress(Exception), LogContext(wtf='bbq'), log_exceptions():320 logging.info('In log context')321 raise Exception("In context manager")322 (out, _) = capsys.readouterr()323 [in_ctx, in_ctx_man] = [json.loads(s) for s in out.split("\n") if s]324 assert in_ctx['message'] == 'In log context'325 assert in_ctx_man['message'] == 'In context manager'326 assert in_ctx['wtf'] == 'bbq'327 assert in_ctx_man['wtf'] == 'bbq'328def test_log_exceptions_suppress(capsys):329 setup_logging()330 with LogContext(wtf='bbq'), log_exceptions(suppress=True):331 logging.info('In log context')332 raise Exception("In context manager")333 (out, _) = capsys.readouterr()334 [in_ctx, in_ctx_man] = [json.loads(s) for s in out.split("\n") if s]335 assert in_ctx['message'] == 'In log context'336 assert in_ctx_man['message'] == 'In context manager'337 assert in_ctx['wtf'] == 'bbq'...

Full Screen

Full Screen

test_ios_whats_new.py

Source:test_ios_whats_new.py Github

copy

Full Screen

1# coding=utf-82"""3 Whats New Test Module4"""5from common import strings6from common.globals import Globals7from ios.pages.ios_login import IosLogin8from ios.pages.ios_main_dashboard import IosMainDashboard9from ios.pages.ios_whats_new import IosWhatsNew10class TestIosWhatsNew(object):11 """12 Whats New screen's Test Case13 """14 def test_start_whats_new_smoke(self, login, setup_logging, set_capabilities):15 """16 Scenarios:17 Verify Whats New screen is loaded successfully18 """19 global_contents = Globals(setup_logging)20 setup_logging.info('-- Starting {} Test Case'.format(TestIosWhatsNew.__name__))21 if login:22 setup_logging.info('{} is successfully logged in'.format(global_contents.login_user_name))23 if global_contents.is_first_time:24 assert IosWhatsNew(set_capabilities, setup_logging).get_title_textview()25 else:26 textview_screen_title = IosMainDashboard(set_capabilities, setup_logging)27 assert textview_screen_title.get_drawer_icon().text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME28 def test_validate_ui_elements_smoke(self, set_capabilities, setup_logging):29 """30 Scenarios:31 Verify following contents are visible on screen, 32 "Screen Title", "Cross Icon", "Main Feature Image",33 "Feature Title", "Feature Details", "Done"34 Verify all screen contents have their default values35 """36 global_contents = Globals(setup_logging)37 if global_contents.is_first_time:38 ios_whats_new_page = IosWhatsNew(set_capabilities, setup_logging)39 assert ios_whats_new_page.get_title_textview()40 assert ios_whats_new_page.get_close_button().text == strings.BLANK_FIELD41 assert ios_whats_new_page.get_main_image()42 assert ios_whats_new_page.get_feature_title_textview()43 assert ios_whats_new_page.get_feature_details()44 assert ios_whats_new_page.get_done_button().text == strings.WHATS_NEW_DONE45 else:46 setup_logging.info('validate_ui_elements is not needed')47 assert True48 def test_navigate_features_smoke(self, set_capabilities, setup_logging):49 """50 Verify that user can navigate between features51 """52 global_contents = Globals(setup_logging)53 if global_contents.is_first_time:54 ios_whats_new_page = IosWhatsNew(set_capabilities, setup_logging)55 assert ios_whats_new_page.navigate_features().text == strings.WHATS_NEW_DONE56 else:57 setup_logging.info('navigate_features is not needed')58 def test_close_features_screen_smoke(self, set_capabilities, setup_logging):59 """60 Verify that user can close New Feature screen and move to Main Dashboard screen61 """62 global_contents = Globals(setup_logging)63 if global_contents.is_first_time:64 ios_whats_new_page = IosWhatsNew(set_capabilities, setup_logging)65 assert ios_whats_new_page.exit_features().text == strings.MAIN_DASHBOARD_SCREEN_TITLE66 else:67 setup_logging.info('close_features_screen is not needed')68 def test_re_login_smoke(self, setup_logging, set_capabilities):69 """70 Scenarios:71 Verify after re-login with same user "Whats New" screen will not be visible72 """73 global_contents = Globals(setup_logging)74 ios_main_dashboard_page = IosMainDashboard(set_capabilities, setup_logging)75 assert ios_main_dashboard_page.get_drawer_icon().text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME76 assert ios_main_dashboard_page.get_account_options()[3].text == strings.ACCOUNT_LOGOUT77 assert ios_main_dashboard_page.log_out().text == strings.LOGIN78 setup_logging.info('{} is successfully logged out'.format(global_contents.login_user_name))79 ios_login_page = IosLogin(set_capabilities, setup_logging)80 login_output = ios_login_page.login(81 global_contents.login_user_name,82 global_contents.login_password,83 False84 )85 assert login_output.text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME86 setup_logging.info('{} is successfully logged in'.format(global_contents.target_environment))87 def test_landscape_smoke(self, set_capabilities, setup_logging):88 """89 Scenarios:90 Landscape support is added for Whats New screen with following cases,91 Change device orientation to Landscape mode92 Verify Whats New screen is loaded successfully after login93 Verify following contents are visible on screen, 94 "Screen Title", "Cross Icon", "Main Feature Image",95 "Feature Title", "Feature Details", "Done"96 Verify all screen contents have their default values97 Verifies that user can navigate between features98 Verifies that user can close New Feature screen and move to Main Dashboard screen99 Verify after re-login with same user "Whats New" screen will not be visible100 Change device orientation to Portrait mode101 """102 global_contents = Globals(setup_logging)103 ios_login_page = IosLogin(set_capabilities, setup_logging)104 ios_whats_new_page = IosWhatsNew(set_capabilities, setup_logging)105 ios_main_dashboard_page = IosMainDashboard(set_capabilities, setup_logging)106 assert ios_main_dashboard_page.get_drawer_icon().text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME107 assert ios_main_dashboard_page.get_account_options()[3].text == strings.ACCOUNT_LOGOUT108 assert ios_main_dashboard_page.log_out().text == strings.LOGIN109 assert ios_login_page.login(global_contents.login_user_name, global_contents.login_password)110 assert IosWhatsNew(set_capabilities, setup_logging).get_title_textview()111 setup_logging.info('{} is successfully logged in'.format(global_contents.login_user_name))112 global_contents.turn_orientation(set_capabilities, global_contents.LANDSCAPE_ORIENTATION)113 assert ios_whats_new_page.get_title_textview()114 assert ios_whats_new_page.get_close_button().text == strings.BLANK_FIELD115 assert ios_whats_new_page.get_main_image()116 assert ios_whats_new_page.get_feature_title_textview()117 assert ios_whats_new_page.get_feature_details()118 assert ios_whats_new_page.get_done_button().text == strings.WHATS_NEW_DONE119 assert ios_whats_new_page.navigate_features().text == strings.WHATS_NEW_DONE120 assert ios_main_dashboard_page.get_drawer_icon().text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME121 assert ios_main_dashboard_page.get_account_options()[3].text == strings.ACCOUNT_LOGOUT122 assert ios_main_dashboard_page.log_out().text == strings.LOGIN123 setup_logging.info('{} is successfully logged out'.format(global_contents.login_user_name))124 ios_login_page = IosLogin(set_capabilities, setup_logging)125 login_output = ios_login_page.login(126 global_contents.login_user_name,127 global_contents.login_password,128 False129 )130 assert login_output.text == strings.MAIN_DASHBOARD_NAVIGATION_MENU_NAME131 setup_logging.info('{} is successfully logged in'.format(global_contents.target_environment))132 global_contents.turn_orientation(set_capabilities, global_contents.PORTRAIT_ORIENTATION)...

Full Screen

Full Screen

test_logging.py

Source:test_logging.py Github

copy

Full Screen

...10# 2. It's important that every test uses a different logger name (e.g.11# with_file vs. console_only); otherwise, you'll get errors trying to write12# to a closed file between one test to another.13def test_setup_logging_with_file():14 setup_logging(LOGGING_CONFIG)15 log = logging.getLogger("nosuch")16 assert len(log.handlers) == 017 log = config_logger("with_file", {"log_file": "foo.log", "no_color": True})18 assert len(log.handlers) == 219def test_setup_logging_console_only():20 setup_logging()21 log = logging.getLogger("nosuch")22 assert len(log.handlers) == 023 log = config_logger("console_only", LOGGING_CONFIG)24 assert len(log.handlers) == 125def test_logging_error_method(capsys):26 setup_logging(LOGGING_CONFIG)27 sys.stderr.write("==START==\n")28 log = logging.getLogger("error_method")29 log.error("error")30 sys.stderr.write("==END==")31 captured = capsys.readouterr()32 assert captured.out == ""33 assert captured.err == """==START==34[ERROR ] error35==END=="""36def test_logging_debug_method_quiet(capsys):37 setup_logging(LOGGING_CONFIG)38 sys.stderr.write("==START==\n")39 log = logging.getLogger("debug_q")40 log.debug("debug")41 sys.stderr.write("==END==")42 captured = capsys.readouterr()43 assert captured.out == ""44 assert captured.err == "==START==\n==END=="45def test_logging_debug_method_verbose(capsys):46 setup_logging(LOGGING_CONFIG)47 sys.stderr.write("==START==\n")48 log = config_logger("debug_v", {"log_level": DEBUG, "log_file": None, "no_color": True})49 log.diagnostic('Logging level for the console is set to DEBUG.')50 log.debug("debug")51 sys.stderr.write("==END==")52 captured = capsys.readouterr()53 assert captured.out == ""54 assert captured.err == """==START==55[DIAGNOSTIC] Logging level for the console is set to DEBUG.56[DEBUG ] debug57==END=="""58def test_logging_diagnostic_method_quiet(capsys):59 setup_logging(LOGGING_CONFIG)60 sys.stderr.write("==START==\n")61 log = logging.getLogger("diagnostic_q")62 log.diagnostic("diagnostic")63 sys.stderr.write("==END==")64 captured = capsys.readouterr()65 assert captured.out == ""66 assert captured.err == "==START==\n==END=="67def test_logging_diagnostic_method_verbose(capsys):68 setup_logging(LOGGING_CONFIG)69 sys.stderr.write("==START==\n")70 log = config_logger("diagnostic_v", {"log_level": DIAGNOSTIC, "log_file": None, "no_color": True})71 log.diagnostic('Logging level for the console is set to DIAGNOSTIC.')72 log.diagnostic("diagnostic")73 sys.stderr.write("==END==")74 captured = capsys.readouterr()75 assert captured.out == ""76 assert captured.err == """==START==77[DIAGNOSTIC] Logging level for the console is set to DIAGNOSTIC.78[DIAGNOSTIC] diagnostic79==END=="""80def test_logging_trace_method_quiet(capsys):81 setup_logging(LOGGING_CONFIG)82 sys.stderr.write("==START==\n")83 log = logging.getLogger("trace_q")84 log.diagnostic('Logging level for the console is set to the default of WARNING.')85 log.trace("trace")86 sys.stderr.write("==END==")87 captured = capsys.readouterr()88 assert captured.out == ""89 assert captured.err == "==START==\n==END=="90def test_logging_trace_method_verbose(capsys):91 setup_logging(LOGGING_CONFIG)92 sys.stderr.write("==START==\n")93 log = config_logger("trace_v", {"log_level": TRACE, "log_file": None, "no_color": True})94 log.diagnostic('Logging level for the console is set to TRACE.')95 log.trace("trace")96 sys.stderr.write("==END==")97 captured = capsys.readouterr()98 assert captured.out == ""99 assert captured.err == """==START==100[DIAGNOSTIC] Logging level for the console is set to TRACE.101[TRACE ] trace102==END=="""103def test_logging_exception_method(capsys):104 setup_logging(LOGGING_CONFIG)105 sys.stderr.write("==START==\n")106 log = logging.getLogger("exception_method")107 log.exception(GWError("exception", loglevel=CRITICAL))108 sys.stderr.write("==END==")109 captured = capsys.readouterr()110 assert captured.out == ""111 err_txt = captured.err.replace('NoneType: None\n', '') # FIXME Why in the hell is this necessary????????????112 assert err_txt == """==START==113[CRITICAL] exception114==END=="""115def test_logging_uncaught_method(capsys):116 setup_logging(LOGGING_CONFIG)117 sys.stderr.write("==START==\n")118 log = logging.getLogger("uncaught_method")119 log.uncaught(GWError("uncaught"))120 sys.stderr.write("==END==")121 captured = capsys.readouterr()122 assert captured.out == ""123 err_txt = captured.err.replace('NoneType: None\n', '') # FIXME Why in the hell is this necessary????????????124 assert err_txt == \125 """==START==126[ERROR ] Uncaught error detected. There is no good reason why the following error wasn't handled earlier.127[ERROR ] uncaught128==END=="""129def test_level_constants():130 assert CRITICAL == 50...

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 Testify 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