Docsity

WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1,, Exams of Nursing

Toggle sidebar
bg1
WGU D522 Python for IT Automation API, MailHog,
Logging & Exception Handling Guide Task 1,
Exams of Nursing - Complete 50 Verified Q&A with
Answers & Rationales for Exam Prep
Q1
In Python's logging module, what happens when a logger's level is NOTSET and propagate is False?
A. It inherits the effective level from its parent logger.
B. It defaults to WARNING level and ignores parent settings.
C. It processes all messages regardless of level.
D. It raises a ValueError due to invalid configuration.
Answer: A
Rationale: A logger with level NOTSET (0) inherits its effective level from the nearest ancestor with a
level set. The propagate attribute only controls whether records are passed to ancestor handlers, not level
inheritance. Thus, the effective level is determined by the parent, making A correct. B is false because
NOTSET does not default to WARNING; C is false because level filtering still applies; D is false because
NOTSET is valid.
Q2
When using requests to call an API that returns 429, which strategy best implements exponential backoff
with jitter?
A. Retry immediately after a fixed delay of 1 second.
B. Use a loop with sleep time doubling each attempt plus random jitter.
C. Ignore the error and proceed to the next request.
D. Set a timeout parameter and rely on automatic retries.
Answer: B
Rationale: Exponential backoff with jitter involves waiting increasing intervals (e.g., 2^attempt seconds)
plus random jitter to avoid thundering herd. B describes this correctly. A uses fixed delay, which is not
exponential; C ignores the error, which is poor practice; D relies on timeout, which does not implement
backoff.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1, and more Exams Nursing in PDF only on Docsity!

WGU D522 Python for IT Automation API, MailHog,

Logging & Exception Handling Guide Task 1,

Exams of Nursing - Complete 50 Verified Q&A with

Answers & Rationales for Exam Prep

Q

In Python's logging module, what happens when a logger's level is NOTSET and propagate is False?

A. It inherits the effective level from its parent logger. B. It defaults to WARNING level and ignores parent settings. C. It processes all messages regardless of level. D. It raises a ValueError due to invalid configuration.

Answer: A Rationale: A logger with level NOTSET (0) inherits its effective level from the nearest ancestor with a level set. The propagate attribute only controls whether records are passed to ancestor handlers, not level inheritance. Thus, the effective level is determined by the parent, making A correct. B is false because NOTSET does not default to WARNING; C is false because level filtering still applies; D is false because NOTSET is valid.

Q

When using requests to call an API that returns 429, which strategy best implements exponential backoff with jitter?

A. Retry immediately after a fixed delay of 1 second. B. Use a loop with sleep time doubling each attempt plus random jitter. C. Ignore the error and proceed to the next request. D. Set a timeout parameter and rely on automatic retries.

Answer: B Rationale: Exponential backoff with jitter involves waiting increasing intervals (e.g., 2^attempt seconds) plus random jitter to avoid thundering herd. B describes this correctly. A uses fixed delay, which is not exponential; C ignores the error, which is poor practice; D relies on timeout, which does not implement backoff.

In MailHog, which API endpoint retrieves all messages in JSON format for automated testing?

A. GET /api/v2/messages B. GET /api/v1/messages C. POST /api/v1/messages D. GET /api/v1/mail

Answer: A Rationale: MailHog's API v2 provides GET /api/v2/messages to list all messages. v1 is deprecated and uses /api/v1/messages, but v2 is current. POST is for sending, and /api/v1/mail does not exist. Thus A is correct.

Q

Which Python exception should be caught to handle a JSON decoding error from response.json()?

A. requests.exceptions.JSONDecodeError B. json.JSONDecodeError C. ValueError D. KeyError

Answer: B Rationale: response.json() uses the json module and raises json.JSONDecodeError (a subclass of ValueError) when parsing fails. requests.exceptions.JSONDecodeError exists in newer requests versions but inherits from json.JSONDecodeError; however, the canonical exception is json.JSONDecodeError. Catching ValueError would also work but is broader. B is the specific and correct exception.

Q

What is the primary purpose of a logging Formatter in Python?

A. To define the layout of log records in the final output. B. To filter log records based on level. C. To send log records to a file or console. D. To manage the hierarchical structure of loggers.

Answer: A Rationale: A Formatter specifies the format string that determines how a log record is rendered as text. Filters handle level-based filtering (B), handlers send records to destinations (C), and loggers manage hierarchy (D). Thus A is correct.

When automating email validation with MailHog, which method retrieves the body of a specific message?

A. GET /api/v1/messages/{id}/body B. GET /api/v2/messages/{id} then parse JSON body field. C. POST /api/v1/messages/{id}/body D. GET /api/v1/messages/{id}/raw

Answer: B Rationale: MailHog API v2 provides GET /api/v2/messages/{id} returning full message details including body. There is no /body endpoint in v1. POST is for sending, and /raw is not standard. Thus B is correct.

Q

Which exception is raised when a requests call exceeds the specified timeout?

A. requests.exceptions.ConnectionError B. requests.exceptions.Timeout C. requests.exceptions.RequestException D. requests.exceptions.HTTPError

Answer: B Rationale: requests.exceptions.Timeout is raised when a request times out. ConnectionError is for network issues, RequestException is the base class, and HTTPError is for bad status codes. Thus B is correct.

Q

Which Python construct best isolates API call failures while preserving original traceback context for debugging?

A. A bare except clause that logs a generic error message B. try/except with 'raise ... from e' chaining C. A finally block that suppresses the exception D. Using assert statements to validate API responses

Answer: B Rationale: Exception chaining with 'raise NewError from e' preserves the original traceback and causal context, which is essential for debugging API failures. A bare except hides the exception type and traceback, finally does not suppress unless combined with return/continue, and assert is removed under -O and unsuitable for runtime error handling.

In MailHog, which SMTP behavior explains why messages appear in the web UI but are never delivered externally?

A. MailHog acts as a sink that accepts and stores messages without relaying B. MailHog requires TLS client certificates for all outbound relays C. MailHog rejects messages lacking DKIM signatures by default D. MailHog only supports IMAP retrieval, not SMTP submission

Answer: A Rationale: MailHog is a testing tool that captures SMTP traffic and exposes it via a web UI/API; it does not relay to external MTAs. It does not require client certificates, does not enforce DKIM, and does support SMTP (not just IMAP).

Q

A script uses logging.basicConfig(level=logging.INFO) then a library calls basicConfig(level=DEBUG). What level is effective?

A. DEBUG, because the later call overrides the root level B. INFO, because basicConfig is a no-op after the root handler exists C. WARNING, the default when conflicting configurations occur D. It raises a ConfigurationError at import time

Answer: B Rationale: logging.basicConfig only configures the root logger if it has no handlers; subsequent calls without force=True are no-ops. Therefore the original INFO level persists, and no exception is raised.

Q

Which requests pattern correctly implements retry with exponential backoff for transient HTTP 503 responses?

A. Wrap requests.get in a while loop with time.sleep(2**attempt) on 503 B. Set requests.adapters.HTTPAdapter(max_retries=Retry(total=5, backoff_factor=1, status_forcelist=[503])) C. Use requests.Session with hooks that re-raise on 503 D. Catch requests.exceptions.ConnectionError and retry immediately

Answer: B Rationale: The Retry object with backoff_factor and status_forcelist integrates with HTTPAdapter to automatically retry 503 responses with exponential backoff. Manual loops risk missing edge cases, hooks do not retry, and ConnectionError does not cover 503 status responses.

Which logging configuration prevents duplicate log lines when a module is imported multiple times?

A. Call logging.basicConfig in every module B. Use logging.getLogger(name) and configure handlers once at entry point C. Set propagate=False on the root logger D. Use print statements instead of logging

Answer: B Rationale: Using module-level loggers via getLogger(name) and configuring handlers once at the application entry point avoids duplicate handlers and messages. Repeated basicConfig calls are no-ops after the first, propagate=False on root is invalid, and print lacks logging features.

Q

Which HTTP status code range should an automation script treat as retryable for idempotent GET requests?

A. 4xx client errors B. 5xx server errors, especially 500, 502, 503, 504 C. 3xx redirects D. 1xx informational

Answer: B Rationale: 5xx errors often indicate transient server-side issues that may resolve on retry for idempotent requests. 4xx errors are client mistakes unlikely to succeed on retry, 3xx are redirects handled by the client, and 1xx are informational.

Q

Which context manager usage ensures a file or network resource is released even if an exception occurs?

A. Manual open() and close() calls in sequence B. with statement around the resource acquisition C. try/except without finally D. Relying on garbage collection to close resources

Answer: B Rationale: The with statement guarantees exit is called, releasing resources even on exceptions. Manual close can be skipped on error, try/except without finally may not release, and relying on GC is nondeterministic and unsafe.

Which Python construct most reliably enforces cleanup when a MailHog API call raises inside nested context managers?

A. try/except/else with a finally block B. A bare except clause followed by cleanup C. A with statement using contextlib.ExitStack D. Relying on the garbage collector's del

Answer: C Rationale: ExitStack composes multiple context managers and guarantees LIFO exit invocation even when inner calls raise, unlike a bare except or GC-dependent del. A finally block works for one resource but does not manage nested context-manager semantics as cleanly, and bare except also swallows KeyboardInterrupt/SystemExit.

Q

A requests.post to MailHog returns 200 but no message appears in the inbox. Which diagnostic step best isolates the cause?

A. Increase the requests timeout value B. Inspect the MailHog API response body and the /api/v2/messages endpoint C. Switch from requests to urllib D. Add a retry decorator around the POST

Answer: B Rationale: MailHog's /api/v2/messages endpoint reveals whether the message was accepted and stored; the POST response body may carry validation errors even with HTTP 200. Timeouts, library swaps, and retries do not diagnose an acceptance/storage mismatch.

Q

Which logging configuration best prevents duplicate log lines when a library and application both call basicConfig?

A. Call logging.basicConfig twice with different formats B. Use logging.getLogger(name) and configure handlers once at the application entry point C. Set the root logger level to DEBUG in every module D. Attach a new StreamHandler in each module's top-level code

Answer: B Rationale: basicConfig is a no-op after the root logger already has handlers, but per-module handler attachment causes duplicate emissions. Configuring handlers once at entry and using module-level getLogger(name) is the standard, duplicate-free pattern.

A MailHog SMTP send silently drops messages. Which configuration error is most likely?

A. Using port 1025 instead of 25 B. Sending to a domain MailHog does not accept without a wildcard C. Omitting the Subject header D. Using MIMEText instead of MIMEMultipart

Answer: B Rationale: MailHog accepts mail for configured domains; without a wildcard or matching domain, messages may be rejected or dropped. Port 1025 is MailHog's default SMTP port, and Subject/MIME type do not cause silent drops.

Q

Which logging formatter field best correlates log entries across distributed automation workers?

A. %(asctime)s B. %(levelname)s C. %(process)d D. A custom %(request_id)s injected via a LoggerAdapter or filter

Answer: D Rationale: A request/correlation ID propagated via LoggerAdapter or a logging.Filter enables cross-worker tracing of a single logical operation. Timestamps, levels, and PIDs are useful but do not uniquely correlate a request across processes.

Q

Which approach most safely handles a JSONDecodeError when parsing an API response that may be empty?

A. Assume response.json() always succeeds B. Check response.status_code and response.text before calling response.json(), catching JSONDecodeError C. Wrap in except Exception: return {} D. Use eval(response.text) instead

Answer: B Rationale: Empty or non-JSON bodies raise JSONDecodeError; guarding on status/text and catching the specific exception preserves diagnosability. Broad Exception swallowing hides bugs, and eval is unsafe and unrelated.

Which exception-handling anti-pattern most directly causes lost root-cause information in automated pipelines?

A. Using raise NewError from original B. Using raise NewError() without chaining inside except C. Logging exc_info=True in the handler D. Catching specific exception subclasses

Answer: B Rationale: Raising a new exception without 'from original' discards cause and obscures the original traceback. Explicit chaining, exc_info logging, and specific catches all preserve diagnostic context.

Q

Which requests construct guarantees automatic retries on connection errors without manual loop coding?

A. requests.get(url, retries=3) B. requests.Session() mounted with HTTPAdapter(max_retries=Retry(total=3)) C. requests.get(url, timeout=3, allow_redirects=True) D. urllib.request.urlopen(url, retries=3)

Answer: B Rationale: Only mounting an HTTPAdapter configured with urllib3 Retry on a Session enables automatic connection-error retries; requests.get has no retries parameter, timeout/allow_redirects control other behavior, and urllib.request has no retries argument.

Q

MailHog captures SMTP traffic; which assertion about its default behavior is accurate?

A. It relays captured messages to real recipients after inspection. B. It stores messages in memory and exposes them via a web UI/API, never delivering externally. C. It requires TLS client certificates before accepting any message. D. It permanently deletes messages immediately after the SMTP DATA command.

Answer: B Rationale: MailHog is a disposable SMTP sink that keeps messages in memory and exposes them through its web UI and HTTP API; it does not relay to external recipients, mandate client certificates, or delete messages on receipt.

An API returns 429 with Retry-After: 30; which client action best follows RFC 9110?

A. Immediately resend the request up to three times. B. Wait at least 30 seconds before retrying the request. C. Treat 429 as a permanent failure and abort. D. Switch to HTTP/1.0 and resend without delay.

Answer: B Rationale: RFC 9110 defines Retry-After as the minimum delay before retrying; immediate retries worsen throttling, 429 is transient, and downgrading HTTP does not address rate limiting.

Q

Which logging configuration prevents duplicate handler output when a library logger propagates?

A. Set propagate=False on the library logger or avoid duplicate root handlers. B. Increase the formatter verbosity on the library logger. C. Attach a second StreamHandler to the library logger. D. Set the library logger level to NOTSET.

Answer: A Rationale: Duplicate lines arise when both the library logger and root have handlers and propagation is enabled; disabling propagation or avoiding duplicate handlers fixes it, while adding handlers or NOTSET worsens duplication.

Q

Which exception should wrap a JSONDecodeError when re-raising for callers, preserving the original?

A. raise APIResponseError('bad json') from exc B. raise APIResponseError('bad json') C. raise exc D. sys.exit(1)

Answer: A Rationale: Using 'raise ... from exc' sets cause and preserves the traceback chain; raising without from loses explicit context, bare raise exc resets context, and sys.exit terminates rather than signaling a typed error.

Which SMTP interaction correctly simulates MailHog message capture in a test?

A. Connect to MailHog's SMTP port and issue EHLO, MAIL FROM, RCPT TO, DATA. B. POST the raw message to MailHog's web UI root path. C. Use IMAP to append a message to MailHog's inbox. D. Send via sendmail binary pointed at /dev/null.

Answer: A Rationale: MailHog listens on an SMTP port and captures messages through the standard SMTP dialogue; it does not accept raw POSTs at the UI root, does not expose IMAP append, and sendmail to /dev/null captures nothing.

Q

Which pattern best isolates API credentials in an automation script under version control?

A. Hard-code the token in the script for reproducibility. B. Read from environment variables or a git-ignored secrets file. C. Commit a .env file containing the token to the repo. D. Embed the token in the URL query string and log it.

Answer: B Rationale: Reading secrets from environment variables or git-ignored files keeps them out of version control; hard-coding, committing .env, or logging tokens in URLs exposes credentials and violates security best practices.

Q

Which requests call correctly posts JSON to an API with a timeout, using the modern recommended pattern?

A. requests.post(url, json=payload, timeout=5) B. requests.post(url, data=payload, timeout=5) C. requests.post(url, json=payload) D. requests.post(url, params=payload, timeout=5)

Answer: A Rationale: Passing json= serializes the dict and sets Content-Type: application/json, and timeout= prevents indefinite blocking. data= sends form-encoded data, params= appends to the query string, and omitting timeout risks hanging the automation.

MailHog is running locally; an app sends mail but nothing appears in its UI. Which configuration issue is most likely?

A. SMTP pointed to port 1025 but the app targets port 8025 B. The app uses STARTTLS on port 1025 without TLS support C. MailHog requires authentication credentials not supplied D. The recipient address domain is not resolvable externally

Answer: A Rationale: MailHog listens for SMTP on 1025 and serves its web UI/API on 8025; pointing SMTP at 8025 yields no captured messages. MailHog accepts unauthenticated SMTP by default and does not deliver externally, so domain resolution is irrelevant.

Q

Which approach most reliably validates that an automated email contains the expected dynamic order ID using MailHog's API?

A. Query /api/v2/messages, parse JSON, and assert the ID appears in the decoded body B. Scrape the MailHog HTML UI with regex against the full page source C. Poll the SMTP port for a banner containing the order ID D. Check the local filesystem for MailHog's mbox file contents

Answer: A Rationale: The v2 messages API returns structured JSON including MIME content, enabling robust parsing and assertion. UI scraping is brittle, SMTP banners carry no message content, and MailHog stores messages in memory unless configured otherwise.

Q

A function must distinguish a missing config key from an invalid value. Which exception strategy best expresses this?

A. Raise KeyError for absence and ValueError for malformed values, catching each distinctly B. Raise a single generic Exception with a combined message C. Return None for both cases and let the caller inspect D. Use assert statements that vanish under python -O

Answer: A Rationale: Distinct built-in exceptions let callers handle absence versus malformation precisely. A generic Exception erases type information, returning None conflates states, and asserts are stripped under optimization, making them unsuitable for runtime validation.

Which pattern correctly propagates correlation IDs across API calls and log records in a multithreaded automation?

A. A contextvars.ContextVar injected into a logging Filter and request headers B. A module-level global string mutated by each thread C. A thread-local variable read only at program startup D. Embedding the ID only in exception messages

Answer: A Rationale: ContextVar provides per-task/thread isolation and integrates with logging Filters and outbound headers. A global string races across threads, startup-only reads miss later IDs, and exception-only embedding loses context on successful paths.

Q

An API returns 429 with Retry-After: 30. What is the correct client behavior under current HTTP semantics?

A. Wait at least 30 seconds before retrying the same request B. Immediately retry with the same headers to confirm the limit C. Treat 429 as a permanent failure and abort the workflow D. Switch to HTTP/1.0 and resend without delay

Answer: A Rationale: Retry-After specifies the minimum delay before retrying; honoring it avoids further throttling. Immediate retries worsen rate limiting, 429 is transient, and downgrading HTTP does not affect server-side rate limits.

Q

Which pytest construct most appropriately asserts that a malformed payload raises a specific custom exception with a message?

A. with pytest.raises(ValidationError, match='missing field'): B. try/except around the call with a boolean flag assertion C. assertRaisesRegex from unittest.TestCase only D. A bare assert on the function's return value being None

Answer: A Rationale: pytest.raises with match asserts both exception type and message pattern idiomatically. Manual try/except flags are verbose and error-prone, unittest's assertRaisesRegex requires TestCase inheritance, and asserting None return does not verify the exception.