


























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!



























WGU D522 Python for IT Automation API, | Comprehensive Examination WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2 Support actual exam preparation document with verified
This document is an important and very helpful preparation resource for WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2 Support. Every item uses a focused exam stem, four response options, a keyed response, and a clear rationale, making it easier to understand the subject, spot distractors, and build real exam confidence.
Question 1
When using Python's requests library to interact with a REST API that returns
paginated results via a 'next' link in the JSON response, which approach best
ensures all pages are retrieved while handling transient network errors?
A. Use a while loop that follows the 'next' link until it is null, wrapping each request in a try-except block with retries using exponential backoff. B. Use a for loop over a fixed range of page numbers, ignoring the 'next' link, and catch exceptions to retry the entire loop. C. Use a recursive function that calls itself with the 'next' URL, without any exception handling, relying on Python's recursion limit. D. Use the requests library's built-in pagination support by passing a 'paginate=True' parameter to the get method.
RATIONALE Option A correctly follows the 'next' link dynamically and handles transient errors with retries and backoff, which is a robust pattern. Option B assumes a fixed number of pages and may miss data. Option C lacks error handling and may hit recursion limits. Option D is incorrect because requests does not have built-in pagination.
Question 2
In a Python automation script that sends emails via SMTP, you need to test the
email content without actually sending it to external recipients. How should
MailHog be configured and used?
A. Run MailHog locally, configure the script to use localhost:1025 as the SMTP server, and inspect messages via MailHog's web UI at localhost:8025. B. Use MailHog's cloud service by signing up for an API key, then send
different formatters for each handler.
RATIONALE Option B correctly uses RotatingFileHandler for size-based rotation and allows separate formatters. Option A is incorrect because basicConfig cannot handle multiple handlers with different formats. Option C is plausible but dictConfig can also work; however, B is more direct and common. Option D is inefficient and error-prone.
Question 4
When writing a Python function that makes an API call, which exception
handling strategy best balances robustness and debuggability?
A. Catch all exceptions with a bare except clause, log the error, and return None. B. Catch specific exceptions like requests.exceptions.RequestException, log with exc_info=True, and re-raise a custom exception with context. C. Use a try-except block that catches Exception, logs a generic message, and continues execution without re-raising. D. Avoid exception handling entirely and let the program crash to reveal the error.
RATIONALE Option B catches specific exceptions, logs with traceback (exc_info=True), and re-raises with context, which aids debugging and allows higher-level handling. Option A is too broad and loses stack trace. Option C swallows errors. Option D is not robust for automation.
Question 5
In a Python script that automates API interactions, you need to handle rate
limiting (HTTP 429) by retrying after a delay specified in the 'Retry-After'
header. Which implementation is most correct?
A. Check the status code; if 429, sleep for a fixed 60 seconds and retry indefinitely. B. Use a library like tenacity to retry with exponential backoff, ignoring the 'Retry-After' header. C. On 429, parse the 'Retry-After' header, sleep for that duration, and retry up to a maximum number of attempts. D. On 429, immediately retry without delay, as the rate limit may reset quickly.
RATIONALE Option C respects the server's Retry-After header and sets a retry limit, which is polite and effective. Option A ignores the header and may retry too soon or too late. Option B ignores the header. Option D may exacerbate rate limiting.
Question 6
Which of the following is a correct way to configure MailHog to accept emails
from any domain and store them in memory, and then programmatically
retrieve them via its API?
A. Start MailHog with -smtp-bind-addr 0.0.0.0:1025 and use the /api/v2/messages endpoint to fetch messages. B. Start MailHog with -storage=memory and use the /api/v1/messages endpoint to fetch messages. C. Start MailHog with -api-bind-addr 0.0.0.0:8025 and use the
RATIONALE Option C uses SysLogHandler to send logs to the system log (journald on systemd systems) and also writes to a file. Option A only captures stdout, not file. Option B requires an external module. Option D is incorrect because basicConfig cannot handle multiple handlers with different destinations.
Question 8
In Python, which exception handling construct is most appropriate for ensuring
that a critical cleanup action (e.g., closing a database connection) occurs
regardless of whether an exception is raised?
A. try-finally B. try-except-else C. try-except D. with statement
RATIONALE try-finally guarantees the finally block executes even if an exception occurs, making it ideal for cleanup. try-except-else runs else only if no exception, not for cleanup. try-except handles exceptions but doesn't guarantee cleanup. The with statement is for context managers, which may not apply to all cleanup scenarios.
Question 9
When using the requests library to POST JSON data to an API, which code
snippet correctly sets the Content-Type header and handles a potential JSON
decoding error in the response?
A. requests.post(url, json=data, headers={'Content-Type': 'application/json'}) and then response.json() inside a try-except for ValueError. B. requests.post(url, data=json.dumps(data), headers={'Content-Type':
'application/json'}) and then response.json() without error handling. C. requests.post(url, json=data) and then response.json() inside a try-except for requests.exceptions.JSONDecodeError. D. requests.post(url, data=data, headers={'Content-Type': 'application/json'}) and then response.json() inside a try-except for KeyError.
RATIONALE Option A correctly uses the json parameter (which sets Content-Type automatically) and handles JSON decoding errors with ValueError (or requests.exceptions.JSONDecodeError, a subclass). Option B manually sets header but lacks error handling. Option C omits explicit header but is also correct; however, A is more explicit. Option D sends data as form-encoded, not JSON.
Question 10
In a Python automation script, you need to log messages with varying severity
levels to different destinations: DEBUG and above to a file, and ERROR and
above to the console. Which logging configuration achieves this?
A. Set the root logger level to DEBUG, add a FileHandler with level DEBUG and a StreamHandler with level ERROR. B. Set the root logger level to ERROR, add a FileHandler with level DEBUG and a StreamHandler with level ERROR. C. Set the root logger level to DEBUG, add a FileHandler with level ERROR and a StreamHandler with level DEBUG. D. Set the root logger level to DEBUG, add a FileHandler with level DEBUG and a StreamHandler with level DEBUG.
Question 12
In MailHog, a developer observes that messages sent from a script do not
appear in the web UI at http://localhost:8025. The script uses SMTP on port
A. The script is sending via SMTP but MailHog's UI only displays messages fetched over IMAP. B. The script is targeting a real external SMTP server, or MailHog is bound to a different interface/port than the script is using. C. MailHog requires TLS on port 1025, so unencrypted messages are silently discarded. D. MailHog only accepts messages from localhost, and the script is running in a container.
RATIONALE MailHog captures messages sent to its configured SMTP listener (default 1025) and displays them in the UI on 8025; a mismatch in host, port, or pointing at a real server is the common failure. A is false because MailHog does not require IMAP, C is false (MailHog accepts plain SMTP by default), and D is false since MailHog accepts connections from any reachable interface.
Question 13
A script uses logging with a `RotatingFileHandler(maxBytes=1048576,
backupCount=3)`. After the log exceeds 1 MB repeatedly, how many total log
files exist and what naming pattern applies?
A. One file only; the handler truncates on overflow. B. Four files: app.log, app.log.1, app.log.2, app.log.3. C. Three files: app.log, app.log.1, app.log.2.
D. Two files: app.log and app.log.bak.
RATIONALE RotatingFileHandler keeps the active app.log plus backupCount rotated files (app.log.1..app.log.3), totaling four. A describes no rotation, C omits the active file, and D is not the naming scheme used by the standard library.
Question 14
Which try/except/else/finally structure correctly logs an exception while
guaranteeing a cleanup action runs regardless of success or failure?
A. try: work() except Exception: log() else: cleanup() finally: pass B. try: work() finally: cleanup() except Exception: log() C. try: work() except Exception: log() finally: cleanup() D. try: work() else: cleanup() except Exception: log()
RATIONALE except handles/logs the exception and finally always executes cleanup, which is the correct ordering. A runs cleanup only on success, B is syntactically invalid (finally must follow except), and D places else before except, which is invalid syntax.
Question 15
An automation script must authenticate to an API whose token expires every
60 minutes. Which design best satisfies the principle of least privilege and
operational reliability?
A. Hard-code a long-lived token in the script to avoid refresh logic. B. Store credentials in environment variables or a secrets manager and
Question 17
Which statement best distinguishes logging.exception() from
logging.error() inside an except block?
A. logging.exception() automatically includes the traceback and must be called from an exception handler. B. logging.error() always includes the traceback, while logging.exception() does not. C. Both are identical in output and differ only in severity level. D. logging.exception() suppresses the exception and prevents propagation.
RATIONALE logging.exception() logs at ERROR level and appends the current exception's traceback; it is intended for use inside except. B reverses the behavior, C ignores the traceback difference, and D is false-logging does not alter exception propagation.
Question 18
A script uses requests.Session() to call multiple endpoints on the same host.
Which benefit most directly improves automation performance and reliability?
A. It automatically retries failed requests with exponential backoff. B. It reuses the underlying TCP connection and persists headers/cookies across requests. C. It converts all responses to JSON automatically. D. It bypasses TLS certificate verification for speed.
RATIONALE A Session reuses connections (keep-alive) and persists headers/cookies, reducing latency and simplifying auth. A is false (retries require HTTPAdapter/Retry), C is false, and D would be a security regression.
Question 19
In MailHog, a test must assert that an email's body contains a specific one-time
code. Which approach most reliably extracts the code for assertion in an
automated test?
A. Query MailHog's HTTP API (e.g., /api/v2/messages) and parse the JSON body for the code. B. Read MailHog's SMTP debug log and grep for the code. C. Open the MailHog UI manually and copy the code. D. Use IMAP to fetch from MailHog, since MailHog exposes IMAP on port 143 by default.
RATIONALE MailHog exposes a JSON API (v2) that automated tests can query and parse deterministically. B is unreliable, C is not automated, and D is false-MailHog does not provide an IMAP server by default.
Question 20
A script defines a custom exception class APIError(Exception) and raises it
inside a function. Which except clause will catch it while also catching
built-in ValueError?
A. except APIError or ValueError: B. except (APIError, ValueError): C. except APIError, ValueError:
RATIONALE The Retry adapter with backoff_factor and status_forcelist provides built-in, configurable retry logic that respects idempotency and avoids busy loops. Option A risks infinite loops and hides errors; C re-raises too early; D relies on unreliable OS-level behavior and does not handle HTTP status codes.
Question 22
A developer configures MailHog for local email testing. The application sends
an email via SMTP to localhost:1025, but MailHog does not display the
message. The application logs show `SMTPAuthenticationError: 535
Authentication failed`. Which configuration change is MOST appropriate?
A. Enable TLS on MailHog by setting --smtp-tls and provide a valid certificate. B. Remove or disable SMTP authentication in the application's email settings, as MailHog does not require authentication by default. C. Change the SMTP port to 25 and use the system's default mail transfer agent. D. Configure the application to use the MailHog API endpoint on port 8025 instead of SMTP.
RATIONALE MailHog's SMTP server accepts unauthenticated connections by default; the error indicates the client is attempting authentication. Disabling auth resolves it. TLS and port changes are irrelevant; the API endpoint is for retrieving messages, not sending.
Question 23
In a Python logging configuration, a developer sets up a RotatingFileHandler
with maxBytes=1024 and backupCount=3. After the log file exceeds 1024
bytes multiple times, how many total log files exist, and what happens when
the fourth rotation occurs?
A. Four files exist; the oldest is deleted and a new file is created. B. Three files exist; the current log is overwritten and no backups are kept. C. Four files exist; the current log is renamed to .1, and the previous .3 is deleted. D. Two files exist; the handler stops logging until the file is manually cleared.
RATIONALE RotatingFileHandler keeps the current file plus backupCount rotated files (e.g., .1, .2, .3). On rotation, .3 is removed, .2->.3, .1->.2, and the current becomes .1, so four files total. Options A, B, and D misstate the handler's behavior.
Question 24
A Python script uses try/except/else/finally to interact with a database. The
try block executes a query and raises a DatabaseError. The except block
handles it, but the else block also runs. Which statement about the else
block is correct?
A. The else block runs only if the try block completes without raising an exception. B. The else block runs regardless of whether an exception occurred. C. The else block runs only if an exception is raised and not caught. D. The else block runs before the except block if both are present.
Question 26
An API returns a JSON payload with nested fields. A Python script uses
response.json() but occasionally receives a 204 No Content response, causing
a json.decoder.JSONDecodeError. Which handling strategy is MOST robust?
A. Check response.status_code == 204 before calling .json(), and return None or an empty dict for that case. B. Wrap .json() in a try/except JSONDecodeError and log the raw text. C. Set response.encoding = 'utf-8' before calling .json(). D. Use response.text and parse with json.loads() after stripping whitespace.
RATIONALE A 204 response has no body, so calling .json() is invalid. Checking status code first prevents the error. Option B catches the error but doesn't prevent it; C and D do not address the empty body issue.
Question 27
A Python script uses smtplib.SMTP to send emails through MailHog. The
script must handle transient network failures and ensure the connection is
closed even if an exception occurs. Which code pattern BEST achieves this?
A. Use a with smtplib.SMTP('localhost', 1025) as smtp: block and send the email inside, allowing automatic cleanup. B. Create the SMTP object, send the email, and call smtp.quit() in a finally block. C. Use smtp = smtplib.SMTP('localhost', 1025) and rely on garbage collection to close the connection. D. Wrap the send in a try/except and call smtp.close() only if an exception occurs.
Correct Answer: A - Use a with smtplib.SMTP('localhost', 1025) as smtp: block and send the email inside, allowing automatic cleanup.
RATIONALE The context manager (with statement) ensures quit() is called even if an exception occurs, providing clean resource management. Option B also works but is more verbose; C is unreliable; D fails to close on success.
Question 28
A developer configures a Python logger with a StreamHandler and a
FileHandler. The logger's level is set to DEBUG, but the StreamHandler
level is WARNING and the FileHandler level is INFO. A DEBUG
message is logged. What is the outcome?
A. The message appears in both the console and the file. B. The message appears only in the file. C. The message appears only in the console. D. The message is not recorded by either handler.
RATIONALE The logger's level (DEBUG) allows the message to be processed, but each handler filters independently. The StreamHandler (WARNING) and FileHandler (INFO) both ignore DEBUG, so the message is not recorded. Options A, B, and C incorrectly assume one handler would accept it.