




























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!





























WGU D385 Task 1 Performance Assessment Guide | Comprehensive Examination WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026 actual exam preparation document
This document is an important and very helpful preparation resource for WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026. Every item uses a focused exam stem, four response options, a keyed response, and a clear rationale, making it easier to understand the subject, spot distractors, and build real exam confidence.
Question 1
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 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
RATIONALE 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.
Question 2
Which statement most accurately distinguishes the appropriate use of assert
statements in production Python code versus their use in test suites?
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
Question 4
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 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
RATIONALE 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.
Question 5
mypy reports 'error: Incompatible return value type (got "Optional[str]",
expected "str")' in a function that returns a value from a dict.get() call. Which
change most precisely resolves the type error without weakening type safety?
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, ...)
RATIONALE 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.
Question 6
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 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
RATIONALE 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.
Question 7
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
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 C. Logs should be written to a database instead of files D. Passwords should be hashed before logging
RATIONALE 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.
Question 10
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 C. Run static analysis nightly and email reports to the security team D. Rely on code review alone to catch security issues
RATIONALE 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.
Question 11
A security review flags a module for using assert to validate that an
authenticated user's role is 'admin' before executing a privileged operation.
Why is this pattern considered a critical vulnerability in production?
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.
RATIONALE 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.
Question 12
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.
contextvars.ContextVar and injects the ID into record.dict before formatting.
RATIONALE 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.
Question 14
A CI pipeline runs mypy --strict and pylint over a codebase. A developer
argues that passing mypy --strict makes pylint redundant for catching defects.
Which statement best characterizes the complementary roles of these static
analysis tools?
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.
RATIONALE 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.
Question 15
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. D. pytest.raises catches Exception by default; the fix is to use except ValueError in a try/except block instead.
RATIONALE 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.
Correct Answer: B - Assert the output is sorted, is a permutation of the input (same multiset), and is idempotent under re-sorting.
RATIONALE 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.
Question 18
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. C. Wrap the call in a try/except to catch injection-induced errors. D. Log the command at ERROR level so injections are auditable.
RATIONALE 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.
Question 19
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. 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.
RATIONALE 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.
Question 20
A developer wants to guarantee that a production service never emits stack
traces containing secrets, even when unexpected exceptions occur. Which
logging configuration achieves this most robustly?
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
RATIONALE A logging.Filter inspects each LogRecord before emission, so a regex-based redaction filter removes or masks token-bearing messages while DEBUG diagnostics elsewhere still flow. Level changes (A, D) suppress all DEBUG output rather than redacting selectively, and isEnabledFor guards (C) only avoid work-they do not sanitize emitted content.
Question 22
A test uses assertAlmostEqual(a, b, places=7) and passes locally but fails in
CI where the same inputs are computed in a different order. Which property
best explains the CI failure?
A. assertAlmostEqual compares rounded values, so reordering changes the rounding mode. B. Floating-point addition is non-associative, so accumulated rounding error can exceed the 7-place tolerance. C. Python's round() uses banker's rounding, which CI disables. D. The unittest framework seeds a global PRNG that perturbs float comparisons.
RATIONALE IEEE-754 addition is not associative; reordering operations changes the accumulated rounding error, which can push the difference past the 10^-7 tolerance. Rounding mode (A, C) is irrelevant to summation order, and unittest does not perturb float comparisons via a PRNG (D).
Question 23
A repository's CI runs bandit -r src/ and reports B608 (hardcoded SQL) on a
line using a parameterized query with a constant table name. What is the most
defensible engineering response?
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.
RATIONALE 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.
Question 24
A developer writes assert user.is_admin to gate a privileged operation in
production code. Which statement best characterizes the security risk?
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.
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.
RATIONALE 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.
Question 27
A code review flags this pattern: subprocess.run(cmd, shell=True) where
cmd interpolates a user-supplied filename. Which remediation most directly
eliminates the injection class?
A. Escape shell metacharacters in the filename before interpolation. B. Pass the command as a list of arguments with shell=False. C. Wrap the call in a try/except to catch CalledProcessError. D. Set check=True to fail fast on non-zero exit codes.
RATIONALE Using shell=False with an argument list bypasses the shell entirely, so metacharacters in the filename cannot be interpreted as commands. Escaping (A) is fragile and easy to get wrong, while error handling (C) and check=True (D) do not address injection.
Question 28
A team measures branch coverage at 92% but mutation score at 41%. Which
conclusion is most warranted?
A. The suite executes most branches but its assertions rarely detect behavioral changes, indicating weak oracles. B. The suite is nearly complete because branch coverage subsumes mutation adequacy. C. Mutation testing is unreliable below 95% branch coverage, so the score should be ignored. D. The gap proves the code contains no dead branches.
RATIONALE High branch coverage with low mutation score means tests reach code but do not assert on outcomes strongly enough to kill mutants-a classic weak-oracle signal. Coverage does not subsume mutation adequacy (B), mutation testing remains valid at any coverage level (C), and the gap says nothing about dead code (D).
Question 29
A flaky test fails only when run in the full suite but passes in isolation. The test
relies on a module-level mutable list that another test mutates. Which fix best
addresses the root cause?
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.