
































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!

































98 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 V2 TASK 1 PERFORMANCE ASSESSMENT GUIDE | STATIC CODE ANALYSIS, PYTHON LOGGING, DEFENSIVE CODING, UNIT TESTING, DEBUGGING & SECURITY REPORT | 2026 UPDATED. It contains 98 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 98 Questions
Foundations - Application - WGU D385 V2 TASK 1 Performance Assessment Guide Static CODE Analysis Python Logging Defensive Coding UNIT Testing Debugging & Security Report 2026 Updated Software Engineering Static Analysis Logging Defensive Programming Testing Debugging Security Graduate / Advanced Undergraduate YEAR 4 All answers with rationales
Content Area Questions Key Topics
Static CODE Analysis 1-17 Python, Developer, Function, Input, Application
Python Logging 18-34 Python, Security, Developer, Logging, Writes
Defensive Coding 35-51 Python, Logging, Function, Logger, Security
UNIT Testing 52-68 Python, Function, Logging, Logger, Message
Debugging 69-85 Python, Breakpoint, Value, Function, Application
Security Reporting 86-98 Python, Input, Exception, Analysis, Function
TOTAL 98 All questions include answers and detailed rationales
Section A - Static CODE Analysis
Rationale: A logging.Filter can examine the LogRecord and modify or redact the message before it is processed by handlers, ensuring no sensitive data reaches the output. Catching exceptions and logging only the type loses diagnostic information. Raising the level or truncating messages does not guarantee that sensitive data won't appear in messages that are logged.
Why the other answers are wrong: B. Logging only exception type loses valuable context and may still not catch all sensitive data. C. CRITICAL level still logs critical messages, which could contain sensitive data. D. Truncation does not prevent sensitive data from appearing in the first part of the message.
Reference: WGU D385 V2: Python Logging - Best Practices and Security
A developer is implementing a function that processes a dictionary of configuration parameters. Which defensive coding practice BEST prevents unexpected crashes from malformed input?
A. Assume the dictionary is well-formed and rely on the caller to validate it
B. Use assertions to verify the dictionary's keys and types before processing
C. Catch all exceptions within the function and return None
D. Validate the dictionary's structure and types, raising ValueError or using defaults for missing keys Correct: D - Validate the dictionary's structure and types, raising ValueError or using defaults for missing keys
Rationale:Defensive coding involves validating inputs and handling missing or malformed data gracefully. Raising ValueError on invalid structure or using defaults for missing keys allows the function to behave predictably without crashing. Assertions can be disabled with -O and are not suitable for input validation. Catching all exceptions and returning None obscures errors. Assuming well-formed input violates defensive coding principles.
Why the other answers are wrong: A. Assuming well-formed input is the opposite of defensive coding. B. Assertions are for debugging and are stripped in optimized mode. C. Swallowing all exceptions hides bugs and makes debugging difficult.
Reference: WGU D385 V2: Defensive Coding - Input Validation and Error Handling
In a pytest suite, a test function uses the tmp_path fixture to create a temporary file. However, the test fails when run in a different order. What is the MOST likely cause?
A. The test is not using the fixture correctly because tmp_path is function-scoped
B. The test relies on a file created by another test that ran earlier
Section A - Static CODE Analysis
C. The test uses tmp_path but writes to a global path instead
D. The test modifies the tmp_path directory and does not clean up Correct: B - The test relies on a file created by another test that ran earlier
Rationale:Test order independence requires each test to set up its own data. If a test depends on a file created by a previous test, it will fail when run alone or in a different order. tmp_path is function-scoped and provides a unique directory per test, so it doesn't cause cross-test contamination. Writing to a global path or not cleaning up could cause issues but not necessarily order dependence.
Why the other answers are wrong: A. tmp_path is function-scoped, so it provides a fresh directory per test, not a cause of order dependence. C. Writing to a global path would cause contamination regardless of order, not specifically order dependence. D. Lack of cleanup might affect disk space but not test order dependence.
Reference: WGU D385 V2: Unit Testing - Test Isolation and Fixtures
A developer is debugging a race condition in a multithreaded Python application. Which tool or technique is MOST effective for identifying the interleaving that causes the bug?
A. Adding print statements to each thread to trace execution order
B. Using a debugger to step through the code line by line
C. Running the code under a tool like helgrind or ThreadSanitizer to detect data races
D. Increasing the number of threads to stress the system
Correct: C - Running the code under a tool like helgrind or ThreadSanitizer to detect data races
Rationale:Race conditions are notoriously hard to reproduce and debug with print statements or stepping because they depend on timing. Specialized tools like ThreadSanitizer or helgrind instrument the code to detect data races and provide detailed reports on conflicting accesses. Increasing threads may make the race more likely but doesn't help identify it.
Why the other answers are wrong: A. Print statements are invasive and may alter timing, not reliable for race detection. B. Stepping through code in a debugger is manual and unlikely to catch the exact interleaving. D. Stress testing only demonstrates the existence of a race, not its cause.
Reference: WGU D385 V2: Debugging - Concurrency and Race Conditions
Section A - Static CODE Analysis A. High complexity is not about length; it's about branching. B. Complexity does not affect runtime speed. D. Complexity is not a direct security vulnerability.
Reference: WGU D385 V2: Static Code Analysis - Maintainability Metrics
A developer is using pytest to test a function that makes an HTTP request to an external API. To avoid network calls during tests, which approach is MOST appropriate?
A. Use pytest.mark.skipif to skip the test if network is unavailable
B. Use a mock object to replace the API client and simulate responses
C. Use time.sleep() to wait for the API to respond
D. Use a fixture that calls the real API but caches the result Correct: B - Use a mock object to replace the API client and simulate responses
Rationale:Mocking the API client isolates the unit test from external dependencies, making it fast and deterministic. Skipping tests avoids the issue but leaves the code untested. Sleeping is not a solution. Caching real API calls reduces network usage but still introduces external dependency and non-determinism.
Why the other answers are wrong: A. Skipping tests without mocks means the function is not tested at all. C. Sleeping does not solve the dependency problem and slows down tests. D. Caching still requires the API to be available on the first run and may yield stale results.
Reference: WGU D385 V2: Unit Testing - Mocking and External Dependencies
In a Python application, a developer wants to log exceptions with their traceback. Which logging call correctly captures the traceback in the log output?
A. logger.error('An error occurred: %s', e) B. logger.exception('An error occurred')
C. logger.error('An error occurred', exc_info=False)
D. logger.log(logging.ERROR, 'An error occurred', stack_info=False) Correct: B - logger.exception('An error occurred')
Rationale:logger.exception() is specifically designed to be called within an exception handler and automatically adds the exception traceback to the log record. Using logger.error with the exception object only logs the string representation, not the traceback. exc_info=False omits the traceback. stack_info=False controls stack frame info, not the exception traceback.
Why the other answers are wrong: A. Logging the exception object as a string does not include the traceback.
Section A - Static CODE Analysis C. exc_info=False explicitly disables traceback capture. D. stack_info=False does not include the exception traceback.
Reference: WGU D385 V2: Python Logging - Exception Logging
A security review identifies that a Python application uses pickle to deserialize data from an untrusted source. Which alternative is the MOST secure replacement?
A. Use json with a custom decoder that validates types
B. Use yaml.unsafe_load to parse the data
C. Use pickle with a checksum to verify integrity
D. Use marshal to deserialize the data
Correct: A - Use json with a custom decoder that validates types
Rationale:The pickle module is known to be unsafe for untrusted data because it can execute arbitrary code during unpickling. JSON is a safe serialization format that does not execute code; using a custom decoder allows type validation. yaml.unsafe_load is also dangerous. Checksums do not prevent malicious payloads, and marshal is equally unsafe.
Why the other answers are wrong: B. yaml.unsafe_load is also capable of executing arbitrary code. C. A checksum only verifies integrity, not safety, and an attacker can produce a valid checksum. D. marshal is similar to pickle and is not safe for untrusted data.
Reference: WGU D385 V2: Security - Secure Deserialization
In a Python 3.11 codebase, a developer uses logging.debug() statements for detailed internal state. After deploying, they notice these messages appear in production logs despite the root logger being set to WARNING. Which configuration flaw most likely causes this?
A. The debug messages are being emitted by a child logger that has its own level set to DEBUG and propagate set to True, bypassing the root logger's effective level.
B. The root logger's level is set to DEBUG but a filter on a handler is rejecting records below WARNING.
C. The debug statements are using the logging.debug() module-level function, which always emits at DEBUG level regardless of the root logger's configuration.
D. A custom formatter is converting DEBUG records to WARNING before they reach the handler.
Correct: A - The debug messages are being emitted by a child logger that has its own level set to DEBUG and propagate set to True, bypassing the root logger's effective level.
Section A - Static CODE Analysis denial-of-service via malicious input?
A. Wrapping the int() call in a try-except block and returning a 400 response.
B. Using a regex to validate the input matches ^[0-9]+$ before calling int().
C. Limiting the length of the input string to 10 characters before conversion.
D. Using a custom function that catches ValueError and logs the exception. Correct: C - Limiting the length of the input string to 10 characters before conversion.
Rationale:A very long numeric string can cause a DoS by consuming CPU and memory during conversion. Length limiting caps the resource usage. Try-except (A) and regex (B) still process the entire input. Logging (D) does not prevent resource exhaustion.
Why the other answers are wrong: A. Catching exceptions does not prevent the expensive conversion attempt. B. Regex validation also processes the full string and does not bound length. D. Logging is after the fact; the conversion still occurs.
Reference: SEI CERT Python Coding Standard: IDS11-PL, IDS04-PL
In a unit test suite using pytest, a developer writes a test that checks a function's side effect by mocking an external API call. The test passes in isolation but fails when the full suite runs. Which practice best addresses this flakiness?
A. Using unittest.mock.patch with autospec=True to ensure the mock matches the real API signature.
B. Increasing the timeout for the test to account for slower CI machines.
C. Running the test in a separate process to avoid interference from other tests.
D. Adding a sleep(1) before the assertion to allow the mock to update. Correct: A - Using unittest.mock.patch with autospec=True to ensure the mock matches the real API signature.
Rationale:Flakiness often arises from mock mismatches or shared state. autospec=True ensures the mock has the same interface, preventing subtle errors. Timeouts (B) and sleeps (D) mask symptoms. Separate processes (C) avoid interference but do not fix the root cause if it's a mock signature issue.
Why the other answers are wrong: B. Increasing timeouts does not address the root cause of flakiness. C. Running in a separate process may hide shared state issues but doesn't fix mock correctness. D. Sleeps are a code smell and do not reliably fix race conditions or mock issues.
Reference: Brian Okken, Python Testing with pytest, 2nd Ed., Ch. 6
Section A - Static CODE Analysis
Q15. During a debugging session, a developer uses pdb to inspect a variable. They issue the command 'p variable' but receive a NameError. Why?
A. The variable is a local variable in a function frame that is not currently active.
B. The command 'p' is not a valid pdb command; they should use 'print'.
C. The variable is shadowed by a pdb internal variable with the same name.
D. The developer forgot to use the 'debug' command to enter the frame. Correct: A - The variable is a local variable in a function frame that is not currently active.
Rationale:pdb evaluates expressions in the current frame's scope. If the variable is not in that scope (e.g., a local variable in a different stack frame), a NameError is raised. 'p' is an alias for 'print' (B). pdb does not shadow user variables (C). The 'debug' command is for entering interactive debuggers, not for frame access (D).
Why the other answers are wrong: B. p is a valid alias for print in pdb. C. pdb does not reserve variable names that shadow user variables. D. The debug command is for launching a recursive debugger, not for variable access.
Reference: Python Documentation: pdb - The Python Debugger
A security report identifies that a Python web application is vulnerable to SQL injection because it constructs queries with f-strings. Which remediation best addresses the root cause while preserving query flexibility?
A. Use a stored procedure for all database access.
B. Implement a regex-based input filter to remove SQL keywords.
C. Use parameterized queries with placeholders for all user-supplied values.
D. Escape single quotes in user input before embedding in SQL. Correct: C - Use parameterized queries with placeholders for all user-supplied values.
Rationale:Parameterized queries (prepared statements) separate SQL code from data, eliminating injection. Stored procedures (A) can still be vulnerable if they concatenate input. Regex filters (B) and escaping (D) are blacklist approaches that are error-prone and bypassable.
Why the other answers are wrong: A. Stored procedures do not inherently prevent injection if they use dynamic SQL. B. Regex filters are incomplete and can be bypassed with encoding tricks. D. Escaping quotes is insufficient and does not protect against all injection vectors.
Reference: OWASP SQL Injection Prevention Cheat Sheet
Section B - Python Logging
A developer writes a unit test that mocks an external REST API using responses library. The test asserts that the function makes a request with a specific JSON payload. Which assertion verifies the request body correctly?
A. assert call.request.body == b'{"key": "value"}'
B. assert call.request.url == 'https://api.example.com/endpoint'
C. assert call.request.headers['Content-Type'] == 'application/json'
D. assert call.request.method == 'POST'
Correct: A - assert call.request.body == b'{"key": "value"}'
Rationale:The request body contains the JSON payload. Comparing the raw bytes ensures the exact payload was sent. URL (B), Content-Type (C), and method (D) are important but do not verify the payload content.
Why the other answers are wrong: B. URL verification does not check the request body. C. Content-Type header does not guarantee the body content. D. Method verification alone does not validate the payload.
Reference: responses library documentation; unittest.mock examples
A static analysis tool reports a high-severity issue in a Python script: 'try, except, pass' block detected. Why is this pattern considered a security risk?
A. It suppresses exceptions, making failures invisible and potentially masking security-relevant errors.
B. It causes a memory leak because exceptions are not properly handled.
C. It is a syntax error in Python 3.10 and above.
D. It makes the code run slower due to exception handling overhead. Correct: A - It suppresses exceptions, making failures invisible and potentially masking security-relevant errors.
Rationale:Silently passing on exceptions hides failures, which can include security checks, connection errors, or data integrity issues. This is a classic bad practice. It does not cause memory leaks (B), is not a syntax error (C), and performance is not the primary concern (D).
Why the other answers are wrong: B. No memory leak is associated with pass in except blocks. C. It is syntactically valid in all Python versions.
Section B - Python Logging D. Performance impact is minimal and not the security issue.
Reference: Bandit B110; OWASP Code Review Guide
A developer writes a logging statement: logging.info(f'User {user_id} accessed {file_path}'). Why is this a security concern?
A. File paths are sensitive and should never be logged.
B. Using f-strings in logging is inefficient and should be avoided.
C. User IDs are considered personally identifiable information and cannot be logged under GDPR.
D. The message may contain sensitive data that is not properly redacted, and the f-string is evaluated even if logging is disabled. Correct: D - The message may contain sensitive data that is not properly redacted, and the f-string is evaluated even if logging is disabled.
Rationale:f-strings are evaluated at runtime even when the log level suppresses the record, causing a performance and potential data exposure issue. Also, logging sensitive data like file paths may violate security policies. Efficiency is a minor point (B), and while user IDs may be PII, the primary issue is the unconditional evaluation and lack of redaction (A, C).
Why the other answers are wrong: A. File paths may be sensitive, but the main issue is the f-string evaluation and lack of redaction. B. Efficiency is a concern, but it is not the primary security risk. C. User IDs can be logged if allowed by policy; the issue is broader data exposure.
Reference: OWASP Logging Cheat Sheet; Python Logging Best Practices
A security analyst is reviewing a Python codebase and encounters the following pattern: command = "ping -c 4 " + user_input; subprocess.call(command, shell=True). Which single remediation most effectively mitigates the injection vulnerability while preserving functionality?
A. Replace shell=True with shell=False and pass the command as a list
B. Use shlex.quote() on user_input before concatenation
C. Sanitize user_input with a regex that allows only alphanumeric characters and dots
D. Set the timeout parameter in subprocess.call to a low value
Correct: A - Replace shell=True with shell=False and pass the command as a list
Section B - Python Logging
A. Verify that the final absolute path starts with the intended base directory
B. Use os.path.abspath() on the filename before joining
C. Replace all '../' occurrences in the filename with an empty string
D. Use open() with the 'x' mode to ensure the file does not already exist Correct: A - Verify that the final absolute path starts with the intended base directory
Rationale:Path traversal is best prevented by normalizing the full path and checking it remains within the intended directory. Using os.path.abspath() alone does not resolve symlinks or ensure containment; simple string replacement is bypassable; and 'x' mode does not address path traversal.
Why the other answers are wrong: B. abspath() does not prevent traversal if the base directory is not checked. C. String replacement can be bypassed with nested encodings or symlinks. D. File exclusive creation does not prevent reading or writing arbitrary paths.
Reference: CWE-22: Improper Limitation of a Pathname to a Restricted Directory, 2026
During unit testing of a function that sorts a list of dictionaries by a 'date' key, you write a test that passes a list with one element. What is the primary limitation of this test case?
A. It does not test the function's behavior on empty input
B. It cannot detect errors in the sort algorithm's comparison logic
C. It does not verify that the original list remains unmodified
D. It fails to test the function with duplicate dates Correct: B - It cannot detect errors in the sort algorithm's comparison logic
Rationale:A single-element list does not exercise the sort's comparison logic because no comparisons occur. Testing empty input, immutability, and duplicates are all important, but the fundamental limitation is the lack of multiple elements to trigger sorting.
Why the other answers are wrong: A. Not testing empty input is a limitation but not the primary one for a sort function. C. Immutability is not tested, but the sort logic itself is the core functionality. D. Duplicates are edge cases, but the main sorting logic is not exercised at all.
Reference: Pytest Documentation, 2026, Section: Test Design
An application fails intermittently in production. The logs show a RecursionError but the stack trace does not indicate the entry point. Which debugging technique is most effective to diagnose the root cause?
Section B - Python Logging
A. Enable Python's faulthandler module to dump the Python traceback on fatal errors
B. Add a breakpoint at the top-level function that is suspected to be the entry point
C. Use sys.setrecursionlimit() to increase the recursion limit and observe if the error persists
D. Review the code for any recursive function and add a counter to limit recursion depth Correct: A - Enable Python's faulthandler module to dump the Python traceback on fatal errors
Rationale:faulthandler can dump tracebacks on crashes, including RecursionError, showing the full call chain at the moment of failure. Breakpoints require reproduction, increasing recursion limit may crash the interpreter, and adding counters changes behavior without revealing the original call path.
Why the other answers are wrong: B. Breakpoints are only useful if the error is reproducible in a debugger. C. Increasing recursion limit can cause a hard crash and does not identify the root cause. D. Adding counters is a code change that may not be feasible in production and does not show the call stack.
Reference: Python Documentation, faulthandler, 2026
In a security report, you must document a vulnerability where an attacker can cause a denial of service by sending many requests that trigger expensive regex operations. Which CWE category best describes this issue?
A. CWE-400: Uncontrolled Resource Consumption
B. CWE-1333: Inefficient Regular Expression Complexity
C. CWE-770: Allocation of Resources Without Limits or Throttling
D. CWE-20: Improper Input Validation
Correct: B - CWE-1333: Inefficient Regular Expression Complexity
Rationale:CWE-1333 specifically addresses ReDoS (Regular Expression Denial of Service) due to inefficient regex patterns. While CWE-400 and CWE-770 are related to resource consumption, CWE-1333 is the precise classification for regex complexity issues.
Why the other answers are wrong: A. CWE-400 is a broad category; CWE-1333 is the more specific weakness. C. CWE-770 focuses on resource allocation without limits, not regex patterns. D. CWE-20 is about input validation, not the regex engine's behavior.
Reference: CWE-1333, 2026, MITRE
Section B - Python Logging
Q29. A Python application uses a custom logging handler that sends logs to a remote SIEM over UDP. In high-load conditions, logs are being dropped. Which change to the logging architecture is most likely to reduce log loss?
A. Switch from UDP to TCP with a retry mechanism
B. Increase the logging level to WARNING to reduce the volume of logs
C. Add a queue handler with a worker thread that sends logs asynchronously
D. Use a synchronous handler that blocks until the log is sent Correct: C - Add a queue handler with a worker thread that sends logs asynchronously
Rationale:A QueueHandler decouples logging from the application's execution, allowing logs to be buffered and processed by a background thread, reducing drops during bursts. Switching to TCP helps but can still block; increasing level loses information; synchronous handlers worsen the bottleneck.
Why the other answers are wrong: A. TCP reduces packet loss but does not solve the buffering problem if the network is slow. B. Raising the log level discards lower-severity logs, which may be needed. D. Synchronous sending will block the application and may still drop logs if the buffer overflows.
Reference: Python Logging Cookbook, QueueHandler, 2026
A security audit reveals that a Python web application is vulnerable to timing attacks when comparing user-supplied tokens. Which code change is the most secure mitigation?
A. Use hmac.compare_digest(token, stored_token)
B. Hash the token with MD5 and compare the hashes
C. Add a random delay before comparison to obscure timing
D. Use Python's == operator after encoding both strings to UTF- Correct: A - Use hmac.compare_digest(token, stored_token)
Rationale:hmac.compare_digest performs constant-time comparison, preventing timing side-channel attacks. MD5 hashing is cryptographically weak and the comparison may still be non-constant-time; random delays are unreliable; the == operator is not constant-time.
Why the other answers are wrong: B. MD5 is broken and hashing does not guarantee constant-time comparison. C. Random delays are not a robust mitigation and can be statistically bypassed. D. The == operator short-circuits on the first differing byte, leaking timing information.
Reference: Python hmac module documentation, 2026
Section B - Python Logging
Q31. In a Python logging pipeline, a developer configures a RotatingFileHandler with maxBytes=2048 and backupCount=3, then logs a single 5 KB message. Which statement accurately describes the resulting log files?
A. The message is split across multiple files, each under 2 KB.
B. One file contains the full message, and three backup files are created empty.
C. The message is written to the active file, and the file is rotated immediately, creating a backup with the full message.
D. The message is truncated to fit within 2 KB, and the remainder is discarded.
Correct: C - The message is written to the active file, and the file is rotated immediately, creating a backup with the full message.
Rationale:RotatingFileHandler checks the file size before writing; if the current message would exceed maxBytes, it rotates first. Since the active file is empty and the message is 5 KB, the handler rotates before writing, creating an empty backup (e.g., .1) and then writes the full message to the new active file. Thus the full message is in the active file, not split or truncated.
Why the other answers are wrong: A. Messages are never split across files; rotation occurs before writing if the file size exceeds maxBytes. B. Backup files are created only when rotation happens, and they contain the previous file content, not empty files. D. Logging does not truncate messages; it rotates the file to accommodate the full message.
Reference: Python Documentation - logging.handlers.RotatingFileHandler (2026)
A static analysis tool flags a Python function that reads a file path from an HTTP request and passes it directly to open(). Which defensive coding strategy BEST mitigates this vulnerability without breaking legitimate functionality?
A. Use os.path.abspath to resolve the path and ensure it starts with the intended base directory.
B. Apply a blocklist of dangerous characters like ../ and null bytes.
C. Use shutil.copyfile instead of open() to read the file.
D. Log the file path and user identity for audit purposes. Correct: A - Use os.path.abspath to resolve the path and ensure it starts with the intended base directory.