




















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 with Answers and Detailed Rationales
100 PERCENT GUARANTEED PASS
INSTANT DOWNLOAD ANSWERS INCLUDED
This comprehensive examination preparation guide has been meticulously developed to help you succeed in the WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING, ASSERTIONS, EXCEPTION HANDLING & REMEDIATION 2026. It contains 50 carefully selected questions that reflect the most current exam content and testing strategies. Each question is accompanied by a correct answer and a detailed rationale that explains the underlying pathophysiology, pharmacology, or clinical reasoning.
Self-Assessment – Test your knowledge and identify areas requiring further study
Exam Preparation – Familiarize yourself with the question format and content areas
Concept Reinforcement – Deepen your understanding through evidence-based rationales
Confidence Building – Develop test-taking strategies and reduce exam anxiety
Time Management – Practice answering questions under simulated exam conditions
Review Summary 50 Questions
Foundations - Application - WGU D385 TASK 1 Complete Guide Software Security & Testing Static Analysis Python Logging Assertions Exception Handling & Remediation 2026 Software Security & Testing Undergraduate YEAR 3 / Graduate All answers with rationales
Content Area Questions Key Topics
WGU D385 TASK 1 Complete Guide Software Security & Testing Static Analysis Python Logging Assertions Exception Handling & Remediation 2026 Software Security & Testing Undergraduate YEAR 3 / Graduate
1-9 Python, Exception, Security, Remediation, Analysis
Logging 10-18 Logger, Exception, Module, Remediation, Secure
Python 19-27 Autherror, Exception, Class, Tokenexpired, Logging
Remediation 28-36 Logging, Python, Security, Eliminating, Subprocess
Security 37-45 Exception, Level, Autherror, Cause, Coverage
Developer 46-50 Exception, Likely, Python Logging Configuration, Logging Configuration Prevents, Configuration Prevents Sensitive
TOTAL 50 All questions include answers and detailed rationales
Section A - WGU D385 TASK 1 Complete Guide Software Security & Testing Static Analysis Python Logging Assertions Exception Handling & Remediation 2026 Software Security & Testing Undergraduate YEAR 3 / Graduate```python
_assert user.is_authenticated, "User not authenticated"
_Which statement accurately describes a security implication of using this assertion for access control?_ A. Assertions are optimized away when Python runs with -O, potentially bypassing the check. B. Assertions raise AssertionError, which is a subclass of Exception and can be caught. C. Assertions should be used for input validation because they provide clear error messages. D. Assertions are thread-safe and cannot be disabled at runtime. Correct: A - Assertions are optimized away when Python runs with -O, potentially bypassing the check. Rationale:When Python is run with the -O flag, assert statements are removed, so security checks based on assertions can be silently skipped. Assertions are intended for debugging, not for enforcing security controls. The other options misstate assertion behavior. Q4. A developer writes a custom exception class that inherits from Exception but does not call super().__init__(). What is the most likely consequence when this exception is raised and logged? A. The exception message will be empty when str() is called on the instance. B. The exception will not be caught by except Exception clauses. C. The traceback will not include the original exception context. D. The exception will be automatically converted to a SystemExit. Correct: A - The exception message will be empty when str() is called on the instance. Rationale:Without calling super().__init__(), the base Exception class does not receive the message argument, so str(exception) returns an empty string. The exception is still catchable and traceback behavior is unaffected. It is not converted to SystemExit. Q5. During a static analysis review, a tool flags a potential path traversal in a file upload handler. Which remediation strategy most directly addresses the vulnerability at the source? A. Sanitize the filename by removing all non-alphanumeric characters. B. Use a whitelist of allowed file extensions and store files outside the web root. _Section A - WGU D385 TASK 1 Complete Guide Software Security & Testing Static Analysis Python Logging Assertions Exception Handling & Remediation 2026 Software Security & Testing Undergraduate YEAR 3 / Graduate_ C. Implement a Web Application Firewall (WAF) rule to block '../' sequences. D. Encode the filename using URL encoding before saving. Correct: B - Use a whitelist of allowed file extensions and store files outside the web root. Rationale:Storing files outside the web root and restricting extensions prevents traversal by design. Sanitizing by removing characters can break legitimate filenames and may still allow traversal. WAF and encoding are bypassable and do not fix the root cause. Q6. Which Python logging practice best supports the principle of least privilege when handling sensitive data? A. Log all user input at DEBUG level for troubleshooting. B. Use a filter to redact credit card numbers and passwords before logging. C. Store logs in a world-readable directory for easy access. D. Include full stack traces with local variables in error logs. Correct: B - Use a filter to redact credit card numbers and passwords before logging. Rationale:Redacting sensitive data via a logging filter prevents exposure while maintaining useful logs. Logging all input or including local variables can leak secrets. World-readable logs violate confidentiality. Q7. A team uses a static analysis tool that reports a high number of false positives. What is the most effective approach to improve the signal-to-noise ratio without missing critical vulnerabilities? A. Disable all rules that produce false positives. B. Tune rule thresholds and add suppressions with justifications for known false positives. C. Only run the tool on changed files in pull requests. D. Replace the tool with a dynamic analysis tool. Correct: B - Tune rule thresholds and add suppressions with justifications for known false positives. Rationale:Tuning rules and documenting suppressions reduces noise while preserving detection of real issues. Disabling rules outright may miss vulnerabilities. Running only on changed files may miss context. Dynamic analysis complements but does not replace static analysis. Section B - Logging #### Q10. Which of the following best describes the role of assertions in a secure software development lifecycle? A. Assertions should be used to enforce security invariants in production code. B. Assertions are primarily for internal consistency checks during development and testing. C. Assertions should replace exception handling for critical errors. D. Assertions are the preferred method for input validation in public APIs. Correct: B - Assertions are primarily for internal consistency checks during development and testing. Rationale:Assertions are designed for debugging and internal sanity checks, not for enforcing security in production because they can be disabled. They should not replace exception handling or input validation, which must always be active. Q11. A team runs Bandit on a module where `subprocess.Popen(user_input, shell=False)` is flagged as B602. The developer insists there is no injection risk because `shell=False`. Which analysis is most accurate? A. Correct - `shell=False` fully neutralizes command injection regardless of input. B. Incorrect - with `shell=False`, a string command still executes via the shell on POSIX. C. Partially correct - `shell=False` prevents shell metacharacter injection but a single string is treated as an executable path, so an attacker-controlled string can still invoke an arbitrary binary if it resolves. D. Bandit B602 is a false positive by definition; `shell=False` is always safe. Correct: C - Partially correct - `shell=False` prevents shell metacharacter injection but a single string is treated as an executable path, so an attacker-controlled string can still invoke an arbitrary binary if it resolves. Rationale:With `shell=False`, Python does not invoke `/bin/sh`, so metacharacters like `;` are not interpreted; however, passing a single string is treated as the program name, and attacker-controlled tokens can still select an unintended binary or argument. Bandit flags this as a latent risk. Option A overstates safety, B misstates shell behavior, and D is a blanket false claim. _Section B - Logging_ Q12. A logging configuration uses `logging.basicConfig(level=logging.INFO)` and later a module calls `logging.getLogger(__name__).debug('x')`. Why does the debug message not appear even though the module logger inherits from root? A. Child loggers do not inherit level from root; they default to WARNING. B. The effective level of the child logger is computed from its own level (NOTSET) walking up to root's INFO, so DEBUG is below the effective threshold and the record is dropped at the logger before reaching handlers. C. basicConfig only configures the root handler, not the logger hierarchy, so child loggers are silently disabled. D. DEBUG records are always filtered by the `logging.lastResort` handler regardless of configuration. Correct: B - The effective level of the child logger is computed from its own level (NOTSET) walking up to root's INFO, so DEBUG is below the effective threshold and the record is dropped at the logger before reaching handlers. Rationale:Effective level is resolved by walking the hierarchy when a logger's level is NOTSET; root is INFO, so the child's DEBUG call is filtered at the logger. Handlers also have levels, but the drop here occurs at the logger. Options A and C misstate inheritance; D confuses lastResort, which only applies when no handlers exist. Q13. In a pytest suite, `assert response.json()['user']['id'] == expected` fails with a KeyError rather than an assertion failure. Which remediation best preserves test intent and diagnosability? A. Wrap the call in `try/except KeyError: pytest.fail()` with no message. B. Replace with `assert response.json().get('user', {}).get('id') == expected` so a missing key yields a clean assertion diff. C. Add `pytestmark = pytest.mark.filterwarnings('ignore')` to suppress the error. D. Convert to `assert expected in response.json()` to avoid indexing. Correct: B - Replace with `assert response.json().get('user', {}).get('id') == expected` so a missing key yields a clean assertion diff. Rationale:Using `.get` chains converts a missing-key crash into a boolean assertion whose diff shows actual vs expected, preserving intent and diagnostics. Option A discards the value diff, C is unrelated to exceptions, and D weakens the assertion so it no longer verifies the id value. _Section B - Logging_ A. Using `assert` for type narrowing inside a function body. B. Using `assert user.is_admin` as an authorization gate, because `assert` statements are stripped when Python runs with `-O`. C. Using `assert` inside unit tests to validate outputs. D. Using `assert` to validate constant invariants at import time. Correct: B - Using `assert user.is_admin` as an authorization gate, because `assert` statements are stripped when Python runs with `-O`. Rationale:`assert` is removed under `python -O`, so authorization checks silently vanish in optimized deployments, enabling privilege escalation. Options A, C, and D are legitimate uses that do not create production security gaps. Q17. A remediation ticket requires converting a `try/except Exception: pass` block around a crypto verification call. Which refactor best aligns with secure remediation principles? A. Catch `Exception`, log at DEBUG, and continue. B. Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller. C. Remove the try/except entirely so the process crashes on any error. D. Catch `BaseException` to also handle `KeyboardInterrupt` and `SystemExit`. Correct: B - Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller. Rationale:Fail-closed behavior with specific exception handling preserves security guarantees while providing diagnostics. Option A silently continues on verification failure (fail-open), C removes control over error signaling, and D improperly catches system-level exceptions. Q18. Which statement about `logger.exception()` versus `logger.error()` inside an `except` block is most accurate for security incident forensics? A. They are identical; both include the traceback. B. `logger.exception()` automatically includes the active exception traceback, while `logger.error()` includes it only if `exc_info=True` is passed. C. `logger.error()` includes the traceback; `logger.exception()` does not. D. Neither includes the traceback; `traceback.print_exc()` is required. Correct: B - `logger.exception()` automatically includes the active exception traceback, _Section B - Logging while `logger.error()` includes it only if `exc_info=True` is passed._ Rationale:`logger.exception` is shorthand for `logger.error(..., exc_info=True)`, capturing the traceback for forensic reconstruction. Options A, C, and D misstate this behavior and would degrade incident analysis. _Section C - Python_ A. Bandit's B608 plugin only matches AST JoinedStr nodes, so percent-formatting with a tuple bypasses the pattern because the resulting string is constructed at runtime, not in the AST. B. Bandit performs taint tracking of the tuple elements and correctly determines that parameterized placeholders are safe, while f-strings introduce a taint source. C. Bandit treats all string concatenation as safe by default and only flags f-strings because they are a newer Python syntax that the tool has not yet whitelisted. D. Bandit's B608 is a false positive on f-strings and the correct remediation is to disable B608 and rely on a runtime WAF instead. Correct: A - Bandit's B608 plugin only matches AST JoinedStr nodes, so percent-formatting with a tuple bypasses the pattern because the resulting string is constructed at runtime, not in the AST. Rationale:Bandit's SQL-injection check is a syntactic pattern match on AST nodes; f-strings produce JoinedStr nodes containing FormattedValue, which the plugin flags, whereas '%s' formatting with a tuple is a BinOp/Mod expression that the plugin does not match. Bandit does not perform interprocedural taint tracking for this rule, so option B overstates its capability. Option C mischaracterizes the rule's design, and option D is incorrect because parameterization is the correct remediation, not disabling the check. Q22. In a structlog-based service, a developer configures structlog.configure with a ProcessorFormatter that wraps the stdlib logging root handler. Which configuration error most likely causes structured key-value pairs to appear as a single opaque string in downstream JSON logs? A. Setting structlog.processors.KeyValueRenderer as the final processor instead of JSONRenderer, so the event dict is stringified before the stdlib formatter serializes it. B. Omitting structlog.stdlib.add_log_level from the processor chain, causing the formatter to fall back to repr() of the event dict. C. Using structlog.stdlib.ProcessorFormatter .wrap_for_formatter without setting the foreign_pre_chain, which forces the stdlib formatter to escape the dict. D. Configuring the root logger with a plain logging.Formatter instead of ProcessorFormatter, so structlog's event dict is rendered by str() rather than serialized as JSON. Correct: D - Configuring the root logger with a plain logging.Formatter instead of ProcessorFormatter, so structlog's event dict is rendered by str() rather than serialized as JSON. _Section C - Python_ Rationale: ProcessorFormatter is required to convert structlog's event dict into a serializable payload; if the root handler uses a plain logging.Formatter, the dict is coerced via str() and appears as an opaque Python dict literal. Option A is wrong because KeyValueRenderer still produces structured (though non-JSON) output and does not cause a single opaque string. Option B is incorrect because add_log_level affects the level field, not dict serialization. Option C misstates the role of foreign_pre_chain, which only affects records originating from stdlib loggers. Q23. A test suite uses pytest with `assert` statements under `-O` optimization. Which statement best characterizes the risk of relying on bare `assert` for security-critical input validation in production code? A. Bare asserts are always executed in production, so the risk is limited to performance overhead rather than correctness. B. Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed. C. Bare asserts raise AssertionError, which is a subclass of Exception and will be caught by a broad `except Exception` handler, masking the failure. D. Bare asserts are compiled to bytecode that cannot be optimized away, but they are unsuitable because they cannot include custom messages. Correct: B - Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed. Rationale:CPython removes assert statements when run with -O (and -OO), so any validation implemented solely with assert is not enforced in optimized builds, a classic security anti-pattern. Option A is the opposite of the truth. Option C is true about AssertionError's hierarchy but does not address the -O stripping risk. Option D is incorrect because asserts can include messages and are indeed optimized away. Q24. Which exception-handling pattern best avoids both swallowing security-relevant failures and leaking sensitive data in logs when calling an external authentication API? A. `except Exception as e: logging.error(f"auth failed: {e}"); return False` B. `except Exception: pass` followed by a generic failure response to the caller C. `except (requests.Timeout, requests.ConnectionError) as e: logging.warning("auth transport error", exc_info=True); raise AuthUnavailable from e` D. `except BaseException as e: logging.critical(str(e)); sys.exit(1)` Correct: C - `except (requests.Timeout, requests.ConnectionError) as e: _Section C - Python_ Rationale: Library code should never call basicConfig because it mutates global logging state, sets a verbose level, and may add a handler before the application configures logging, causing duplicate or leaked output. Option B is misleading: basicConfig is a no-op only if the root logger already has handlers, but the side effect of setting level still occurs in some Python versions and the call is still an anti-pattern. Option C is false; there is no such circular import. Option D is incorrect because basicConfig does not disable propagation. Q27. Consider a custom exception hierarchy where `class AuthError(Exception)` and `class TokenExpired(AuthError)`. A handler is written as `except AuthError: ... except TokenExpired: ...`. What is the behavioral consequence? A. TokenExpired is caught by the first clause, so the second clause is unreachable; the order must be reversed to handle the subclass specifically. B. Python matches the most specific exception first regardless of clause order, so both clauses work as intended. C. A SyntaxError is raised at import time because subclass clauses must precede superclass clauses. D. Both clauses execute in sequence, allowing layered handling of the same exception. Correct: A - TokenExpired is caught by the first clause, so the second clause is unreachable; the order must be reversed to handle the subclass specifically. Rationale:Python evaluates except clauses top to bottom and selects the first matching class, so the AuthError clause captures TokenExpired and makes the second clause dead code. Option B is false; Python does not reorder clauses. Option C is false; this is a logic error, not a syntax error. Option D is false; only one except clause runs per exception. Section D - Remediation #### Q28. A team adopts `python -X dev` and `PYTHONDEVMODE=1` in CI. Which combination of effects most accurately describes what this enables for security and testing? A. It enables assertions, disables bytecode caching, and turns DeprecationWarnings into errors, but it does not affect exception chaining. B. It enables the default warning filter to show DeprecationWarning, activates the debug allocator, and enables faulthandler, improving detection of resource and memory issues. C. It disables the GIL for concurrency testing and enables audit hooks for all syscalls. D. It runs the interpreter in a sandboxed mode that blocks network access unless explicitly allowed. Correct: B - It enables the default warning filter to show DeprecationWarning, activates the debug allocator, and enables faulthandler, improving detection of resource and memory issues. Rationale:Python's development mode (-X dev / PYTHONDEVMODE) enables the default warning filter (showing DeprecationWarning), the debug memory allocator, and faulthandler, which together surface latent defects. Option A overstates the effect on assertions and bytecode caching (dev mode does not strip or enable asserts in that sense). Option C is false; the GIL is not disabled by dev mode, and audit hooks are separate. Option D is false; dev mode is not a sandbox. Q29. A remediation ticket requires eliminating a `eval()` call used to parse configuration. Which replacement best preserves the intended expressiveness while eliminating arbitrary code execution? A. `ast.literal_eval` on the raw string, which parses only Python literals. B. `exec` inside a restricted namespace with `__builtins__` set to None. C. `pickle.loads` on the string after base64-decoding it. D. `compile(source, '', 'eval')` followed by `eval(code, {})`. Correct: A - `ast.literal_eval` on the raw string, which parses only Python literals. Rationale:ast.literal_eval safely evaluates only literal structures (strings, numbers, tuples, lists, dicts, booleans, None) and raises ValueError on other nodes, eliminating code execution. Option B is a known-unsafe pattern because restricted namespaces are bypassable. Option C introduces deserialization RCE. Option D still calls eval and offers no safety. _Section D - Remediation_ Q32. In a Python service, `logging.basicConfig(level=logging.INFO)` is called in the library package, and then the application calls `basicConfig(level=logging.DEBUG)`. DEBUG messages never appear. What is the root cause? A. `basicConfig` is idempotent; the second call is a no-op because the root logger already has a handler. B. The root logger level was set to INFO and cannot be lowered at runtime. C. DEBUG records are filtered by the default `lastResort` handler before propagation. D. Library loggers set `propagate=False`, isolating their records from the root handler. Correct: A - `basicConfig` is idempotent; the second call is a no-op because the root logger already has a handler. Rationale:basicConfig only configures the root logger if it has no handlers; the second invocation is silently ignored, leaving level at INFO. Levels are mutable (B is false), lastResort only fires when no handler exists (C), and propagate defaults to True absent explicit override (D). Q33. A developer writes `assert user.is_admin, 'denied'` to gate a privileged operation, and the code is deployed with `python -O`. Which statement about the resulting security posture is most accurate? A. The assertion still raises AssertionError but with a generic message. B. The assertion is removed entirely, so the gate never executes and all users pass. C. The assertion is converted into a warning logged to stderr. D. The assertion raises RuntimeError instead of AssertionError under -O. Correct: B - The assertion is removed entirely, so the gate never executes and all users pass. Rationale:Under -O, the compiler strips assert statements, so the authorization check vanishes and the privileged path executes unconditionally - a classic reason assertions must never enforce security. Options A, C, and D misstate Python's documented optimization semantics. Q34. A function calls `int(user_input)` inside a loop that also opens a file. Reviewers want file handles always closed and only conversion errors surfaced to the caller. Which construct best satisfies both requirements simultaneously? A. try/except ValueError around the loop with a finally block that closes the file. B. A bare `except:` inside the loop that logs and continues. _Section D - Remediation_ C. with open(...) as f: inside a try that catches ValueError and re-raises. D. try/except/else with `else` closing the file and `finally` converting input. Correct: C - with open(...) as f: inside a try that catches ValueError and re-raises. Rationale:A context manager guarantees deterministic file closure even on exceptions, and catching/re-raising ValueError preserves the intended error contract. Option A risks leaking the handle on non-ValueError paths, B swallows all errors including KeyboardInterrupt, and D inverts the semantics of else/finally. Q35. A SAST tool flags a taint path from `request.args` to `cursor.execute(query)`. The developer refactors to use parameterized queries but the finding persists. Which explanation for the persistent finding is most technically sound? A. Parameterization only prevents SQL injection in PostgreSQL, not SQLite. B. The taint engine tracks data flow to the sink regardless of whether the sink is safe, so the rule must be refined or the sink annotated. C. Parameterized queries still concatenate strings internally, so the taint is genuine. D. The scanner requires the parameter list to be a literal tuple to clear taint. Correct: B - The taint engine tracks data flow to the sink regardless of whether the sink is safe, so the rule must be refined or the sink annotated. Rationale:Many taint analyses are flow-sensitive but not sanitizer-aware; without modeling parameterization as a sanitizer or annotating the sink, the flow remains flagged though the code is safe. A, C, and D mischaracterize how parameterization and taint engines actually behave. Q36. A remediation plan must prioritize three findings: (1) hardcoded AWS secret in source, (2) reflected XSS in a search page, (3) verbose stack traces returned to clients. Using CVSS-based risk and exploitability, which prioritization is most defensible? A. 3, then 1, then 2 - information disclosure always dominates. B. 1, then 2, then 3 - credential exposure enables full compromise; XSS enables session theft; stack traces are lower severity. C. 2, then 3, then 1 - client-facing flaws always rank highest. D. All three are equal severity and should be fixed in code-commit order. Correct: B - 1, then 2, then 3 - credential exposure enables full compromise; XSS enables session theft; stack traces are lower severity.