Docsity

WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Pyth, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE
SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,
ASSERTIONS, EXCEPTION HANDLING & REMEDIATION 2026
50 QUESTIONS
TABLE OF CONTENTS
# 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
ABSTRACT
This study document brings together 50 carefully worded exam questions drawn from WGU D385
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Pyth and more Exams Computer Security in PDF only on Docsity!

WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE

SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,

ASSERTIONS, EXCEPTION HANDLING & REMEDIATION 2026

50 QUESTIONS

TABLE OF CONTENTS

# 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

ABSTRACT

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.

Q1 APPLY STATIC ANALYSIS TOOLS TO DETECT SECURITY VULNERABILITIES IN SOURCE

CODE

A static analysis tool reports a potential SQL injection vulnerability in a Python

function that constructs a query using string formatting. Which remediation

strategy best addresses the root cause while maintaining functionality?

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.

Q2 APPLY STATIC ANALYSIS TOOLS TO DETECT SECURITY VULNERABILITIES IN SOURCE

CODE

In Python's logging module, which configuration ensures that log records are

written to a file only when an exception occurs, while still capturing full stack

traces?

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.

Q5 APPLY STATIC ANALYSIS TOOLS TO DETECT SECURITY VULNERABILITIES IN SOURCE

CODE

In the context of static analysis, what distinguishes a false positive from a false

negative, and which is more dangerous from a security perspective?

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.

Q6 IMPLEMENT EFFECTIVE LOGGING AND ASSERTION STRATEGIES FOR DEBUGGING AND

SECURITY MONITORING

When using Python's logging module, which handler and formatter combination

best supports forensic analysis after a security incident?

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.

Q7 IMPLEMENT EFFECTIVE LOGGING AND ASSERTION STRATEGIES FOR DEBUGGING AND

SECURITY MONITORING

Which exception handling anti-pattern is most likely to introduce a security

vulnerability in a Python web application?

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.

Q8 IMPLEMENT EFFECTIVE LOGGING AND ASSERTION STRATEGIES FOR DEBUGGING AND

SECURITY MONITORING

A static analysis tool flags a potential path traversal vulnerability in a Python file

download function. Which code change effectively remediates this?

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.

Q11 DESIGN ROBUST EXCEPTION HANDLING AND REMEDIATION PLANS FOR COMMON

SOFTWARE WEAKNESSES

A security engineer runs Bandit on a Python module and receives a B

(hardcoded_sql_expressions) finding for a query built with an f-string that

interpolates a variable validated by a strict regex allowlist. Which remediation best

preserves functionality while eliminating the finding?

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.

Q12 DESIGN ROBUST EXCEPTION HANDLING AND REMEDIATION PLANS FOR COMMON

SOFTWARE WEAKNESSES

A developer writes: try: risky(); except (ValueError, TypeError):

logger.exception('failed'); raise SystemExit(1). During review, a senior engineer

objects. Which critique is most accurate?

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).

Q13 DESIGN ROBUST EXCEPTION HANDLING AND REMEDIATION PLANS FOR COMMON

SOFTWARE WEAKNESSES

A team configures Python logging with dictConfig using a RotatingFileHandler

and a StreamHandler sharing one logger. During a burst of warnings, duplicate

lines appear in the file but not on the console. Which configuration error most

likely explains this?

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.

Q14 DESIGN ROBUST EXCEPTION HANDLING AND REMEDIATION PLANS FOR COMMON

SOFTWARE WEAKNESSES

Consider this assertion: assert validate(payload), f'invalid: {payload}'. A

production deployment runs with python -O. Which statement about behavior is

correct?

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.

Q17 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

A CI pipeline fails because pylint emits W0703 (broad-except) on a handler that

intentionally catches all exceptions to log and re-raise. Which action best aligns

with secure-coding best practice?

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.

Q18 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

A module defines class AuditError(Exception) with init(self, code, msg) that

calls super().init(msg) and sets self.code. A caller does 'raise AuditError(42,

"bad") from KeyError("k")'. Which statement about the resulting exception is

correct?

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.

Q19 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

A reviewer sees: 'assert isinstance(user, Admin)'. The code then calls

user.delete_all(). Which statement best explains why this pattern is a security

weakness?

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.

Q20 WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING

STATIC ANALYSIS

A team must remediate a SAST finding on a subprocess call built from user input.

Which remediation most directly eliminates the injection class while preserving

functionality?

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.

Q23 PYTHON LOGGING

Which assertion is appropriate for validating an internal invariant whose violation

indicates a programming error, and how should it behave under python -O?

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.

Q24 PYTHON LOGGING

A function raises ValueError for malformed input and OSError for I/O failures. A

caller wraps it in try/except (ValueError, OSError) as e: log and re-raise. Which

refactor best preserves diagnostic fidelity while enabling targeted recovery?

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.

Q25 PYTHON LOGGING

A pipeline fails security gates on a medium-severity finding in a dependency. The

team argues it is not exploitable in their usage. Which remediation decision best

aligns with modern supply-chain risk management?

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.

Q26 ASSERTIONS

A test asserts that a function raises KeyError for a missing key. The

implementation was changed to raise a custom ConfigError(KeyError). Which

assertion most robustly encodes the intended contract?

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.

Q29 ASSERTIONS

A remediation plan upgrades a library with a breaking API change. Which

approach best balances security and delivery risk?

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.

Q30 ASSERTIONS

A module defines a custom exception hierarchy: AppError(Exception),

ValidationError(AppError), and NotFoundError(AppError). A caller uses except

AppError as e. Which behavior is expected when a ValidationError is raised?

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.

Q31 EXCEPTION HANDLING & REMEDIATION 2026

A team runs Bandit on a Python module and it flags `subprocess.Popen(cmd,

shell=True)in a function wherecmd` is assembled from a config file. Which

remediation most directly eliminates the injection class while preserving the ability

to pass arguments?

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.

Q32 EXCEPTION HANDLING & REMEDIATION 2026

A developer configures logging.basicConfig(level=logging.INFO) and then calls

logging.debug('token=%s', token) in a hot path. Which statement about runtime

behavior and security is most accurate?

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.

Q35 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A SAST tool reports a taint flow from request.args.get('q') to

cursor.execute('SELECT * FROM t WHERE c = ' + q). Which fix is the strongest

remediation according to secure coding standards?

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.

Q36 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A pytest suite uses @pytest.mark.parametrize to test a sanitizer. Which property

best distinguishes a unit test from a property-based test in this context?

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.

Q37 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A logging handler writes to a file shared by multiple processes. Which

configuration most reliably prevents interleaved or lost records under concurrent

writes?

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.

Q38 FOUNDATIONS OF SOFTWARE SECURITY & TESTING

A security review finds except: pass around a crypto operation. Which

remediation best aligns with fail-closed design and auditability?

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.