





















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 Apply static analysis tools to detect security vulnerabilities in source code
2 Implement effective logging and assertion strategies for debugging and security monitoring
3 Design robust exception handling and remediation plans for common software weaknesses
4 WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis
5 Python Logging
6 Assertions
7 Exception Handling & Remediation 2026
8 Foundations of Software Security & Testing
9 Applied Software Security & Testing
10 Advanced Software Security & Testing
11 Software Security & Testing Review
This study document brings together 50 carefully worded exam questions drawn from WGU D Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Python Logging, Assertions, Exception Handling & Remediation 2026, with the strongest emphasis placed on Apply static analysis tools to detect security vulnerabilities in source code, Implement effective logging and assertion strategies for debugging and security monitoring and Design robust exception handling and remediation plans for common software weaknesses. 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. Replace string formatting with parameterized queries using the database driver's placeholder syntax. CORRECT
B. Sanitize all user inputs by escaping single quotes and semicolons before concatenation.
C. Implement a web application firewall (WAF) rule to block SQL injection patterns.
D. Use an ORM exclusively for all database interactions without reviewing generated SQL.
RATIONALE: Parameterized queries separate SQL logic from data, preventing injection by design. Escaping is error-prone and bypassable; WAFs are defense-in-depth but not a fix; ORMs can still be misused and may not cover all cases.
A. Set the logging level to ERROR and use a FileHandler with a formatter that includes %(exc_info)s.
B. Use a try-except block that calls logging.exception() within the except clause, with a FileHandler configured. CORRECT
C. Configure a SMTPHandler to email logs on exceptions and a FileHandler for all levels.
D. Use logging.basicConfig(filename='app.log', level=logging.CRITICAL) and call logging.critical() in except blocks.
RATIONALE: logging.exception() automatically logs an ERROR-level message with exception information. Option A would log all errors, not just exceptions; C sends emails; D only logs critical messages and misses stack traces unless explicitly passed.
A. False positive: flagging a non-issue; false negative: missing a real issue. False negatives are more dangerous as they leave vulnerabilities undetected. CORRECT
B. False positive: missing a real issue; false negative: flagging a non-issue. False positives are more dangerous as they cause alert fatigue.
C. False positive: flagging a non-issue; false negative: missing a real issue. False positives are more dangerous as they waste developer time.
D. False positive: incorrect severity rating; false negative: incorrect location. Both are equally dangerous.
RATIONALE: False positives are incorrect warnings; false negatives are missed vulnerabilities. False negatives are more dangerous because they allow exploits to remain. The other options misdefine the terms or prioritize incorrectly.
A. StreamHandler with a simple message format to console for real-time monitoring.
B. RotatingFileHandler with a detailed format including timestamp, log level, module, and process ID. CORRECT
C. SysLogHandler sending logs to a remote syslog server with default formatting.
D. MemoryHandler buffering logs and flushing only on critical errors.
RATIONALE: RotatingFileHandler preserves logs with rotation, and detailed formatting aids forensics. Console logging is ephemeral; syslog may lack detail; MemoryHandler may lose logs on crash.
A. Catching specific exceptions like ValueError and returning a generic error message.
B. Using a bare except: clause that swallows all exceptions and continues execution. CORRECT
C. Logging exceptions with logging.exception() and re-raising them.
D. Using finally blocks to release resources such as database connections.
RATIONALE: Bare excepts can hide critical errors, leading to inconsistent state and potential security bypasses. The other options are good practices or less risky.
A. Use os.path.basename() on the user-supplied filename before constructing the path.
B. Validate the filename against a whitelist of allowed filenames.
C. Use os.path.realpath() to resolve the absolute path and ensure it starts with the intended base directory. CORRECT
D. Encode the filename using URL encoding before use.
RATIONALE: realpath() canonicalizes the path, preventing traversal outside the base directory. basename() may not handle all cases; whitelisting is good but less general; URL encoding does not prevent traversal.
A. Add '# nosec' with a comment documenting the allowlist validation.
B. Convert the f-string to a parameterized query using the DB-API placeholder style. CORRECT
C. Replace the f-string with str.format() and pass the variable as a format argument.
D. Wrap the query execution in a try/except and log the SQLException on failure.
RATIONALE: Bandit's B608 flags string-formatted SQL regardless of upstream validation; the canonical fix is parameterization, which separates code from data and satisfies the analyzer. Suppressing with '# nosec' (A) hides the issue without fixing it, str.format (C) is still string interpolation flagged by B608, and try/except (D) addresses error handling, not injection.
A. logger.exception should be logger.error because no exception is active in the handler.
B. SystemExit should be replaced with sys.exit(1) for portability across platforms.
C. Re-raising SystemExit masks the original exception's traceback and prevents upstream recovery. CORRECT
D. Catching both ValueError and TypeError violates the single-responsibility principle.
RATIONALE: SystemExit is not a subclass of Exception and terminates the interpreter, discarding the chained traceback and preventing callers from handling the original error; use bare 'raise' or a custom exception. logger.exception is correct inside an except block (A), sys.exit raises SystemExit identically (B), and grouping exception types is idiomatic (D).
A. The logger's propagate flag is True and a parent logger also has a RotatingFileHandler attached. CORRECT
B. The StreamHandler level is set to WARNING while the RotatingFileHandler level is DEBUG.
C. The formatter uses %(message)s without a timestamp, causing apparent duplicates.
D. The RotatingFileHandler maxBytes is smaller than the burst size, triggering rotation mid-write.
RATIONALE: Duplicate records typically arise when a record propagates to an ancestor logger that also has a handler writing to the same destination; setting propagate=False or attaching handlers only at the root fixes it. Level mismatches (B) change filtering, not duplication, formatting (C) cannot duplicate lines, and rotation (D) does not duplicate records.
A. The assertion still executes and raises AssertionError with the message.
B. The assertion is stripped entirely, and payload is never validated. CORRECT
C. The assertion executes but the message expression is skipped for performance.
D. The assertion raises a RuntimeError instead of AssertionError under -O.
RATIONALE: Under -O (and PYTHONOPTIMIZE), the compiler removes assert statements and their message expressions entirely, so validation silently disappears - a classic rationale for never using asserts for runtime input validation. The other options misstate the optimizer's effect on asserts.
A. Add '# pylint: disable=broad-except' on the line and document the rationale. CORRECT
B. Change to 'except BaseException' to avoid the warning.
C. Remove the handler and rely on the default excepthook for logging.
D. Refactor to catch (Exception,) as a tuple to satisfy the checker.
RATIONALE: Targeted suppression with a documented justification is the accepted way to handle intentional broad catches at process boundaries. BaseException (B) is broader and worse, removing the handler (C) loses context, and (Exception,) (D) is functionally identical and still triggers W0703.
A. str(exc) returns 'bad' and exc.cause is the KeyError instance. CORRECT
B. str(exc) returns '(42, "bad")' because init overrides the message.
C. exc.context is None because 'from' clears the implicit context.
D. The KeyError is discarded because AuditError is not a subclass of it.
RATIONALE: super().init(msg) sets the args so str(exc) yields 'bad', and 'raise ... from ...' explicitly sets cause to the KeyError. Option B misstates args handling, C confuses context (still set) with cause, and D ignores chaining semantics.
A. isinstance is too slow for security checks and should use type() instead.
B. Asserts can be disabled with -O, so the authorization check may vanish in production. CORRECT
C. Admin is a subclass of User, so isinstance returns False and blocks access.
D. The assert raises AssertionError, which is not a subclass of Exception.
RATIONALE: Using assert for authorization is unsafe because the -O flag strips asserts, silently removing the check; explicit if/raise is required. Speed (A), subclass direction (C), and AssertionError's hierarchy (D, it is a subclass of Exception) are all incorrect.
A. Pass shell=False and provide the command as a list of arguments. CORRECT
B. Escape shell metacharacters in the input before concatenation.
C. Set a strict timeout on subprocess.run to limit damage.
D. Redirect stderr to DEVNULL to prevent error-based leakage.
RATIONALE: Using shell=False with an argument list bypasses the shell entirely, so metacharacters cannot be interpreted - the canonical fix. Escaping (B) is fragile and context-dependent, timeouts (C) do not prevent injection, and stderr redirection (D) is orthogonal to injection.
A. Use assert; it is stripped under -O, so it must not guard security-critical or user-input validation. CORRECT
B. Use assert; it remains active under -O and is the preferred runtime input validator.
C. Use a custom exception; assert is always stripped in all CPython modes.
D. Use assert with a message; -O converts failures to warnings instead of raising.
RATIONALE: assert is intended for internal invariants and is removed when optimizations disable it (python -O), so it must never enforce security or input validation. It is not converted to warnings, and it is not stripped in normal execution. Custom exceptions are used for recoverable or externally triggered errors, not for invariants expected to hold.
A. Catch Exception broadly and re-raise a new RuntimeError to unify error types.
B. Separate except clauses: handle ValueError with user feedback and OSError with retry/backoff, logging each with exc_info=True. CORRECT
C. Remove the try block and let exceptions propagate to the top-level handler only.
D. Catch BaseException to ensure no failure escapes, then log and continue.
RATIONALE: Distinct exception types signal different recovery strategies, so separate handlers with exc_info=True preserve the traceback and enable targeted logic. Catching Exception or BaseException erases type information and can swallow KeyboardInterrupt/SystemExit. Removing handling entirely forfeits the opportunity for user feedback and retry.
A. Ignore it because exploitability is the only criterion for remediation.
B. Pin the vulnerable version and add a suppression with no expiry.
C. Triage with reachability and exploitability context, apply a compensating control or upgrade, and record a time-boxed, documented exception if deferring. CORRECT
D. Fork the dependency and patch silently without notifying upstream.
RATIONALE: Modern practice combines reachability/exploitability triage with compensating controls and time-boxed, documented exceptions to manage risk transparently. Permanent suppressions or ignoring based solely on claimed non-exploitability bypass governance. Silent forks create maintenance and disclosure burdens without addressing upstream risk.
A. with self.assertRaises(KeyError):
B. with self.assertRaises(ConfigError): CORRECT
C. with self.assertRaises(Exception):
D. with self.assertRaisesRegex(KeyError, 'missing'):
RATIONALE: Asserting the specific ConfigError type captures the refined contract and will fail if the type regresses to a bare KeyError. Asserting KeyError passes for the subclass, masking the intended specificity, while Exception is too broad. assertRaisesRegex on KeyError still under-specifies the type.
A. Upgrade in production first to validate quickly, then adjust tests.
B. Pin the old version indefinitely and accept the vulnerability.
C. Upgrade in a branch, run the full test suite and SAST/SCA gates, adapt call sites, then stage the rollout. CORRECT
D. Vendor the old code and remove the dependency manager.
RATIONALE: A controlled branch upgrade with full test, SAST, and SCA gates validates both functional and security impacts before rollout. Upgrading in production first exposes users to regressions, and indefinite pinning leaves the vulnerability unaddressed. Vendoring shifts maintenance burden without fixing the flaw.
A. The handler catches ValidationError because it is a subclass of AppError. CORRECT
B. The handler does not catch ValidationError because only exact type matches are caught.
C. The handler catches it only if ValidationError is listed first in the except tuple.
D. The handler catches it only if AppError is also raised in the same try block.
RATIONALE: Python's except matches subclasses, so catching AppError also catches ValidationError and NotFoundError. Exact-type matching is not required, and ordering within a single except clause is irrelevant here. The presence of other raises in the block does not affect matching.
A. Wrap the call in try/except and log the exception
B. Replace shell=True with shell=False and pass an argument list (e.g., shlex.split or explicit list) CORRECT
C. Add # nosec to suppress the finding
D. URL-encode the config values before interpolation
RATIONALE: shell=True invokes the shell, so metacharacters in cmd become injectable; passing an argument list with shell=False (or shlex.split) prevents shell interpretation. try/except, # nosec, and URL-encoding do not remove the shell parsing vulnerability.
A. The token is logged because basicConfig overrides the logger's effective level
B. The message is not emitted because DEBUG < INFO, so the token is not written to the log CORRECT
C. The message is emitted but the token is masked by the logging module
D. The message is emitted at WARNING level due to level coercion
RATIONALE: The root logger's effective level is INFO, so DEBUG records are filtered before emission; the token is not logged. The logging module does not mask secrets, does not coerce levels, and basicConfig does not force DEBUG emission.
A. Escape single quotes in q before concatenation
B. Use a parameterized query with a placeholder and pass q as a bound parameter CORRECT
C. Cast q to int before concatenation
D. Add a WAF rule blocking SQL keywords
RATIONALE: Parameterized queries separate code from data and eliminate the taint flow regardless of input content. Escaping, casting, and WAF rules are partial mitigations that fail for non-integer or encoded payloads and do not address the root cause.
A. Parametrize runs the same assertion on fixed inputs; property-based tests generate inputs and check invariants CORRECT
B. Parametrize is only for performance tests
C. Property-based tests require a database fixture
D. Parametrize cannot assert on exceptions
RATIONALE: Parametrize enumerates explicit cases, while property-based frameworks (e.g., Hypothesis) generate inputs to falsify invariants, often finding edge cases. The other options misstate pytest capabilities.
A. Use a single FileHandler with default buffering
B. Use a RotatingFileHandler with a small maxBytes
C. Use a QueueHandler feeding a single logging process/thread that owns the file CORRECT
D. Set logging.raiseExceptions = False
RATIONALE: A QueueHandler with a dedicated consumer serializes writes, avoiding interleaving and loss across processes. RotatingFileHandler does not coordinate processes, default buffering can interleave, and raiseExceptions only affects error reporting.
A. Replace with except Exception: continue
B. Catch specific exceptions, log with structured context, and re-raise or abort the operation CORRECT
C. Wrap the call in a retry loop with no logging
D. Convert the bare except to except BaseException: pass
RATIONALE: Fail-closed requires catching specific exceptions, recording auditable context, and aborting or re-raising rather than silently continuing. The other options either swallow errors, broaden the catch, or omit logging, all weakening security posture.