






















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!























50 QUESTIONS
# TOPIC 1 Configure Python logging to prevent sensitive data leakage and injection attacks while preserving auditability 2 Analyze the behavior of assert statements under -O optimization and select appropriate runtime validation strategies 3 Interpret and integrate outputs from static code analysis tools (Bandit, Semgrep, mypy) into a secure SDLC 4 Design property-based and mutation-tested suites that expose real faults rather than tautological or brittle tests 5 Apply taint analysis and input validation principles to remediate injection and deserialization vulnerabilities in Python 6 WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging 7 Assertions 8 Static Code Analysis & Testing 2026 9 Foundations of Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 10 Applied Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 11 Advanced Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 12 Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing Review
This study document brings together 50 carefully worded exam questions drawn from WGU D Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026, with the strongest emphasis placed on Configure Python logging to prevent sensitive data leakage and injection attacks while preserving auditability, Analyze the behavior of assert statements under -O optimization and select appropriate runtime validation strategies, Interpret and integrate outputs from static code analysis tools (Bandit, Semgrep and mypy) into a secure SDLC. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.
A. Set the logging level to WARNING to reduce the attack surface. B. Use a JSON formatter that serializes the message field and escapes control characters. CORRECT C. Wrap the log call in a try/except to catch injection exceptions. D. Encode the username with base64 before logging. RATIONALE: Structured JSON logging serializes and escapes newlines/control characters, neutralizing forged entries while keeping fields queryable. Level changes and exception handling do not sanitize content, and base64 obscures but does not structurally separate attacker-controlled data from log metadata.
A. Increasing line coverage to 100% on all branches. B. Adding property-based tests that assert invariants across generated inputs, including empty sequences. CORRECT C. Running the suite under pytest -x to stop on first failure. D. Adding more assertions inside the function under test. RATIONALE: Line coverage does not guarantee oracle quality or input diversity; property-based testing generates edge cases like empty inputs and checks invariants, exposing the None return. Branch coverage may still miss it, -x only changes failure handling, and internal assertions do not create external test oracles.
A. Disable the rule globally to reduce false positives. B. Verify the ORM's parameterization path with a taint-mode Semgrep rule and adjust the rule's sanitizer configuration. CORRECT C. Convert all queries to string concatenation to satisfy the rule. D. Add # nosemgrep to every flagged line. RATIONALE: The correct response is to validate the sanitizer behavior and refine the rule using taint mode so it recognizes the ORM's parameterization. Global disabling or blanket suppression hides real issues, and reverting to concatenation would introduce vulnerabilities.
A. None; mypy still checks all operations on Any values. B. Any propagates and suppresses type-based taint tracking, allowing unsafe flows to pass unchecked. CORRECT C. mypy will raise a runtime error when Any is used. D. Disabling that flag only affects documentation generation. RATIONALE: Any is compatible with all types and effectively disables type checking for those values, which can break taint propagation in type-aware analyzers. The other options misstate mypy's behavior; mypy is static and does not raise runtime errors.
A. The mutants are equivalent and cannot be killed. B. The mock removes the real logic from the test path, so mutants in the payment module are never executed. CORRECT C. Mutation testing requires 100% branch coverage to run. D. The stub returns success, which is the expected behavior. RATIONALE: Patching out the module under test prevents its mutated code from executing, yielding zero kills regardless of test quality. Equivalent mutants are possible but unlikely across an entire module, and mutation testing does not require full branch coverage to operate.
A. Remove the -ll flag to include all severities. B. Add --exclude tests to the command. C. Override the default exclusion with --include or remove tests from the excluded set. CORRECT D. Run bandit with -s B101 to skip assert checks. RATIONALE: Bandit's default exclusions include common test directories; to scan them, the exclusion set must be overridden or removed. -ll only filters severity, --exclude adds exclusions, and -s skips specific tests rather than including test files.
A. Confidentiality of the assertion message in logs B. Integrity of the authorization check, because assertions are stripped under -O CORRECT C. Availability, because -O disables exception handling D. Non-repudiation, because assert writes no audit record RATIONALE: CPython removes assert statements when debug is false (e.g., -O/-OO), so an authorization guard implemented as an assertion silently disappears, breaking the integrity of the access-control decision. Assertions are for internal invariants, not security enforcement; the other options misattribute the failure mode to logging, availability, or auditability.
A. pytest.mark.parametrize B. A session-scoped fixture that shares the dict C. pytest-randomly with a fixed seed D. An autouse function-scoped fixture that restores the dict CORRECT RATIONALE: An autouse function-scoped fixture that snapshots and restores the module-level dict isolates state between tests, removing order dependence. Parametrization changes inputs, session-scoped fixtures worsen sharing, and a fixed random seed only makes the order deterministic-not independent.
A. Cast uid to int before interpolation B. Add # nosec with a justification comment C. Use a parameterized query with a placeholder and pass uid as a bound parameter CORRECT D. Escape single quotes in uid with a regex RATIONALE: Parameterized queries separate SQL structure from data, eliminating injection regardless of input shape. Integer casting and regex escaping are fragile allowlist/denylist mitigations, and # nosec suppresses the detector without fixing the flaw.
A. Run radon with --total-average and parse the exit code B. Configure a linter (e.g., Ruff C901 with max-complexity) and exclude migrations via extend-exclude CORRECT C. Add # noqa: C901 to every migration file D. Use mypy --strict with per-module overrides RATIONALE: Ruff's C901 rule with max-complexity and an extend-exclude glob enforces a complexity threshold while skipping generated code in one config. Radon's average metric does not gate per-function complexity, blanket noqa is unmaintainable, and mypy does not measure complexity.
A. Increase the fuzzer's timeout B. Run the parser in a thread with a larger stack C. Enforce a maximum nesting depth and reject inputs exceeding it CORRECT D. Catch RecursionError and return None RATIONALE: Bounding nesting depth constrains resource consumption at the input boundary, preventing stack exhaustion. Raising timeouts or stack size only delays the crash, and catching RecursionError is unreliable once the C stack is exhausted.
A. Lower the threshold to 80% B. Add # pragma: no cover to type-checking blocks and enable coverage's branch analysis CORRECT C. Delete the type-checking imports D. Run tests with -O to skip the block RATIONALE: Type-checking-only blocks never execute at runtime, so # pragma: no cover (with branch coverage enabled) accurately excludes them without masking real gaps. Lowering the bar, deleting imports, or running with -O degrades type safety or coverage fidelity.
A. Switch to %-style lazy formatting and log a hashed user identifier CORRECT B. Use logging.debug with f-strings C. Buffer messages in a list and flush at exit D. Set the logger level to CRITICAL and remove the log call RATIONALE: Lazy %-style formatting defers string construction until the record is emitted, avoiding cost when disabled, while hashing the identifier prevents PII leakage. Debug f-strings still format eagerly, buffering risks data loss, and removing logs destroys observability.
A. Escape spaces and semicolons in user_input before passing to Popen. B. Replace shell=True with shell=False and pass an argument list. CORRECT C. Wrap the call in shlex.quote(user_input) and keep shell=True. D. Switch to os.system with a validated allow-list of characters. RATIONALE: Removing the shell interpreter and passing an argument list eliminates metacharacter interpretation entirely, which is the canonical CWE-78 fix. Escaping (A, C) is error-prone and still shell-dependent; os.system (D) is strictly worse.
A. Wrap the assertion in try/except and call logging.exception. B. Enable pytest's assertion rewriting (default) and add a descriptive message after a comma. CORRECT C. Replace with self.assertEqual from unittest for richer diffs. D. Add --tb=no to suppress the traceback and rely on logs. RATIONALE: pytest's assertion rewriting produces detailed diffs for complex objects automatically; adding a message supplements context. Option A bypasses rewriting, C loses pytest's introspection, and D hides diagnostics.
A. Call logging.basicConfig(level=logging.DEBUG) at module top. B. Add a FileHandler in the module to persist logs. C. Defer handler configuration to the application entry point and let pytest manage the root logger. CORRECT D. Set logging.disable(logging.CRITICAL) in the module. RATIONALE: pytest's caplog fixture installs its own handler on the root logger; libraries that configure handlers at import interfere with propagation. Deferring configuration to the application entry point preserves library hygiene and enables capture.
A. Freeze time with freezegun in every test module via a conftest autouse fixture. B. Inject a clock callable (e.g., clock=datetime.now) as a default parameter or dependency. CORRECT C. Patch datetime.datetime with unittest.mock.patch in each test. D. Set the system clock in CI to a fixed date. RATIONALE: Dependency injection of a clock is the most surgical, side-effect-free approach and aligns with testable design principles. Freezegun and global patching work but are broader and can mask unrelated time usage; altering the system clock is non-portable.
A. The output list has the same length as the input. B. The output is sorted and is a permutation of the input. CORRECT C. The first element is the minimum of the input. D. The output contains no duplicate values. RATIONALE: A correct sort must both order elements and preserve the multiset of inputs, making B the strongest invariant. Length, minimum, and uniqueness checks are necessary but not sufficient and can pass on incorrect implementations.
A. Assertions are slower than if-statements at runtime. B. Assertions can be stripped when Python runs with -O, silently disabling the check. CORRECT C. Assertions cannot reference object attributes. D. Assertions raise SystemExit instead of AssertionError. RATIONALE: Python's -O flag removes assert statements, so security-relevant checks may vanish in optimized deployments. Assertions are for internal invariants; authorization must use explicit conditionals and proper exceptions.
A. Increase the mock's side_effect to raise on any unexpected call. B. Use patch as a context manager or decorator scoped to each test rather than module-level patching. CORRECT C. Set autospec=True on every patch call. D. Add retries to the test to mask flakiness. RATIONALE: Module-level patches leak across tests and interact poorly with parallel execution; scoping patches to each test isolates state. Autospec improves fidelity but does not address leakage, and retries hide the underlying race.
A. basicConfig is idempotent and silently no-ops once any handler exists on the root logger; the submodule's import order triggered an earlier no-op configuration. CORRECT B. Child loggers created with __name__ do not propagate records to the root logger unless propagate=True is explicitly set on each child. C. Logger levels default to WARNING, so INFO/DEBUG records from the submodule are filtered before reaching the root handler. D. The submodule's logger name lacks a dot, so Python treats it as a top-level logger disconnected from the root hierarchy. RATIONALE: basicConfig() is a no-op if the root logger already has handlers, so configuration performed after any prior logging call (or in a different import order) is silently ignored, leaving records unhandled. Propagation is on by default (B false), levels default to WARNING but that filters only lower-severity records, not all (C overgeneralized), and dotted names are not required for hierarchy (D false).
A. Line coverage via coverage.py; the handler lines are counted as covered because they are syntactically present. B. Branch coverage via coverage.py --branch; it flags the unexecuted handler path as a partial branch. CORRECT C. Mutation testing via mutmut; it measures whether tests detect injected faults, which correlates directly with handler execution. D. Cyclomatic complexity via radon; high complexity in the try/except guarantees the handler is untested. RATIONALE: Branch coverage tracks whether both outcomes of conditional constructs (including exception paths) are exercised, exposing the never-taken handler. Line coverage can mark the handler lines as present without execution (A), mutation testing detects fault sensitivity but not branch execution per se (C), and complexity metrics measure structure, not test execution (D).
A. Switch to logging.info("user=%s token=%s", user, token) to defer formatting and improve performance. B. Remove the token from the message and log only non-sensitive identifiers; use lazy %s formatting for permitted fields. CORRECT C. Raise the log level to DEBUG so the token is only emitted in development environments. D. Hash the token with MD5 before logging so the value is not directly readable. RATIONALE: OWASP guidance requires excluding sensitive data from logs; deferring formatting (A) addresses performance, not disclosure. DEBUG does not prevent leakage in production (C), and MD5 of a token is reversible/guessable and still sensitive (D). The correct fix removes the secret and uses lazy formatting for allowed fields.
A. Convert the fixture to a module-scoped yield fixture to reduce setup frequency. B. Add autouse=True so the fixture runs for every test including thread-spawned ones. C. Ensure the fixture joins all spawned threads before yielding control back, using a factory that tracks and terminates threads in teardown. CORRECT D. Replace yield with return and rely on addfinalizer to run rollback after the test. RATIONALE: Teardown ordering with concurrent threads requires deterministic synchronization: the fixture must join/stop threads before rollback so no writes race the cleanup. Module scope increases shared state (A), autouse does not synchronize threads (B), and addfinalizer has similar ordering issues without joining (D).
A. Increase the root logger level to DEBUG to ensure records are enqueued. B. Set queue to a bounded queue.Queue(maxsize=N) and handle queue.Full by blocking or applying backpressure. CORRECT C. Add a second StreamHandler to the root logger to duplicate records to stderr. D. Disable propagate on all child loggers to reduce record volume. RATIONALE: Dropped records under load typically stem from a bounded queue that discards on Full; explicit backpressure or blocking enqueue preserves records. Level changes (A) do not affect capacity, extra handlers (C) bypass the queue, and disabling propagation (D) loses records rather than preserving them.