
































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!

































EXAM INFORMATION
Subject: Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing Questions: 50 | Format: Multiple choice Duration: 3 hours Passing score: 92%
ABOUT THIS EXAM
This exam assesses advanced competency in Python-based software security and testing practices, including structured logging, assertion design, static analysis tooling, and test architecture. It emphasizes secure coding patterns, tool configuration, and reasoning about subtle failure modes in production systems.
WHAT THIS COVERS
Detailed Explanations
Q A security audit reveals that an application logs full HTTP request bodies at DEBUG level in production, and the log files are world-readable on the host. Which combination of changes most effectively mitigates the risk while preserving operational debuggability?
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
CORRECT
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
EXPLANATION 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.
Detailed Explanations
Q bandit flags 'B608: hardcoded_sql_expressions' in a function that builds a query using an f-string with a user-supplied variable. Which remediation best addresses the root cause while preserving functionality?
A (^) Add a # nosec comment to suppress the warning
B (^) Replace the f-string with parameterized query placeholders and pass the variable as a bound parameter
CORRECT
C (^) Escape single quotes in the user input before interpolation
D (^) Move the query construction into a separate module to avoid detection
EXPLANATION Parameterized queries separate code from data, eliminating SQL injection at the root. Suppression (A) hides the vulnerability, manual escaping (C) is error-prone and incomplete, and moving code (D) does not fix the flaw.
Detailed Explanations
Q A pytest suite uses unittest.mock.patch to replace a database call, but the test passes even when the production code path is broken because the mock returns a truthy MagicMock by default. Which practice most reliably prevents this class of false-positive test?
A (^) Use autospec=True or spec_set on the mock to constrain its interface
CORRECT
B (^) Increase the number of assertions in the test
C (^) Run the tests with -p no:cacheprovider
D (^) Replace pytest with unittest for stricter defaults
EXPLANATION autospec/spec_set ensure the mock only exposes attributes and signatures that exist on the real object, catching typos and interface drift. More assertions (B) do not help if the mock is too permissive, cache settings (C) are unrelated, and unittest (D) has the same MagicMock behavior.
Detailed Explanations
Q In a CI pipeline, coverage reports show 95% line coverage but mutation testing (mutmut) reveals a mutation score of 40%. What does this discrepancy most strongly indicate about the test suite?
A (^) The tests execute most lines but fail to assert on the behavior those lines produce
CORRECT
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
EXPLANATION 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.
Detailed Explanations
Q A logging configuration uses a RotatingFileHandler with maxBytes=10MB and backupCount=5, but an incident shows logs older than the rotation window were lost during a high-volume attack. Which adjustment most directly improves forensic retention without unbounded disk growth?
A (^) Increase the logging level to CRITICAL
B (^) Switch to a TimedRotatingFileHandler with a longer retention interval and off-host shipping
CORRECT
C (^) Disable rotation and write to a single file
D (^) Compress logs in memory before writing
EXPLANATION 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.
Detailed Explanations
Q A developer adds logging of user passwords at ERROR level to diagnose a login failure, then removes it after the fix. Which secure logging principle was violated, and what is the correct practice?
A (^) Log level misuse; passwords should be logged at DEBUG
B (^) Sensitive data should never be logged in plaintext regardless of level; use redaction or omit
CORRECT
C (^) Logs should be written to a database instead of files
D (^) Passwords should be hashed before logging
EXPLANATION Credentials must never appear in logs in any form; redaction or omission is required. Logging at DEBUG (A) still exposes secrets, databases (C) do not solve exposure, and hashing (D) still leaks a crackable or replayable artifact.
Detailed Explanations
Q In a secure CI/CD pipeline, which integration of static analysis most effectively prevents vulnerable code from reaching production while minimizing developer friction?
A (^) Run bandit and mypy only on the main branch after merge
B (^) Run static analysis as a pre-commit hook and as a required CI gate on pull requests
CORRECT
C (^) Run static analysis nightly and email reports to the security team
D (^) Rely on code review alone to catch security issues
EXPLANATION Pre-commit hooks catch issues early, and required PR gates block merges with vulnerabilities, balancing speed and safety. Post-merge (A) allows vulnerable code in, nightly email (C) is too late, and review alone (D) is insufficient for consistent detection.
Detailed Explanations
Q A team configures a root logger with a StreamHandler at DEBUG and a FileHandler at ERROR, then calls logging.getLogger('app').warning('x'). Given Python's effective-level and handler-level filtering rules, what is emitted?
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.
CORRECT
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.
EXPLANATION 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.
Detailed Explanations
Q An audit requires every log record to be traceable to the originating request in a multithreaded service. Which logging configuration correctly attaches a per-request correlation ID without cross-thread leakage?
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.
CORRECT
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.
EXPLANATION 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.
Detailed Explanations
Q A developer writes with pytest.raises(ValueError): parse('bad'), but the test passes even when parse raises TypeError. Which pytest behavior explains this false positive, and what is the correct fix?
A (^) pytest.raises matches by MRO, so TypeError is a subclass of ValueError; use pytest.raises(ValueError, match=...).
B (^) pytest.raises catches any exception unless strict=True; the fix is to pass strict=True to pytest.raises.
C (^) The context manager only fails if no exception is raised; TypeError is not caught by pytest.raises(ValueError), so the test should already fail - the premise is incorrect.
CORRECT
D (^) pytest.raises catches Exception by default; the fix is to use except ValueError in a try/except block instead.
EXPLANATION pytest.raises(ValueError) re-raises any exception that is not an instance of ValueError, so a TypeError would fail the test - the described false positive cannot occur with this code. A is false (TypeError is not a ValueError subclass), and B/D misstate pytest.raises semantics.
Detailed Explanations
Q A test uses unittest.mock.patch('mymodule.requests.get') but the code under test imports requests as import requests and calls requests.get. The mock has no effect. What is the correct patching target and principle?
A (^) Patch 'requests.get'; patch always targets the original definition site.
B (^) Patch 'mymodule.requests.get'; patch targets where the object is looked up (the importing module's namespace), not its origin.
CORRECT
C (^) Patch 'requests.get' with create=True; the create flag resolves namespace mismatches.
D (^) Patch 'mymodule.requests'; you must replace the whole module object to intercept get.
EXPLANATION unittest.mock.patch replaces the name in the namespace where it is looked up - here mymodule.requests.get - so the code under test resolves the mock. A and C misstate the lookup rule; D replaces the module unnecessarily and breaks other attributes.
Detailed Explanations
Q A SAST tool reports a high-severity finding: user input flows into subprocess.run(cmd, shell=True). Which remediation most directly eliminates the injection class while preserving functionality?
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.
CORRECT
C (^) Wrap the call in a try/except to catch injection-induced errors.
D (^) Log the command at ERROR level so injections are auditable.
EXPLANATION 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.
Detailed Explanations
Q A CI gate fails when branch coverage drops below 85%, yet a critical authentication bypass ships undetected. Which testing principle best explains this failure of the gate?
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.
CORRECT
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.
EXPLANATION 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.