



















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 Configure and interpret Flake8 plugins for security-relevant linting (bandit, flake8-bugbear, flake8-annotations) 2 Identify and remediate Python vulnerabilities such as injection, insecure deserialization, and weak cryptography 3 Design structured logging and error handling that avoids sensitive data leakage while preserving auditability 4 Apply testing strategies (unit, integration, property-based, fuzz) to validate security controls and remediations 5 Integrate static analysis into CI/CD pipelines with policy-as-code and risk-based triage 6 WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security 7 Logging 8 Testing & Remediation 2026 9 Foundations of Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 10 Applied Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 11 Advanced Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation 12 Software Security and Testing: Static Code Analysis, Flake8, Python Security, Logging, Testing & Remediation Review
This study document brings together 50 carefully worded exam questions drawn from WGU D Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python Security, Logging, Testing & Remediation 2026, with the strongest emphasis placed on Configure and interpret Flake8 plugins for security-relevant linting (bandit, flake8-bugbear, flake8-annotations), Identify and remediate Python vulnerabilities such as injection, insecure deserialization, and weak cryptography and Design structured logging and error handling that avoids sensitive data leakage while preserving auditability. 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 pickle with json and validate the schema with pydantic before use. B. Wrap pickle.loads in a try/except and log the exception. C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes. CORRECT D. Enable Python's -X dev mode to catch deserialization errors. RATIONALE: Restricting find_class to a whitelist maintains pickle compatibility while blocking arbitrary code execution. JSON (A) may not support all types; try/except (B) does not prevent exploitation; -X dev (D) only adds runtime checks, not security.
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. CORRECT D. The log message lacks a timestamp and correlation ID. 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.
A. Unit tests with mocked inputs B. Property-based testing with Hypothesis CORRECT C. Integration tests with a real database D. Manual exploratory testing 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.
A. Remove the import if truly unused. CORRECT 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. 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.
A. hashlib.md5(password.encode()).hexdigest() B. hashlib.sha256(password.encode()).hexdigest() C. bcrypt.hashpw(password.encode(), bcrypt.gensalt()) CORRECT D. base64.b64encode(password.encode()) 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.
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. CORRECT D. Add # nosec to suppress the warning. 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.
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. CORRECT 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. 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.
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. CORRECT 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. 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.
A. with pytest.raises(SystemExit): fn(-1) B. with pytest.raises(ValueError): fn(-1) CORRECT C. assert fn(-1) is None D. monkeypatch.setattr(sys, 'exit', lambda code: None) then call 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.
A. Log the body only when the log level is DEBUG. B. Redact or omit sensitive fields before logging, and log structured, non-sensitive metadata. CORRECT C. Encrypt the log file at rest and continue logging the body. D. Log only the HTTP status code and drop all request context. RATIONALE: OWASP recommends minimizing and redacting sensitive data at the point of logging; structured metadata preserves diagnostics without exposing secrets. Logging at DEBUG still persists secrets, encryption at rest does not prevent exposure to log readers, and dropping all context harms operability.
A. When the token is a bytes object rather than a str. B. When Python is run with -O, which strips assert statements. CORRECT C. When the assert uses '==' instead of 'is'. D. When the assert is inside a try/except block. 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.
A. patch('requests.get') B. patch('mymodule.get') where mymodule imported it CORRECT C. patch('requests') D. patch.object(requests, 'get', autospec=True) 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.
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. CORRECT C. Vendor the vulnerable package source into the repo unchanged. D. Disable pip-audit for transitive dependencies. 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.
A. Escape single quotes in name using name.replace("'", "''") before interpolation. B. Wrap the call in a try/except and log the exception. C. Replace string interpolation with a parameterized query: cursor.execute("SELECT * FROM users WHERE name = %s", (name,)). CORRECT D. Switch the database driver to one that auto-sanitizes all string inputs. RATIONALE: Parameterized queries send the SQL structure and the data separately, so user input cannot alter the query's parse tree regardless of content. Manual escaping (A) is error-prone and driver-dependent, exception handling (B) does not prevent injection, and no mainstream driver (D) auto-sanitizes interpolated strings.
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. CORRECT 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. 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.
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. CORRECT 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. 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.
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. CORRECT 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. 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.
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. CORRECT C. Validate the file extension is .yaml before loading. D. Run the loader in a thread pool to isolate failures. 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.
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. CORRECT C. Run mypy --strict to catch type errors that indicate vulnerabilities. D. Run pytest --cov and require 100% coverage before merging. 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.
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. CORRECT C. Asserts raise the wrong exception type; replace with sys.exit(1). D. Asserts leak stack traces; wrap them in try/except. 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.
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. CORRECT 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. 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.
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. CORRECT 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. 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.
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. CORRECT D. Log the password only when DEBUG=True and disable logging in production. 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.
A. pip install safety && safety check CORRECT B. flake8 --select=S C. bandit -r . D. pytest --cov 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.
A. Use pickle.loads(data, fix_imports=False). B. Use json.loads(data) if the data structure is JSON-compatible; otherwise use a safe serializer like defusedxml for XML. CORRECT C. Use yaml.load(data, Loader=yaml.FullLoader). D. Use pickle.Unpickler with a restricted find_class. RATIONALE: JSON parsing is safe for JSON-compatible data; defusedxml handles XML securely. pickle.loads with fix_imports still executes arbitrary code, yaml.FullLoader is unsafe, and a restricted Unpickler is complex and error-prone.