Docsity

WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python, Exams of Computer Security

Toggle sidebar
bg1
WGU D385 SOFTWARE SECURITY AND TESTING STATIC
CODE ANALYSIS & FLAKE8 PRACTICE LAB PYTHON
SECURITY, LOGGING, TESTING & REMEDIATION 2026
50 Questions with Answers and Detailed Rationales
100 PERCENT GUARANTEED PASS
INSTANT DOWNLOAD ANSWERS INCLUDED
IMPORTANCE OF THIS DOCUMENT
This comprehensive examination preparation guide has been meticulously developed to help you succeed in the
WGU D385 SOFTWARE SECURITY AND TESTING STATIC CODE ANALYSIS & FLAKE8 PRACTICE LAB
PYTHON SECURITY, LOGGING, TESTING & 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 Software Security AND Testing Static CODE Analysis & Flake8
LAB Python Security Logging Testing & Remediation 2026 Software Security AND Testing Static CODE
Analysis Flake8 Python Security Logging Testing & Remediation Undergraduate YEAR 3 / Graduate
All answers with rationales
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python and more Exams Computer Security in PDF only on Docsity!

WGU D385 SOFTWARE SECURITY AND TESTING STATIC

CODE ANALYSIS & FLAKE8 PRACTICE LAB PYTHON

SECURITY, LOGGING, TESTING & REMEDIATION 2026

50 Questions with Answers and Detailed Rationales

100 PERCENT GUARANTEED PASS

INSTANT DOWNLOAD ANSWERS INCLUDED

IMPORTANCE OF THIS DOCUMENT

This comprehensive examination preparation guide has been meticulously developed to help you succeed in the WGU D385 SOFTWARE SECURITY AND TESTING STATIC CODE ANALYSIS & FLAKE8 PRACTICE LAB PYTHON SECURITY, LOGGING, TESTING & 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 Software Security AND Testing Static CODE Analysis & Flake LAB Python Security Logging Testing & Remediation 2026 Software Security AND Testing Static CODE Analysis Flake8 Python Security Logging Testing & Remediation Undergraduate YEAR 3 / Graduate All answers with rationales

Table of Contents

Content Area Questions Key Topics

WGU D385 Software Security AND Testing Static CODE Analysis & Flake8 LAB Python Security Logging Testing & Remediation 2026 Software Security AND Testing Static CODE Analysis Flake8 Python Security Logging Testing & Remediation Undergraduate YEAR 3 / Graduate

1-9 Flake8, Remediation, Security, Python, Password

Security 10-18 Logging, Module, Function, Flags, Remediation

Logging 19-27 Remediation, Directly, Pipeline RUNS, Reports, Preserving

Bandit 28-36 Python, Security, Service, Configuration, Dependencies

Flake8 37-45 Bandit, Logging, Remediation, Flagged, Security

Developer 46-50 Application, Security, Hooks, Reliably Prevents SQL, Prevents SQL Injection

TOTAL 50 All questions include answers and detailed rationales

Section A - WGU D385 Software Security AND Testing Static CODE Analysis & Flake8 LAB Python Security Logging Testing & Remediation 2026 Software Security AND Testing Static CODE Analysis Flake8 Python Security Logging Testing & Remediation Undergraduate YEAR 3 / Q3. Which flake8 plugin combination best detects both style and security issues in Python code?

A. flake8-docstrings and flake8-import-order B. flake8-bugbear and flake8-comprehensions

C. flake8-bandit and flake8-bugbear D. flake8-annotations and flake8-quotes Correct: C - flake8-bandit and flake8-bugbear

Rationale:flake8-bandit integrates Bandit security checks; flake8-bugbear catches likely bugs. The others focus on style, documentation, or import ordering, not security.

Q4. A developer uses logging.info(f"User {user} logged in with password {password}"). What is the most critical security flaw?

A. Using f-strings instead of %-formatting causes performance overhead.

B. Logging at INFO level may be disabled in production.

C. Sensitive credentials are written to logs, risking exposure.

D. The log message lacks a timestamp and correlation ID. Correct: C - Sensitive credentials are written to logs, risking exposure.

Rationale:Logging passwords is a severe data leakage vulnerability. Performance (A) and log level (B) are secondary; missing metadata (D) is an audit concern, not the primary flaw.

Q5. Which testing approach is most effective for uncovering edge cases in a function that parses untrusted input?

A. Unit tests with mocked inputs B. Property-based testing with Hypothesis

C. Integration tests with a real database D. Manual exploratory testing Correct: B - Property-based testing with Hypothesis

Rationale:Property-based testing generates diverse inputs to find edge cases. Unit tests (A) may miss unexpected inputs; integration tests (C) focus on system interaction; manual testing (D) is not systematic.

Q6. A flake8 report shows F401 'module imported but unused' for the 'cryptography' module. What is the best remediation?

Section A - WGU D385 Software Security AND Testing Static CODE Analysis & Flake8 LAB Python Security Logging Testing & Remediation 2026 Software Security AND Testing Static CODE Analysis Flake8 Python Security Logging Testing & Remediation Undergraduate YEAR 3 /

A. Remove the import if truly unused. B. Add # noqa: F401 to suppress the warning.

C. Use the module in a dummy function to avoid the warning.

D. Move the import inside a function.

Correct: A - Remove the import if truly unused.

Rationale:Unused imports should be removed to reduce attack surface and improve clarity. Suppression (B) or dummy usage (C) hides the issue; moving the import (D) doesn't resolve unused status.

Q7. Which of the following is a secure way to handle password hashing in Python?

A. hashlib.md5(password.encode()).hexdige st()

B. hashlib.sha256(password.encode()).hexd igest()

C. bcrypt.hashpw(password.encode(), bcrypt.gensalt())

D. base64.b64encode(password.encode())

Correct: C - bcrypt.hashpw(password.encode(), bcrypt.gensalt())

Rationale:bcrypt is designed for password hashing with salt and work factor. MD5 (A) and SHA-256 (B) are fast and unsuitable; base64 (D) is encoding, not hashing.

Q8. In a CI/CD pipeline, which strategy best balances security and developer productivity when integrating static analysis?

A. Block all merges on any flake8 warning. B. Run flake8 only on changed files and fail on high-severity security issues.

C. Run flake8 nightly and email reports. D. Disable flake8 and rely on code reviews. Correct: B - Run flake8 only on changed files and fail on high-severity security issues.

Rationale:Incremental scanning with severity-based gating reduces noise while catching critical issues. Blocking all warnings (A) causes friction; nightly (C) delays feedback; disabling (D) removes automation.

Q9. Which Python logging practice best prevents log injection attacks?

A. Using f-strings to embed user input directly.

B. Sanitizing user input before logging and using structured logging.

Section B - Security

Q10.

A flake8-bandit report flags B303: use of insecure MD5. Which remediation is most appropriate?

A. Replace MD5 with SHA-1. B. Replace MD5 with SHA-256 for non-security checksums.

C. Replace MD5 with SHA-256 or better for security-sensitive hashing.

D. Add # nosec to suppress the warning.

Correct: C - Replace MD5 with SHA-256 or better for security-sensitive hashing.

Rationale:For security, use SHA-256 or stronger. SHA-1 (A) is also broken; SHA-256 for non-security (B) is acceptable but not for security; suppression (D) ignores the risk.

Q11. In a Flake8 plugin, a developer implements a check that flags any call to eval() as a security violation. Which AST traversal strategy most correctly ensures the check fires for eval() invoked indirectly through an alias such as from builtins import eval as e?

A. Match only ast.Call nodes whose func is an ast.Name with id 'eval'.

B. Resolve the Name id through the module's import bindings before comparing it to the canonical builtin name.

C. Use a regex over the raw source lines to detect the token 'eval('.

D. Flag any ast.Call whose func is an ast.Attribute regardless of the attribute name. Correct: B - Resolve the Name id through the module's import bindings before comparing it to the canonical builtin name.

Rationale:Aliasing rebinds the name, so matching only the literal id 'eval' misses aliased calls; resolving import bindings to the canonical builtin is required. Regex over source is brittle and ignores AST semantics, and flagging all Attribute calls produces massive false positives unrelated to eval.

Q12. A logging configuration sets a root logger at WARNING and a module logger at DEBUG, but DEBUG records from that module never appear. Which explanation is most consistent with Python's logging hierarchy?

Section B - Security

A. The module logger's effective level is overridden by the root handler's level filter.

B. The module logger lacks a handler and propagates to root, whose handler level is WARNING.

C. DEBUG records are dropped at creation because the root logger is set to WARNING.

D. The module logger must be set to NOTSET for DEBUG to be emitted. Correct: B - The module logger lacks a handler and propagates to root, whose handler level is WARNING.

Rationale:A child logger with no handler propagates records to ancestor handlers; the root handler's level (WARNING) then filters DEBUG records. Logger levels and handler levels are independent, so the effective level alone does not explain the drop, and NOTSET is not required.

Q13. A test asserts that a function raises ValueError for negative input, but the function currently calls sys.exit(1). Which pytest construct most precisely verifies the intended contract without allowing the process to terminate the test runner?

A. with pytest.raises(SystemExit): fn(-1) B. with pytest.raises(ValueError): fn(-1)

C. assert fn(-1) is None D. monkeypatch.setattr(sys, 'exit', lambda code: None) then call fn(-1) Correct: B - with pytest.raises(ValueError): fn(-1)

Rationale:The intended contract is ValueError, so pytest.raises(ValueError) encodes that expectation and will fail until the code is remediated. pytest.raises(SystemExit) merely asserts the buggy behavior, and monkeypatching sys.exit hides the defect rather than testing the contract.

Q14. Bandit reports B608 (possible SQL injection) for a query built with an f-string, but the same query built with a parameterized placeholder is not flagged. Which remediation most directly eliminates the vulnerability class rather than suppressing the finding?

A. Add '# nosec' to the flagged line. B. Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)).

C. Wrap the user_id in str() before interpolation.

D. Configure Bandit to skip the B608 test.

Correct: B - Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)).

Section B - Security

Q17. A developer uses assert to validate an authentication token in production code. Under which condition does this create a security vulnerability?

A. When the token is a bytes object rather than a str.

B. When Python is run with -O, which strips assert statements.

C. When the assert uses '==' instead of 'is'. D. When the assert is inside a try/except block. Correct: B - When Python is run with -O, which strips assert statements.

Rationale:The -O flag removes assert statements, so authentication checks silently disappear in optimized builds, a classic vulnerability. The other options describe type or style issues that do not disable the check.

Q18. A test suite uses unittest.mock.patch on requests.get at the module level. A new test imports the function directly (from requests import get) and the patch no longer takes effect. Which patching target is correct?

A. patch('requests.get') B. patch('mymodule.get') where mymodule imported it

C. patch('requests') D. patch.object(requests, 'get', autospec=True) Correct: B - patch('mymodule.get') where mymodule imported it

Rationale:Mock patches the name where it is looked up, so the module that imported get must be patched. Patching requests.get affects the original binding, not the local reference, and patching the module object is too broad.

Section C - Logging

Q19.

A CI pipeline runs pip-audit and reports a vulnerable transitive dependency. The team cannot upgrade it directly. Which remediation best reduces risk while preserving functionality?

A. Pin the vulnerable version and add it to an allowlist.

B. Add a constraints file overriding the transitive version to a patched release and re-run tests.

C. Vendor the vulnerable package source into the repo unchanged.

D. Disable pip-audit for transitive dependencies. Correct: B - Add a constraints file overriding the transitive version to a patched release and re-run tests.

Rationale:A constraints file forces a patched transitive version without altering direct dependencies, and re-running tests verifies compatibility. Pinning or allowlisting the vulnerable version, vendoring unchanged code, or disabling the audit all preserve the vulnerability.

Q20. A code review flags subprocess.Popen(cmd, shell=True) where cmd includes user input. Which remediation most completely removes the command injection risk?

A. Escape shell metacharacters in the user input before concatenation.

B. Use subprocess.Popen with a list of arguments and shell=False.

C. Wrap the command in shlex.quote and keep shell=True.

D. Run the command as a non-root user with shell=True. Correct: B - Use subprocess.Popen with a list of arguments and shell=False.

Rationale:Passing an argument list with shell=False avoids shell interpretation entirely, eliminating injection. Escaping or quoting is error-prone and incomplete, and dropping privileges reduces impact but not the vulnerability itself.

Q21. A developer runs flake8 --select=E722 on a codebase and receives no warnings, yet a subsequent Bandit scan reports a high-severity finding in the same file. Which explanation best accounts for this discrepancy?

Section C - Logging

A. Assert that requests.get was called exactly three times using assert_called_with on the final call.

B. Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3.

C. Patch time.sleep to a no-op and assert the function completes within a fixed wall-clock budget.

D. Use pytest.mark.integration and hit a real endpoint that returns 500 to observe retries. Correct: B - Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3.

Rationale:Driving the mock with a side_effect sequence exercises the retry logic deterministically and asserts both the observable outcome (parsed payload) and the interaction (call count), which is the strongest contract-level check. Option A checks only the last call, C tests timing rather than retry semantics, and D introduces nondeterminism and external dependency.

Q24. A logging configuration sets logging.basicConfig(level=logging.INFO) and a module calls logging.getLogger(__name__).debug("token=%s", token). What is the most significant security concern, and what is the correct remediation?

A. The debug call is silently dropped at INFO level, so no risk exists; no remediation needed.

B. The token is formatted eagerly and may leak if the root level is later raised to DEBUG; the fix is to never log secrets and to use structured redaction or omit the token entirely.

C. Using %s formatting is unsafe; the fix is to use f-strings so the token is evaluated lazily.

D. The __name__ logger bypasses the root handler, so the message will always be emitted regardless of level. Correct: B - The token is formatted eagerly and may leak if the root level is later raised to DEBUG; the fix is to never log secrets and to use structured redaction or omit the token entirely.

Rationale:The lazy %s argument is only formatted when the record is emitted, but if any environment raises the effective level to DEBUG the secret is written to logs; secrets should never be passed to logging at all, and redaction or omission is the correct fix. Option A ignores configuration drift, C inverts the laziness tradeoff (f-strings evaluate eagerly), and D misstates logger propagation.

Section C - Logging

Q25. A CI pipeline runs bandit -r src/ -f json and fails the build on any HIGH severity finding. A developer argues that a # nosec comment is the correct fix for a flagged subprocess.Popen(..., shell=True). Which response is most defensible from a secure-SDLC standpoint?

A. Accept the # nosec because Bandit false-positives on subprocess by default.

B. Replace shell=True with a list-form invocation, validate inputs against an allowlist, and only use # nosec with a documented justification if the risk is unavoidable.

C. Lower the CI threshold to MEDIUM so the finding no longer fails the build.

D. Move the call into a separate module excluded from the Bandit scan path. Correct: B - Replace shell=True with a list-form invocation, validate inputs against an allowlist, and only use # nosec with a documented justification if the risk is unavoidable.

Rationale:shell=True enables shell metacharacter injection, so the correct remediation is to avoid the shell and constrain inputs; suppression is a last resort requiring documented justification. Options A, C, and D all mask the finding rather than remediate it, violating secure-SDLC principles.

Q26. A code review flags hashlib.md5(password.encode()).hexdigest() used for storing credentials. Which replacement most correctly reflects current password-storage guidance?

A. hashlib.sha256(password.encode()).hex digest() with a fixed application salt.

B. hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600000) with a per-user random salt.

C. base64.b64encode(password.encode()) to obfuscate the credential.

D. hmac.new(secret_key, password.encode(), hashlib.md5).hexdigest(). Correct: B - hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600000) with a per-user random salt.

Rationale:Current guidance (OWASP/NIST) requires a memory-hard or iterated KDF with a per-user random salt; PBKDF2-HMAC-SHA256 with a high iteration count satisfies this. SHA-256 alone (A) is fast and unsuitable for passwords, base64 (C) is encoding not hashing, and HMAC-MD5 (D) retains a broken hash primitive.

Section D - Bandit

Q28.

A Python service loads YAML configuration with yaml.load(stream) from a user-uploadable file. Which change most effectively prevents arbitrary code execution?

A. Wrap the load in try/except to catch parse errors.

B. Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types.

C. Validate the file extension is .yaml before loading.

D. Run the loader in a thread pool to isolate failures. Correct: B - Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types.

Rationale:yaml.load with the default loader can instantiate arbitrary Python objects via tags like !!python/object, enabling code execution; yaml.safe_load disallows those constructors. Extension checks (C) are trivially bypassed, try/except (A) does not prevent execution, and thread isolation (D) does not sandbox code.

Q29. An audit requires that a Python package's dependencies be checked for known CVEs as part of CI. Which tool and workflow best satisfies this requirement?

A. Run flake8 with the flake8-bandit plugin to detect vulnerable dependencies.

B. Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE.

C. Run mypy --strict to catch type errors that indicate vulnerabilities.

D. Run pytest --cov and require 100% coverage before merging. Correct: B - Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE.

Rationale:SCA tools like pip-audit and safety query vulnerability databases against the resolved dependency set, which is the correct control for third-party CVEs. Flake8 plugins (A) analyze source style/security patterns, mypy (C) checks types, and coverage (D) measures test execution, none of which detect dependency CVEs.

Q30. A developer must remediate a Bandit finding for assert used to enforce an authorization invariant in production code. Why is this a genuine security issue, and what is the appropriate fix?

Section D - Bandit

A. Asserts are slow; replace them with logging statements.

B. Asserts are stripped when Python runs with -O, so security-critical checks may vanish; replace with explicit if not condition: raise logic.

C. Asserts raise the wrong exception type; replace with sys.exit(1).

D. Asserts leak stack traces; wrap them in try/except. Correct: B - Asserts are stripped when Python runs with -O, so security-critical checks may vanish; replace with explicit if not condition: raise logic.

Rationale:Running with optimization (python -O) removes assert statements entirely, so using them for authorization or input validation can silently disable security controls in production; explicit conditionals that raise appropriate exceptions are the correct remediation. The other options misidentify the risk (performance, exception type, or trace leakage) and do not address the stripping behavior.

Q31. A developer wants Flake8 to flag every bare except: clause as a security-relevant error. Which plugin configuration correctly achieves this with the flake8-bugbear plugin, and why does this matter for security?

A. Enable B902; it detects bare excepts and flags them as security issues because they swallow KeyboardInterrupt.

B. Enable B001; it flags bare except clauses, since silently catching all exceptions can mask security-relevant failures and hide tracebacks from logging.

C. Enable E722; it flags bare except clauses, which is a pycodestyle error and therefore security-critical.

D. Enable B110; it flags try-except-pass blocks, which is the only pattern that hides exceptions. Correct: B - Enable B001; it flags bare except clauses, since silently catching all exceptions can mask security-relevant failures and hide tracebacks from logging.

Rationale:flake8-bugbear's B001 flags bare except: clauses; catching everything can hide security-relevant exceptions and suppress logging. B902 is about blind except in certain contexts, E722 is pycodestyle (style, not security-critical), and B110 targets try-except-pass specifically, not all bare excepts.

Q32. In a code review, you see subprocess.Popen(user_input, shell=True). Which remediation preserves functionality while eliminating command injection, and what does Bandit report?

Section D - Bandit

A. SAST analyzes running code and detects runtime injection; DAST scans source for insecure patterns like eval.

B. SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS.

C. SAST requires a deployed environment; DAST runs at commit time and is faster for Python.

D. SAST and DAST are interchangeable for Python because both rely on Flake8 plugins.

Correct: B - SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS.

Rationale:SAST inspects code without executing it (e.g., Bandit finding insecure deserialization), while DAST tests a live application (e.g., reflected XSS). A reverses the definitions, C misstates deployment needs, and D falsely equates them with Flake8 plugins.

Q35. A Python service logs logger.info('User %s logged in with password %s', username, password). Which remediation aligns with OWASP logging cheat sheet and avoids sensitive data exposure?

A. Change level to debug and keep the password for troubleshooting.

B. Hash the password with MD5 before logging to preserve traceability.

C. Remove the password from the log message and log only the username and a success flag; ensure logs are not world-readable.

D. Log the password only when DEBUG=True and disable logging in production.

Correct: C - Remove the password from the log message and log only the username and a success flag; ensure logs are not world-readable.

Rationale:OWASP advises never logging credentials; removing the password and restricting log permissions prevents exposure. Debug-level logging still leaks secrets, MD5 is insecure and unnecessary, and disabling logging entirely harms auditability.

Q36. A requirements.txt pins requests==2.19.0, which has CVE-2018-18074 (credential leak on redirect). Which command best identifies this and similar vulnerable dependencies in CI?

A. pip install safety && safety check B. flake8 --select=S

C. bandit -r . D. pytest --cov Correct: A - pip install safety && safety check

Section D - Bandit

Rationale: Safety checks installed dependencies against a vulnerability database and would flag requests 2.19.0. Flake8 and Bandit analyze source code, not dependency CVEs, and pytest--cov measures test coverage, not vulnerabilities.