Docsity

WGU D522 PYTHON FOR IT AUTOMATION API MAILHOG LOGGING AND EXCEPTION HANDLING GUIDE TASK 1,, Exams of Nursing

Toggle sidebar
bg1
WGU D522 PYTHON FOR IT AUTOMATION API
MAILHOG LOGGING AND EXCEPTION HANDLING
GUIDE TASK 1, Exams of Nursing
This exam assesses advanced Python fundamentals essential for IT automation, focusing on data types, control
flow, functions, and modules. Questions require multi-step reasoning, synthesis of concepts, and application to
novel automation scenarios, ensuring readiness for scripting complex IT tasks. It contains 50 multiple-choice
questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct.
Content is organized into 9 focused sections: Python Fundamentals for IT Automation (data types, control flow,
functions, modules), Working with APIs: HTTP methods, requests library, status codes, headers, and JSON
payloads, MailHog Email Testing: SMTP configuration, capturing and inspecting messages, API access, Logging
in Python: logging module, log levels, handlers, formatters, and log files, Exception Handling:
try/except/else/finally, raising exceptions, custom exceptions, File and Data Handling: reading/writing files,
parsing JSON and CSV, environment variables, Automation Script Design: modular functions, error resilience,
and idempotency, Testing and Debugging Automation Scripts: assertions, test runs, and troubleshooting, Security
and Best Practices: credential handling, input validation, and safe API usage. Targeted learning outcomes
include: Analyze and predict the behavior of Python code involving mutable data types, closures, and scoping
rules.; Design and evaluate control flow structures and function implementations for automation tasks.; Apply
module import semantics and package organization to solve IT automation problems.. Every item has been
Section 1: Python Fundamentals for IT Automation (data types, control flow, functions, modules)
(Questions 1-6)
1What is the output of this code?
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a)
b[0][0] = 99
print(a)
A) [[1, 2], [3, 4]]
B) [[99, 2], [3, 4]]
C) [[1, 2], [99, 4]]
D) [[99, 2], [99, 4]]
Answer: B
Rationale: copy.copy creates a shallow copy: the outer list is new, but inner lists
are shared references. Modifying b[0][0] changes the shared inner list, so a
reflects the change. Deep copy would be needed to avoid this.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download WGU D522 PYTHON FOR IT AUTOMATION API MAILHOG LOGGING AND EXCEPTION HANDLING GUIDE TASK 1, and more Exams Nursing in PDF only on Docsity!

WGU D522 PYTHON FOR IT AUTOMATION API

MAILHOG LOGGING AND EXCEPTION HANDLING

GUIDE TASK 1, Exams of Nursing

This exam assesses advanced Python fundamentals essential for IT automation, focusing on data types, control flow, functions, and modules. Questions require multi-step reasoning, synthesis of concepts, and application to novel automation scenarios, ensuring readiness for scripting complex IT tasks. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Content is organized into 9 focused sections: Python Fundamentals for IT Automation (data types, control flow, functions, modules), Working with APIs: HTTP methods, requests library, status codes, headers, and JSON payloads, MailHog Email Testing: SMTP configuration, capturing and inspecting messages, API access, Logging in Python: logging module, log levels, handlers, formatters, and log files, Exception Handling: try/except/else/finally, raising exceptions, custom exceptions, File and Data Handling: reading/writing files, parsing JSON and CSV, environment variables, Automation Script Design: modular functions, error resilience, and idempotency, Testing and Debugging Automation Scripts: assertions, test runs, and troubleshooting, Security and Best Practices: credential handling, input validation, and safe API usage. Targeted learning outcomes include: Analyze and predict the behavior of Python code involving mutable data types, closures, and scoping rules.; Design and evaluate control flow structures and function implementations for automation tasks.; Apply module import semantics and package organization to solve IT automation problems.. Every item has been

Section 1: Python Fundamentals for IT Automation (data types, control flow, functions, modules) (Questions 1-6)

1 What is the output of this code?

import copy a = [[1, 2], [3, 4]] b = copy.copy(a) b[0][0] = 99 print(a)

A) [[1, 2], [3, 4]] B) [[99, 2], [3, 4]] C) [[1, 2], [99, 4]] D) [[99, 2], [99, 4]]

Answer: B Rationale: copy.copy creates a shallow copy: the outer list is new, but inner lists are shared references. Modifying b[0][0] changes the shared inner list, so a reflects the change. Deep copy would be needed to avoid this.

2 What is the output of this code?

funcs = [] for i in range(3): funcs.append(lambda: i) print([f() for f in funcs])

A) [0, 1, 2] B) [2, 2, 2] C) [0, 0, 0] D) [3, 3, 3]

Answer: B Rationale: Lambdas capture the variable i by reference, not value. After the loop, i is 2, so all lambdas return 2. To capture each value, use a default argument or closure factory.

3 Which statement about Python's for-else construct is correct?

A) The else block executes only if the loop completes without a break. B) The else block executes only if the loop is exited via break. C) The else block executes after every iteration. D) The else block is executed only if an exception occurs.

Answer: A Rationale: In Python, the else clause of a for or while loop runs only if the loop terminates normally (i.e., no break). It does not run if the loop is exited via break. This is useful for search loops to determine if an item was found.

4 Given a module mymod.py with code:

print('module loading') all = ['func1'] def func1(): pass def func2(): pass

What happens when executing from mymod import *?

A) Prints 'module loading' and imports only func1. B) Prints 'module loading' and imports both func1 and func2. C) Does not print 'module loading' and imports only func1.

False. Thus only 0 == False is True.

Section 2: Working with APIs: HTTP methods, requests library, status codes, headers, and JSON payloads (Questions 7-12)

7 Which requests call correctly sends a JSON body with proper Content-Type for a REST API?

A) requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'}) B) requests.post(url, json=payload) C) requests.post(url, params=payload) D) requests.post(url, data=payload, headers={'Accept': 'application/json'})

Answer: B Rationale: The json= parameter automatically serializes the payload and sets Content-Type: application/json. Option A also works but is verbose and error-prone; the question asks for the correct idiomatic call, and B is the canonical requests approach. Options C and D misuse params (query string) and omit proper Content-Type, respectively.

8 A POST returns 201 with a Location header. What is the most appropriate next action in automation?

A) Retry the POST to ensure idempotency. B) Parse the response body for the created resource ID. C) Issue a GET to the URL in the Location header to retrieve the created resource. D) Treat 201 as an error and log the response.

Answer: C Rationale: HTTP 201 Created commonly includes a Location header pointing to the new resource; following it with GET is the RESTful pattern. Retrying a POST risks duplicate creation, parsing the body may work but is less reliable than using Location, and 201 is a success code, not an error.

9 Which status code indicates the client must authenticate and include a WWW-Authenticate header?

A) 401 Unauthorized B) 403 Forbidden C) 407 Proxy Authentication Required

D) 429 Too Many Requests

Answer: A Rationale: 401 Unauthorized signals missing or invalid authentication and requires a WWW-Authenticate header per RFC 9110. 403 means authenticated but not permitted, 407 is for proxy authentication, and 429 indicates rate limiting-none mandate WWW-Authenticate for origin authentication.

10 How should you safely parse a JSON response that may be empty or non-JSON?

A) response.json() directly; it never raises. B) Check response.status_code == 200 then call response.json(). C) Wrap response.json() in try/except ValueError and check Content-Type. D) Use response.text and json.loads only if status_code < 300.

Answer: C Rationale: response.json() raises requests.exceptions.JSONDecodeError (subclass of ValueError) on invalid or empty bodies, so wrapping in try/except and verifying Content-Type is robust. A is false; B and D assume status alone guarantees JSON, which is not reliable (e.g., 204 No Content).

11 Which requests pattern best implements a timeout and raises on 4xx/5xx in one line?

A) requests.get(url, timeout=5).raise_for_status() B) requests.get(url).raise_for_status(timeout=5) C) requests.get(url, timeout=5, allow_redirects=False) D) requests.get(url, headers={'Timeout': '5'}).raise_for_status()

Answer: A Rationale: Passing timeout=5 to requests.get and chaining .raise_for_status() both enforces a timeout and raises HTTPError for 4xx/5xx. raise_for_status() takes no timeout argument (B), allow_redirects does not affect status raising (C), and Timeout is not a valid HTTP header for requests (D).

12 Which header should be set to request a JSON response from an API?

A) Content-Type: application/json B) Accept: application/json C) Authorization: Bearer json D) User-Agent: application/json

C) ehlo() D) auth()

Answer: A Rationale: If MailHog is configured with authentication (via -auth-file), the SMTP client must call login() with credentials before sendmail(). starttls() is for TLS encryption, ehlo() is for greeting, and auth() is not a public smtplib method.

16 What is the purpose of the 'jim' field in a MailHog API message response?

A) It contains the raw email content in JSON format. B) It holds the parsed email headers and body. C) It represents the message ID for deletion. D) It indicates the SMTP transaction log.

Answer: A Rationale: In MailHog's API v2, the 'jim' field (JSON-in-Map) contains the raw email content as a JSON object, including headers and body. It is not for message ID, SMTP logs, or parsed content; those are in other fields like 'ID' or 'Content'.

17 How can a Python script delete all captured messages in MailHog via its API?

A) DELETE http://localhost:8025/api/v1/messages B) DELETE http://localhost:8025/api/v2/messages C) POST http://localhost:8025/api/v1/messages D) GET http://localhost:8025/api/v2/messages?delete=true

Answer: A Rationale: MailHog provides a DELETE endpoint at /api/v1/messages to delete all messages. The v2 API does not support deletion; POST is for sending, and GET with a query parameter is not a valid deletion method.

18 Which Python library is commonly used to interact with MailHog's HTTP API for message retrieval?

A) requests B) smtplib C) imaplib D) http.client

Answer: A Rationale: The requests library is the de facto standard for making HTTP requests to MailHog's API due to its simplicity and readability. smtplib is for SMTP, imaplib for IMAP, and http.client is lower-level and less convenient.

Section 4: Logging in Python: logging module, log levels, handlers, formatters, and log files (Questions 19-24)

19 A script calls logging.basicConfig(level=logging.INFO) then logging.getLogger().setLevel(logging.DEBUG). What is the root logger's effective level?

A) DEBUG, because setLevel overrides basicConfig B) INFO, because basicConfig sets the root level permanently C) WARNING, the default when no level is set D) NOTSET, because basicConfig does not set a level

Answer: A Rationale: basicConfig sets the root logger's level to INFO, but a subsequent setLevel(DEBUG) on the root logger directly overrides it, making DEBUG the effective level. The other options incorrectly assume basicConfig is immutable or that the default persists.

20 A module logger logs at ERROR but no output appears. The root logger has a StreamHandler at DEBUG. What is the most likely cause?

A) The module logger's propagate attribute is set to False B) The module logger's level is set to CRITICAL C) The StreamHandler's formatter is misconfigured D) The root logger's level is higher than ERROR

Answer: B Rationale: If the module logger's level is CRITICAL, ERROR records are filtered out before reaching handlers, so no output occurs even if the root handler is at DEBUG. Propagate=False would still allow the module's own handlers, but none are mentioned; the other options do not explain the absence of output.

21 Which formatter string correctly includes timestamp, level, and message in Python's logging module?

A) '%(asctime)s - %(levelname)s - %(message)s'

B) INFO

C) WARNING

D) ERROR

Answer: A Rationale: DEBUG is used for detailed diagnostic output and is usually disabled in production to reduce log volume. INFO and higher levels are for operational events, warnings, and errors, which are kept in production.

Section 5: Exception Handling: try/except/else/finally, raising exceptions, custom exceptions (Questions 25-30)

25 What is the output when this code runs?

A) A B) B C) C D) D

Answer: C Rationale: The else block runs only if no exception occurs in try. Since the try block raises ValueError, except catches it, prints 'B', and then finally always prints 'C'. The else block is skipped, so output is B then C.

26 Which statement about the finally block is always true?

A) It executes only if no exception occurs. B) It executes only if an exception is caught. C) It executes regardless of whether an exception occurs. D) It executes only if an exception is not caught.

Answer: C Rationale: The finally block is guaranteed to execute whether or not an exception is raised or caught, making it ideal for cleanup actions. Options A, B, and D incorrectly restrict its execution to specific exception scenarios.

27 In a try/except/else/finally, when does the else block execute?

A) Only if an exception occurs in try. B) Only if no exception occurs in try. C) Always, after except and before finally. D) Only if an exception is not caught.

Answer: B Rationale: The else block runs only when the try block completes without raising any exception. It is skipped if an exception occurs, regardless of whether it is caught. Options A, C, and D misstate this condition.

28 What is the output when this code runs?

A) A B) B C) C D) D

Answer: B Rationale: The try block raises ValueError, which is caught by except, printing 'B'. The finally block then prints 'C'. The else block is skipped because an exception occurred. Thus output is B then C.

29 What is the primary purpose of a custom exception in Python?

A) To replace built-in exceptions for performance. B) To provide more specific error information and handling. C) To automatically log errors to a file. D) To prevent exceptions from propagating.

Answer: B Rationale: Custom exceptions allow developers to define specific error types that convey more detailed context and enable targeted exception handling. They do not inherently improve performance, log automatically, or stop propagation; those require additional code.

30 What is the output when this code runs?

A) A B) B C) C D) D

Answer: C Rationale: The try block raises ValueError, caught by except, printing 'B'. The finally block always executes, printing 'C'. The else block is skipped. Thus output is B then C.

Answer: B Rationale: csv.DictReader() is designed to map each row to a dictionary using the header row as keys, providing a direct and efficient solution. csv.reader() (A) requires manual mapping; DictWriter (C) is for writing; pandas (D) is overkill and not part of the standard library.

34 What is the most secure way to load environment variables from a .env file in a Python script?

A) Use os.system('source .env') to load variables into the environment. B) Read the .env file manually and set os.environ for each key-value pair. C) Use python-dotenv's load_dotenv() with override=False to avoid overwriting existing variables. D) Store the .env file in the same directory as the script and use exec(open('.env').read()).

Answer: C Rationale: python-dotenv's load_dotenv() safely parses .env files and sets environment variables without executing arbitrary code, and override=False preserves existing environment variables. os.system('source') (A) is shell-dependent and insecure; manual parsing (B) is error-prone; exec (D) is dangerous as it executes file content.

35 When writing to a file with open('data.txt', 'w', encoding='utf-8'), what happens if the file already exists?

A) The file is truncated to zero length before writing. B) An error is raised because the file exists. C) The new content is appended to the existing file. D) The file is overwritten only if the new content is longer.

Answer: A Rationale: Mode 'w' opens the file for writing and truncates it to zero length if it exists, effectively overwriting. It does not raise an error (B), append (C), or conditionally overwrite (D); those would require modes like 'x' or 'a'.

Section 7: Automation Script Design: modular functions, error resilience, and idempotency (Questions 36-40)

36 Which design best ensures idempotency when sending emails via MailHog in a retry loop?

A) Use a unique message ID per attempt to avoid duplicates. B) Check a local sent-log before sending; skip if already recorded. C) Wrap the send in try/except and ignore all exceptions. D) Send multiple times to guarantee delivery.

Answer: B Rationale: Idempotency means repeated executions produce the same result. Checking a sent-log prevents duplicate sends. Unique IDs per attempt (A) would cause duplicates, ignoring exceptions (C) hides errors, and sending multiple times (D) is not idempotent.

37 A script calls an API that may return 500 errors. Which exception handling approach is most resilient?

A) Catch all exceptions and log a generic error. B) Use try/except around the request, log the error, and retry with exponential backoff. C) Let the exception propagate to the caller without logging. D) Use a bare except to ignore errors and continue.

Answer: B Rationale: Resilient error handling includes specific exception catching, logging, and retry with backoff. Catching all exceptions generically (A) may mask issues, propagating without logging (C) loses diagnostic info, and bare except (D) is bad practice.

38 How should you structure a modular Python automation script to separate concerns for API calls and email sending?

A) Write all code in a single main function for simplicity. B) Create separate functions for API interaction and email sending, with a main orchestrator. C) Use global variables to share data between API and email code. D) Combine API and email logic in one function to reduce overhead.

Answer: B Rationale: Modular design with separate functions for API and email promotes reusability and testability. Single function (A) reduces modularity, global variables (C) increase coupling, and combining logic (D) violates separation of concerns.

D) The test uses pytest.raises incorrectly, wrapping the assertion so that any exception (including AssertionError) is caught and the test is marked as passed.

Answer: B Rationale: A missing key in a dict raises KeyError; if the test is wrapped in a broad try/except that catches Exception or KeyError, the failure is swallowed and the test passes. Option A is wrong because dict subscripting raises KeyError, not None. Option C misidentifies the object type and behavior. Option D describes a different misuse of pytest.raises that would also suppress failures, but the scenario specifically points to a try/except block catching KeyError.

42 A test suite passes individually but fails when run together. Which debugging step best isolates the cause?

A) Add pytest -x to stop at first failure and inspect the traceback. B) Run tests in random order with pytest -p no:randomly to disable randomization. C) Use pytest --lf to rerun only last failed tests and compare results. D) Execute each test in a fresh process using pytest-forked or pytest-xdist with --forked to detect shared state.

Answer: D Rationale: Running each test in isolation (fresh process) reveals whether shared state (e.g., global variables, database, or MailHog inbox) causes order-dependent failures. Option A only stops early but does not isolate state. Option B disables randomization, which may hide the issue. Option C reruns failures but does not isolate the cause. Option D directly tests for inter-test contamination.

43 Which assertion most reliably verifies that a MailHog-captured email contains a specific subject without false positives?

A) assert 'Subject: Test' in mailhog_response.text B) assert json.loads(mailhog_response.text)['items'][0]['Content']['Headers'][' Subject'][0] == 'Test' C) assert re.search(r'Subject: Test', mailhog_response.text) D) assert mailhog_response.status_code == 200

Answer: B

Rationale: MailHog's API returns JSON; parsing and checking the exact header field avoids substring false positives (e.g., 'Subject: Testing'). Option A is a raw substring match that could match partial text. Option C uses regex but still operates on raw text and may match unintended occurrences. Option D only checks HTTP status, not content.

44 A test fails with AssertionError: assert 500 == 200. Which troubleshooting approach is most effective?

A) Add logging.basicConfig(level=logging.DEBUG) and inspect the log for the request/response cycle. B) Increase the assertion timeout to allow the server more time to respond. C) Mock the API call to always return 200 to make the test pass. D) Skip the test with @pytest.mark.skip to avoid the failure.

Answer: A Rationale: Enabling debug logging captures the request and response details, revealing why the server returned 500 (e.g., malformed payload, server error). Option B is irrelevant because the status code is already 500, not a timeout. Option C masks the defect. Option D avoids the issue rather than debugging it.

45 Which practice best ensures that a test for an exception-handling path is both correct and isolated?

A) Use with pytest.raises(ValueError): around the call and assert the exception message. B) Wrap the call in try/except Exception: pass and assert no exception occurred. C) Use assertRaises(ValueError) in a unittest.TestCase and check the exception context. D) Both A and C are valid; B is incorrect because it suppresses the exception.

Answer: D Rationale: Both pytest.raises and unittest's assertRaises are correct context managers for asserting exceptions and can inspect the message. Option B is wrong because it swallows the exception and would not verify the expected error. Option D correctly identifies that A and C are valid while B is not.

Section 9: Security and Best Practices: credential handling, input validation, and safe API usage (Questions 46-50)

A) Ignore rate limits and retry immediately on 429 errors. B) Implement exponential backoff with jitter and respect Retry-After headers. C) Use a single API key for all requests to simplify tracking. D) Cache all responses indefinitely to reduce API calls.

Answer: B Rationale: Exponential backoff with jitter and honoring Retry-After prevents overwhelming the API and reduces ban risk. Immediate retries worsen rate limiting; single key increases impact if compromised; indefinite caching may serve stale data and is not a rate-limiting solution.

50 When using MailHog for email testing, which security practice is essential to prevent accidental email delivery?

A) Configure MailHog to listen on all interfaces. B) Use MailHog's default SMTP port 1025 without authentication. C) Ensure the application's SMTP settings point to MailHog's local host and port. D) Disable TLS in the application's email configuration.

Answer: C Rationale: Pointing SMTP to MailHog's local host and port ensures emails are captured, not sent. Listening on all interfaces or using default port without auth may expose MailHog; disabling TLS is insecure but not directly related to accidental delivery.