Docsity

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

Toggle sidebar
bg1
Page 1
WGU D522 PYTHON FOR IT AUTOMATION API,
MAILHOG, LOGGING & EXCEPTION HANDLING
GUIDE TASK 1 & TASK 2 SUPPORT
50 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Design and implement Python scripts that interact with REST APIs using requests, including
authentication, error handling, and pagination
2 Configure and utilize MailHog for testing email sending functionality in automated workflows
3 Implement robust logging and exception handling strategies to ensure reliable and maintainable
automation scripts
4 WGU D522 Python for IT Automation API
5 MailHog
6 Logging & Exception Handling Guide Task 1 & Task 2 Support
7 Foundations of Python for IT Automation
8 Applied Python for IT Automation
9 Advanced Python for IT Automation
10 Python for IT Automation Review
ABSTRACT
This study document brings together 50 carefully worded exam questions drawn from WGU D522
Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2
Support, with the strongest emphasis placed on Design and implement Python scripts that interact
with REST APIs using requests, including authentication, error handling, and pagination, Configure
and utilize MailHog for testing email sending functionality in automated workflows and Implement
robust logging and exception handling strategies to ensure reliable and maintainable automation
scripts. 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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Partial preview of the text

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

WGU D522 PYTHON FOR IT AUTOMATION API,

MAILHOG, LOGGING & EXCEPTION HANDLING

GUIDE TASK 1 & TASK 2 SUPPORT

50 QUESTIONS

TABLE OF CONTENTS

# TOPIC

1 Design and implement Python scripts that interact with REST APIs using requests, including authentication, error handling, and pagination

2 Configure and utilize MailHog for testing email sending functionality in automated workflows

3 Implement robust logging and exception handling strategies to ensure reliable and maintainable automation scripts

4 WGU D522 Python for IT Automation API

5 MailHog

6 Logging & Exception Handling Guide Task 1 & Task 2 Support

7 Foundations of Python for IT Automation

8 Applied Python for IT Automation

9 Advanced Python for IT Automation

10 Python for IT Automation Review

ABSTRACT

This study document brings together 50 carefully worded exam questions drawn from WGU D Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2 Support, with the strongest emphasis placed on Design and implement Python scripts that interact with REST APIs using requests, including authentication, error handling, and pagination, Configure and utilize MailHog for testing email sending functionality in automated workflows and Implement robust logging and exception handling strategies to ensure reliable and maintainable automation scripts. 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.

Q1 DESIGN AND IMPLEMENT PYTHON SCRIPTS THAT INTERACT WITH REST APIS USING

REQUESTS, INCLUDING AUTHENTICATION, ERROR HANDLING, AND PAGINATION

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. CORRECT

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.

Q2 DESIGN AND IMPLEMENT PYTHON SCRIPTS THAT INTERACT WITH REST APIS USING

REQUESTS, INCLUDING AUTHENTICATION, ERROR HANDLING, AND PAGINATION

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. CORRECT

B. Use MailHog's cloud service by signing up for an API key, then send emails through its REST API.

C. Configure the script to use MailHog's SMTP server at mailhog.example.com:25, which requires no authentication.

D. Install MailHog as a Python package and import it directly into the script to intercept emails.

RATIONALE: MailHog is a local SMTP server that captures emails, with a web UI for inspection. Option A correctly describes its typical use. Option B is false; MailHog is not a cloud service. Option C is incorrect because MailHog runs locally by default. Option D is wrong; MailHog is a standalone binary, not a Python library.

Q5 DESIGN AND IMPLEMENT PYTHON SCRIPTS THAT INTERACT WITH REST APIS USING

REQUESTS, INCLUDING AUTHENTICATION, ERROR HANDLING, AND PAGINATION

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. CORRECT

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.

Q6 CONFIGURE AND UTILIZE MAILHOG FOR TESTING EMAIL SENDING FUNCTIONALITY IN

AUTOMATED WORKFLOWS

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. CORRECT

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 /api/v2/messages endpoint to fetch messages.

D. Start MailHog with -smtp-bind-addr 0.0.0.0:1025 and use the /api/v1/messages endpoint to fetch messages.

RATIONALE: MailHog's default storage is in-memory, and the API endpoint for messages is /api/v2/messages. Option A correctly binds SMTP to all interfaces. Option B uses an incorrect flag and endpoint. Option C binds the API but not SMTP. Option D uses an outdated API endpoint.

Q7 CONFIGURE AND UTILIZE MAILHOG FOR TESTING EMAIL SENDING FUNCTIONALITY IN

AUTOMATED WORKFLOWS

When implementing logging in a Python automation script that runs as a systemd

service, which practice ensures that log messages are captured by journald and

also available in a file?

A. Configure the logging module to write to sys.stdout and rely on systemd to capture stdout.

B. Use the systemd.journal module to send logs directly to journald, and also add a FileHandler.

C. Set up a SysLogHandler with address '/dev/log' and a FileHandler. CORRECT

D. Use logging.basicConfig with filename and stream, and set systemd to capture the file.

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.

Q8 CONFIGURE AND UTILIZE MAILHOG FOR TESTING EMAIL SENDING FUNCTIONALITY IN

AUTOMATED WORKFLOWS

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 CORRECT

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.

Q10 CONFIGURE AND UTILIZE MAILHOG FOR TESTING EMAIL SENDING FUNCTIONALITY IN

AUTOMATED WORKFLOWS

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. CORRECT

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.

RATIONALE: Option A sets the root logger to DEBUG so all messages are processed, then the FileHandler logs DEBUG and above, while the StreamHandler logs only ERROR and above. Option B sets root to ERROR, so DEBUG and INFO are ignored. Option C swaps the handlers. Option D logs everything to both.

Q11 IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING STRATEGIES TO ENSURE

RELIABLE AND MAINTAINABLE AUTOMATION SCRIPTS

A Python automation script uses the requests library to call a REST API. The

endpoint returns HTTP 429 with a Retry-After: 30 header. Which implementation

most correctly handles this response to satisfy production-grade automation

requirements?

A. Immediately retry the request in a tight loop until a 200 status is received.

B. Raise a custom exception and terminate the script, since 429 indicates an unrecoverable client error.

C. Read the Retry-After header, sleep for the indicated seconds, then retry with exponential backoff and a capped retry count. CORRECT

D. Ignore the header and retry after a fixed 1-second delay regardless of the server's guidance.

RATIONALE: HTTP 429 is a transient rate-limit signal; honoring Retry-After and combining it with exponential backoff and a retry cap is the accepted production pattern. Option A causes a tight loop that worsens throttling, B misclassifies a recoverable error, and D ignores the server's explicit guidance.

Q12 IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING STRATEGIES TO ENSURE

RELIABLE AND MAINTAINABLE AUTOMATION SCRIPTS

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 1025. Which

is the most likely configuration cause?

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. CORRECT

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.

Q13 IMPLEMENT ROBUST LOGGING AND EXCEPTION HANDLING STRATEGIES TO ENSURE

RELIABLE AND MAINTAINABLE AUTOMATION SCRIPTS

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. CORRECT

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.

Q16 WGU D522 PYTHON FOR IT AUTOMATION API

A script parses JSON from an API using response.json(). Occasionally the

response is HTML (e.g., a proxy error page). Which exception-handling approach

is most robust?

A. Wrap the call in try/except json.JSONDecodeError and log the raw response body for diagnosis. CORRECT

B. Use response.text and eval() to parse the content.

C. Assume the API always returns JSON and skip error handling.

D. Catch Exception broadly and silently pass.

RATIONALE: response.json() raises json.JSONDecodeError on non-JSON payloads; catching it and logging the raw body enables diagnosis. B is unsafe (eval), C ignores real failure modes, and D swallows errors without visibility.

Q17 WGU D522 PYTHON FOR IT AUTOMATION API

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. CORRECT

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.

Q18 WGU D522 PYTHON FOR IT AUTOMATION API

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. CORRECT

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.

Q19 WGU D522 PYTHON FOR IT AUTOMATION API

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. CORRECT

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.

Q22 MAILHOG

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. CORRECT

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.

Q23 MAILHOG

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. CORRECT

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.

Q24 MAILHOG

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. CORRECT

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.

RATIONALE: The else clause executes only when the try block finishes without an exception. If an exception is raised and caught, else is skipped. Options B, C, and D contradict this control flow.

Q25 MAILHOG

A developer wants to log exceptions with full traceback information while also

sending a concise alert email. Which combination of logging and exception

handling BEST achieves this without duplicating traceback output?

A. Use logging.error(str(e)) in the except block and send the email with traceback.format_exc().

B. Use logging.exception('Error occurred') in the except block and send the email with str(e) only.

C. Use logging.error('Error occurred', exc_info=True) and send the email with traceback.format_exc(). CORRECT

D. Use logging.critical(e) and send the email with repr(e).

RATIONALE: logging.error(..., exc_info=True) includes the traceback in the log, while traceback.format_exc() provides the same for the email without duplicating in the log. Option A logs only the message, B uses logging.exception (which already includes traceback) and sends a short email, D lacks traceback detail.

Q28 LOGGING & EXCEPTION HANDLING GUIDE TASK 1 & TASK 2 SUPPORT

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. CORRECT

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.

Q29 LOGGING & EXCEPTION HANDLING GUIDE TASK 1 & TASK 2 SUPPORT

A Python script uses requests to call an API that requires a Bearer token. The

token expires every hour. Which approach BEST ensures the script continues to

work without manual intervention?

A. Store the token in a global variable and refresh it only when a 401 response is received, then retry the request.

B. Use a session with an HTTPAdapter that automatically refreshes the token on every request.

C. Implement a custom AuthBase subclass that checks token expiry before each request and refreshes if needed. CORRECT

D. Set a Retry object with status_forcelist=[401] to automatically retry after refreshing the token.

RATIONALE: A custom AuthBase subclass can encapsulate token management, checking expiry and refreshing before the request is sent. Option A only refreshes after failure; B is not how adapters work; D's Retry does not refresh tokens, only retries the same request.

Q30 LOGGING & EXCEPTION HANDLING GUIDE TASK 1 & TASK 2 SUPPORT

A developer wants to log messages to both the console and a file, but with

different formats: console should show LEVEL: message, file should show

TIMESTAMP - LEVEL - message. Which logging configuration achieves this?

A. Use a single Formatter and set different levels for each handler.

B. Create two handlers, assign a distinct Formatter to each, and attach both to the logger. CORRECT

C. Use logging.basicConfig with format and filename parameters.

D. Use a Filter to modify the message format based on the handler.

RATIONALE: Each handler can have its own Formatter, allowing different formats for console and file. Option A uses one format for both; C sets a single format; D misuses filters, which do not alter format strings.

Q31 FOUNDATIONS OF PYTHON FOR IT AUTOMATION

A Python automation script uses requests to call a REST API that returns a 429

status with a Retry-After header. Which implementation most correctly handles

transient rate limiting while preserving idempotency and avoiding thundering-herd

retries?

A. Immediately retry in a tight loop until a 200 response is received, ignoring Retry-After.

B. Sleep for a fixed 1 second and retry indefinitely on any non-2xx status.

C. Parse Retry-After, apply exponential backoff with jitter, cap attempts, and only retry idempotent methods. CORRECT

D. Raise a custom exception on the first 429 and log it at CRITICAL without retrying.

RATIONALE: Retry-After should be honored, and exponential backoff with jitter prevents synchronized retry storms while capping attempts avoids infinite loops. Retrying only idempotent methods (GET, PUT, DELETE) preserves safety. Tight loops, fixed sleeps, or no retry all mishandle transient rate limiting.

Q34 FOUNDATIONS OF PYTHON FOR IT AUTOMATION

Which try/except/finally structure correctly guarantees that a file handle is

released and that a specific network error is logged without masking an unrelated

ValueError?

A. try: ... except Exception: log; finally: close

B. try: ... except (ConnectionError, TimeoutError) as e: log(e); finally: f.close() CORRECT

C. try: ... except: pass; finally: f.close()

D. try: ... except ConnectionError: log; else: f.close()

RATIONALE: Catching the specific network exceptions preserves unrelated errors like ValueError, and finally always runs to close the handle. Catching bare Exception or using bare except masks or over-catches; using else to close only runs on success and skips cleanup on failure.

Q35 FOUNDATIONS OF PYTHON FOR IT AUTOMATION

A log record is emitted at DEBUG level, but the root logger is set to INFO and a

handler is set to DEBUG. What is the observable behavior, and why?

A. The message is emitted because the handler's DEBUG level overrides the logger.

B. The message is suppressed because the logger's effective level gates emission before handlers run. CORRECT

C. The message is emitted twice due to level mismatch.

D. The message is emitted only if propagate is False.

RATIONALE: Logger level filtering occurs before handlers are invoked, so a DEBUG record is dropped when the effective logger level is INFO. Handler levels only filter records that reach them. Propagation and duplicate emission are unrelated to this gate.

Q36 APPLIED PYTHON FOR IT AUTOMATION

An API returns paginated results with a 'next' cursor. Which approach best

ensures a complete, duplicate-free dataset while respecting rate limits?

A. Loop while 'next' is non-null, follow the cursor, and track seen IDs to deduplicate. CORRECT

B. Request page=1..N in parallel with no cursor handling.

C. Increase page size to the maximum and assume a single request returns all data.

D. Retry the same first-page request until the dataset stops growing.

RATIONALE: Cursor-based pagination requires following the 'next' token until exhausted; tracking seen IDs guards against duplicates from shifting datasets. Parallel fixed pages, oversized single requests, and repeated first-page calls do not guarantee completeness or deduplication.

Q37 APPLIED PYTHON FOR IT AUTOMATION

Which statement about MailHog's HTTP API versus its SMTP interface is most

accurate for automated test assertions?

A. SMTP is used to send mail into MailHog; the HTTP API is used to query, inspect, and delete captured messages. CORRECT

B. The HTTP API sends mail; SMTP is only for retrieving messages.

C. Both interfaces are read-only and cannot delete messages.

D. SMTP and HTTP API are interchangeable and both support message deletion.

RATIONALE: MailHog receives messages via SMTP on port 1025 and exposes an HTTP API (default 8025) for listing, inspecting, and deleting messages. The HTTP API does not send mail, and deletion is an API capability, not an SMTP one. The other options invert or misstate these roles.