


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















A. Raise the logging level to WARNING and remove all request-body logging B. Introduce a logging filter that redacts sensitive fields, set file permissions to 640, and gate DEBUG logging behind an environment flag C. Switch to syslog and rely on the OS to protect log integrity D. Encrypt the log files at rest and continue logging all request bodies at DEBUG
Redaction filters remove sensitive data at the source, restrictive permissions limit exposure, and environment-gated DEBUG prevents production leakage. Raising to WARNING (A) destroys debuggability, syslog (C) does not redact content, and encryption at rest (D) still leaves plaintext accessible to the application and any process reading logs.
A. assert is optimized away under python -O, so it should never be used for input validation in production, but is appropriate in tests B. assert should be used for all runtime validation because it raises AssertionError with a clear message C. assert is only valid inside unittest.TestCase methods and is a syntax error elsewhere D. assert statements are always executed regardless of interpreter flags and are therefore safe for security checks
Python's -O flag strips assert statements, making them unreliable for production validation; they are intended for internal sanity checks and test assertions. Option B ignores the -O stripping, C is factually wrong (assert works anywhere), and D is false because -O disables them.
A. Change the return type annotation to Optional[str] B. Add # type: ignore to the line C. Use a default value in dict.get() or explicitly handle the None case before returning D. Cast the result with typing.cast(str, ...)
Handling the None case or providing a default ensures a str is always returned, preserving the contract. Changing the annotation (A) weakens the interface, # type: ignore (B) suppresses rather than fixes, and cast (D) lies to the type checker without runtime guarantee.
A. The tests execute most lines but fail to assert on the behavior those lines produce B. The coverage tool is misconfigured and should be replaced C. Mutation testing is unreliable and should be ignored D. The codebase has too many lines to test effectively
High line coverage with low mutation score indicates tests run code without meaningful assertions, allowing mutants to survive. B and C misattribute the problem to tooling, and D is irrelevant to the assertion gap.
A. Increase the logging level to CRITICAL B. Switch to a TimedRotatingFileHandler with a longer retention interval and off-host shipping C. Disable rotation and write to a single file D. Compress logs in memory before writing
Timed rotation with longer retention plus off-host shipping preserves forensic data while bounding local disk use. Raising level (A) reduces detail, disabling rotation (C) risks disk exhaustion, and in-memory compression (D) does not address retention.
A. pytest.mark.parametrize with a fixed list of inputs B. hypothesis.given with strategies generating varied inputs C. pytest.fixture(scope='session') D. pytest.raises context manager
Hypothesis generates diverse inputs and shrinks failing cases, exposing edge cases beyond fixed examples. Parametrize (A) uses predefined inputs, fixtures (C) manage setup, and pytest.raises (D) only asserts exceptions.
A. Assertions raise AssertionError, which is not a subclass of Exception and therefore cannot be caught by standard error handlers. B. Python's -O flag strips assert statements entirely, so the authorization check silently vanishes while the privileged operation still executes. C. Assertions evaluate both operands eagerly, leaking the admin role value into logs through side-channel timing. D. Assertions are only evaluated inside unittest test cases, so production code never runs them.
Running with -O or PYTHONOPTIMIZE removes all assert statements, so an authorization guard built on assert is compiled away and the privileged path runs unchecked. Assertions are for internal invariants, not security enforcement; A is wrong because AssertionError subclasses Exception, C misstates evaluation semantics, and D is false.
A. Nothing, because the child logger inherits the root's DEBUG level but its own default level is WARNING and propagation is disabled. B. The record is filtered at the logger level (WARNING >= effective level) and then each handler independently decides: stream emits it, file drops it. C. Only the FileHandler emits it, since handler levels override the logger's effective level. D. Both handlers emit it because the root logger's DEBUG level is the lowest configured threshold.
A record passes the logger's effective level first, then each attached handler applies its own level: the DEBUG stream handler emits the WARNING, while the ERROR file handler discards it. A is wrong because child loggers default to NOTSET and inherit the root level; C and D invert the two-stage filtering model.
A. Set a module-level global CORRELATION_ID and reference it in the formatter string. B. Use a logging.Filter that reads contextvars.ContextVar and injects the ID into record.dict before formatting. C. Subclass logging.Formatter and read threading.current_thread().ident as the correlation ID. D. Call logging.basicConfig(extra={'correlation_id': id}) once at application startup.
A Filter that pulls from a ContextVar (or threading.local for threads) injects the per-request ID into each record safely at emit time. Global state (A) and thread IDs (C) leak or misidentify requests, and basicConfig's extra (D) applies only to that single call, not subsequent records.
A. mypy subsumes pylint because type checking is strictly stronger than linting. B. mypy verifies type consistency across annotations; pylint detects style, unused code, and semantic smells (e.g., dangerous default arguments) that type systems cannot express. C. pylint performs dataflow analysis, so it detects all type errors that mypy reports. D. Both tools use the same AST and produce identical diagnostics; running both is purely redundant.
Static type checkers validate annotation consistency but cannot flag mutable default arguments, unused imports, or style violations that pylint targets via its own checkers. A and D wrongly claim redundancy; C overstates pylint's type-inference capability.
A. Assert the output length equals the input length and that the first element is the minimum. B. Assert the output is sorted, is a permutation of the input (same multiset), and is idempotent under re-sorting. C. Assert the output equals a hard-coded expected list for a fixed input. D. Assert the output type is list and that no exception is raised for any input.
Sortedness, permutation equivalence, and idempotence together fully characterize a correct sort, catching both ordering and data-loss bugs. A is incomplete (misses permutation), C is example-based not property-based, and D verifies nothing about correctness.
A. Escape shell metacharacters in the input with a regex before concatenation. B. Pass the command as a list of arguments and set shell=False, avoiding shell interpretation entirely. C. Wrap the call in a try/except to catch injection-induced errors. D. Log the command at ERROR level so injections are auditable.
Using an argument list with shell=False removes the shell from the execution path, structurally preventing command injection. Escaping (A) is error-prone and bypassable, C only handles symptoms, and D provides no security control.
A. Branch coverage is a weaker metric than statement coverage, so the gate is misconfigured. B. Coverage measures executed code, not the adequacy of assertions or the exploration of input space, so high coverage can coexist with untested security-relevant behavior. C. Coverage tools cannot measure code that uses assertions, so security paths are invisible. D. The gate should use mutation testing exclusively, since coverage is always meaningless.
Coverage quantifies which lines/branches executed, not whether assertions validate behavior or whether adversarial inputs were explored; a bypass can sit on a covered branch with no effective oracle. A misstates the metric hierarchy, C is false, and D overstates the case against coverage.
A. Set the logger level to CRITICAL so lower-severity exceptions are never logged. B. Attach a custom Filter that redacts sensitive patterns from record.msg, record.args, and record.exc_info before formatting, and log exceptions with exc_info=True. C. Use print() instead of logging for exception output to avoid formatter processing. D. Disable propagation and rely on the default formatter, which omits exception details.
A redacting Filter that scrubs msg, args, and exc_info is the only approach that sanitizes both the message and the traceback regardless of severity. A suppresses rather than redacts, C bypasses logging controls entirely, and D is false - the default formatter does include exception text.
A. Suppress B608 globally in the Bandit config to keep the build green. B. Refactor the query to remove the constant table name. C. Add a targeted # nosec B608 with a comment justifying the constant, since the table name is not user-controlled. D. Switch from Bandit to Pylint, which does not flag SQL construction.
A targeted # nosec B608 with justification is the accepted practice for a verified false positive, preserving the rule's signal elsewhere. Global suppression (A) blinds the tool to real findings, refactoring a constant table name (B) is unnecessary, and switching tools (D) merely hides the issue rather than resolving it.
A. Assertions are removed when Python runs with -O, so the check silently disappears, enabling privilege bypass. B. Assertions raise AssertionError, which is uncaught and crashes the process, causing a denial of service. C. Assertions are evaluated lazily, so the check may not run on the first call. D. Assertions cannot reference attributes, so user.is_admin is always falsy.
The -O flag strips assert statements entirely, so a security gate built on assert vanishes in optimized deployments. Assertions are eager, not lazy (C), can reference attributes (D), and an AssertionError crash (B) is a lesser concern than the silent bypass.
A. patch replaces the attribute on the module object, so aliased references bound earlier are unaffected, and the assertion checks the wrong target. B. patch only works on class methods, not module-level functions. C. requests.get is a C extension and cannot be patched. D. The mock returns a MagicMock that always equals the real response.
patch('requests.get') rebinds the attribute on the requests module, but from requests import get created an independent name binding in the importing module, so the production call bypasses the mock. The assertion then verifies a call that never occurred in the real path, giving a false green. patch works on module functions (B), requests is pure Python (C), and MagicMock equality (D) is irrelevant.
A. It runs cases in parallel across processes by default. B. It generates a distinct test ID per parameter set, so failures localize to a single case. C. It caches results so re-runs skip unchanged cases. D. It automatically retries flaky parameter sets.
Parametrize yields one test item per case with a unique ID, so a failure points to the specific inputs rather than aborting the loop at the first failure. Parallelism (A), caching (C), and retries (D) are not default behaviors of parametrize.
A. Add time.sleep(0.1) before the assertion to stabilize timing. B. Mark the test with @pytest.mark.flaky(reruns=3) to mask the failure. C. Replace the shared module-level list with a fixture that constructs a fresh instance per test. D. Reorder the suite so the offending test runs first.
The failure is test pollution from shared mutable state; a per-test fixture restores isolation and eliminates order dependence. Sleeping (A) does not fix shared state, reruns (B) hide the defect, and reordering (D) leaves the latent coupling in place.
A. eval(user_input) to evaluate a user-supplied arithmetic expression. B. eval(config_string) where config_string is loaded from an untrusted network source. C. ast.literal_eval(user_input) restricted to literals, used instead of eval for parsing. D. eval(open('plugin.py').read()) to dynamically load plugins at runtime.
ast.literal_eval parses only Python literals and raises on arbitrary expressions, eliminating code execution-the safe replacement for eval in parsing scenarios. Options A, B, and D all evaluate untrusted or attacker-influenced input with full interpreter semantics, enabling arbitrary code execution.
A. caplog.at_level temporarily lowers the handler level, but the root logger level set by basicConfig still filters INFO records before propagation. B. caplog.at_level sets both the logger and handler levels to WARNING, so INFO records are dropped unless propagate is disabled. C. caplog.at_level sets the level on the handler attached by caplog and on the specified logger, but records are still gated by the effective level of the originating logger, which basicConfig may have left at INFO. D. basicConfig is idempotent and therefore ignored during tests, so the root logger defaults to WARNING and caplog's handler level is the only filter.
caplog.at_level sets the level on the caplog handler and on the named logger, but emission is still gated by the originating logger's effective level; basicConfig's INFO setting on the root logger can therefore allow INFO records through. Options A and B misdescribe which levels caplog manipulates, and D incorrectly claims basicConfig is a no-op when it is actually idempotent only after the first successful call.
A. Using if not condition: raise ValueError(...) because it adds branching overhead that the optimizer cannot remove. B. Using assert isinstance(x, int) for input validation because -O strips assert statements entirely, removing the check. C. Using unittest.TestCase.assertTrue because unittest assertions are also removed under -O. D. Using typing.cast for narrowing because casts are erased at runtime regardless of optimization flags.
The -O flag removes assert statements, so any validation relying on assert silently disappears in optimized builds. unittest assertions and raise-based checks are not stripped by -O, and typing.cast is a no-op at runtime by design, making it unsuitable for runtime validation but not because of -O.
A. Four files; the oldest records are in the file with no numeric suffix. B. Three files; the oldest records are in app.log.3. C. Four files; the oldest records are in app.log.3. D. Three files; the oldest records are in the file with no numeric suffix.
RotatingFileHandler keeps the active file plus backupCount rotated files, so with backupCount=3 there are four files total. The highest-numbered backup (app.log.3) holds the oldest retained records, while the unsuffixed file holds the most recent.
A. Both patch the same object because Python resolves func through module at call time. B. patch patches the attribute on the module where it is defined; patch.object patches it on the importing module, so only patch.object works for the rebinding case. C. Neither works; from-imports create immutable bindings that cannot be patched. D. patch targets the name in the module where it is looked up (the importing module), so patch('importer.func') is required; patch.object on the defining module has no effect on the importer's binding.
After from module import func, the importing module holds its own reference, so the patch must target that binding (importer.func); patching the defining module leaves the importer's reference untouched. Options A and B invert the lookup semantics, and C is false because the binding can be replaced.
A. Switching to statement coverage and raising the threshold to 100%. B. Enabling branch coverage with --cov-branch so partial branches are counted as uncovered. C. Adding --cov-report=html to visualize the report. D. Using coverage combine to merge parallel runs before enforcing the threshold.
Statement coverage can be satisfied while a conditional branch is never taken; --cov-branch measures both branch outcomes and would expose the untested path. HTML reports and combining runs change reporting/aggregation, not the metric, and 100% statement coverage still permits untaken branches.
A. Encode the log message with base64 before passing it to the logger. B. Use logging.Formatter with %(message)s and rely on the logger's thread safety. C. Strip or escape CR/LF characters and prefer structured logging (e.g., JSON) that separates data from the message field. D. Set the logger level to WARNING so untrusted INFO records are discarded.
Log injection exploits unescaped newlines and control characters to forge log entries; sanitizing CR/LF and using structured formats that treat user data as a value rather than part of the message prevents it. Base64 obfuscates rather than neutralizes, formatters do not sanitize, and raising the level does not remove injection risk.