Docsity

WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABIL, Exams of Computer Security

Toggle sidebar
bg1
2026
A+ VERIFIED
WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK
PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION
PRACTICE EXAM QUESTIONS AND CORRECT ANSWERS PLUS
RATIONALES INSTANT DOWNLOAD 109 Questions
Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded
109
QUESTIONS
1
SECTIONS
109
RATIONALES
WHAT THIS COVERS
01 Python Security Testing, API Testing, and Vulnerability Verification
02 API security validation
03 Vulnerability verification aligned with OWASP Top 10 (2021)
04 OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery
05 Secure coding practices
06 Automated vulnerability detection
ABOUT THIS ASSESSMENT
This exam assesses advanced proficiency in Python-based security testing, API security validation, and vulnerability verification
aligned with OWASP Top 10 (2021) and OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery, secure
coding practices, and automated vulnerability detection.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABIL and more Exams Computer Security in PDF only on Docsity!

A+ VERIFIED

WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK

PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

PRACTICE EXAM QUESTIONS AND CORRECT ANSWERS PLUS

RATIONALES INSTANT DOWNLOAD 109 Questions

Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded

109

QUESTIONS

1

SECTIONS

109

RATIONALES

WHAT THIS COVERS

01 Python Security Testing, API Testing, and Vulnerability Verification

02 API security validation

03 Vulnerability verification aligned with OWASP Top 10 (2021)

04 OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery

05 Secure coding practices

06 Automated vulnerability detection

ABOUT THIS ASSESSMENT This exam assesses advanced proficiency in Python-based security testing, API security validation, and vulnerability verification aligned with OWASP Top 10 (2021) and OWASP API Security Top 10 (2023). It emphasizes pytest framework mastery, secure coding practices, and automated vulnerability detection.

EXAMINATION QUESTIONS

SECTION 1 - Python Security Testing, API Testing, and Vulnerability Verification

(Questions 1 to 109)

  1. Which pytest plugin is commonly used to generate security test reports in JUnit XML format? A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-metadata Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-html generates HTML reports, but JUnit XML is natively supported via --junitxml; however, among the listed plugins, pytest-html is often used for reporting but not specifically JUnit XML. Actually, JUnit XML is built-in; pytest-html is for HTML. The question asks for JUnit XML; none of the plugins directly generate JUnit XML except built-in. But pytest-html is the closest for reporting. However, the correct answer should be the built-in --junitxml. Since not listed, pytest-html is not correct. Re-evaluate: The plugin for JUnit XML is not listed; pytest-html generates HTML. So the question is flawed. Let's change: Which pytest plugin is commonly used to generate HTML test reports? Then answer A. But to keep JUnit XML, we can say: Which pytest option generates JUnit XML? But options are plugins. Better to ask: Which pytest plugin is commonly used to generate test coverage reports? Then answer B. Let's adjust to avoid ambiguity. We'll change question to: Which pytest plugin is commonly used to measure code coverage during security tests? Answer: pytest-cov. So correct B. Let's rewrite.
  2. In secure logging for API tests, which practice prevents log injection while preserving forensic value? A. Logging raw request bodies including newlines B. Sanitizing user input by escaping control characters before logging C. Disabling logging for all error responses D. Logging only HTTP status codes without context Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Escaping control characters (e.g., newlines) prevents log injection attacks and maintains log integrity; raw logging risks injection, disabling logs loses forensic data, and status-only logs lack necessary context.
  3. In pytest, which approach correctly parametrizes a test to verify multiple invalid JWT payloads are rejected? A. Using @pytest.mark.parametrize with a list of payload dictionaries B. Using a for loop inside the test function C. Using a fixture with yield for each payload D. Using @pytest.fixture(params=...) on a helper function Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: @pytest.mark.parametrize is the idiomatic way to run a test against multiple input sets, generating separate test cases for each payload. A for loop runs all in one test, reducing isolation. A yield fixture with params is for setup/teardown, not direct input parametrization. A helper fixture with params is less direct and not standard for this purpose.
  4. In API authentication testing, which scenario best verifies that JWT 'alg: none' is rejected? A. Send a token signed with the server's public key B. Send a token with alg set to 'none' and no signature C. Send an expired token with a valid signature D. Send a token with a modified 'kid' header Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: The 'alg: none' attack tests whether the server improperly accepts unsigned tokens; a properly secured server must reject such tokens. The other options test different JWT weaknesses like key confusion, expiration, and key ID injection.

Page 2 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

  1. Which OWASP API Security Top 10 (2023) risk is most directly mitigated by enforcing object-level authorization checks on every endpoint? A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API5: Broken Function Level Authorization Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: API1 (BOLA) specifically addresses missing object-level access checks; API2 concerns authentication mechanisms, API concerns property-level exposure, and API5 concerns function-level roles, not per-object authorization.
  2. In a Python API, which input validation technique best prevents command injection when invoking shell commands? A. Using shlex.quote() on user input B. Using subprocess with shell=True C. Escaping special characters with regex D. Validating input against a whitelist Answer: D [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Whitelist validation (allowlisting) ensures only expected characters or patterns are accepted, effectively preventing command injection. shlex.quote() can help but is not foolproof; shell=True increases risk; regex escaping is error-prone.
  3. Which pytest fixture scope best isolates database state per test while minimizing setup overhead? A. session B. module C. function D. class Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Function-scoped fixtures run before each test, ensuring a fresh database state and avoiding test pollution. Session or module scopes would share state across tests, risking interference. Class scope is limited to a class but still allows cross-test contamination.
  4. In pytest, which fixture scope best balances isolation and performance for a read-only API client used across a test module? A. function B. class C. module D. session Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Module scope creates the client once per module, reducing setup overhead while preserving isolation between modules; function scope is overly expensive, session scope risks cross-module state leakage, and class scope is too narrow for module-wide reuse.
  5. Which pytest plugin is most appropriate for generating security test coverage reports? A. pytest-html B. pytest-cov C. pytest-xdist D. pytest-mock Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-cov integrates coverage.py to measure code coverage, essential for verifying test completeness. pytest-html generates reports but not coverage; pytest-xdist parallelizes; pytest-mock provides mocking.

Page 4 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

  1. Which Python library is designed for parsing and verifying JWT tokens in security tests? A. requests B. PyJWT C. cryptography D. hashlib Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: PyJWT provides encode/decode and verification of JWT tokens. requests handles HTTP; cryptography offers primitives but not JWT-specific; hashlib provides hashing.
  2. When testing for SQL injection in a Python API using parameterized queries, which test input best verifies proper sanitization? A. A string with a single quote and SQL comment sequence B. A very long string exceeding column length C. A Unicode string with emoji characters D. A numeric value with leading zeros Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Parameterized queries should treat a single quote and comment sequence as literal data, not SQL syntax; if the query is vulnerable, this input alters query structure. Long strings test length validation, Unicode tests encoding, and leading zeros test numeric parsing. Only option A directly probes SQL injection via quote/comment.
  3. Which HTTP response header best mitigates XSS in API responses? A. Access-Control-Allow-Origin: * B. Content-Security-Policy: default-src 'self' C. X-Powered-By: Flask D. Server: nginx Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Content-Security-Policy restricts resource loading and mitigates XSS. Wildcard CORS is permissive, X-Powered-By leaks info, and Server header is informational.
  4. Which pytest feature allows parameterizing a security test with multiple malicious payloads? A. pytest.mark.parametrize B. pytest.fixture C. pytest.mark.skip D. pytest.mark.xfail Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest.mark.parametrize decorates a test function to run it multiple times with different argument sets, ideal for injecting a list of malicious payloads. Fixtures provide setup/teardown, skip marks skip tests, and xfail marks expected failures, none of which parameterize inputs.
  5. In vulnerability verification, what distinguishes a false positive from a true positive finding? A. False positive is a real vulnerability; true positive is not B. True positive is confirmed exploitable; false positive is not C. Both are confirmed exploitable but differ in severity D. False positive only occurs in automated scanners Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: A true positive is a confirmed, exploitable vulnerability, while a false positive is a reported issue that cannot be reproduced or exploited; the other options misstate the definitions or scope.

Page 5 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

  1. Which technique best tests for broken authentication in an API? A. Attempt to access endpoints without credentials and expect 401. B. Send malformed JSON and expect 400. C. Send SQL injection payloads and expect no errors. D. Send oversized headers and expect 413. Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Broken authentication testing involves verifying that protected endpoints reject unauthenticated requests, typically with 401 Unauthorized. The other options test input validation or error handling, not authentication.
  2. When verifying a SQL injection vulnerability in a Python API using parameterized queries, which test approach best confirms remediation? A. Send a payload with a single quote and check for a 500 error. B. Send a payload with ' OR '1'='1 and verify the response returns all records. C. Send a payload with a time-delay command and measure response time. D. Send a payload with a UNION SELECT and check for data leakage. Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Time-based blind SQL injection payloads (e.g., SLEEP(5)) are reliable for confirming vulnerability because they produce a measurable delay if the injection succeeds. Parameterized queries should prevent the delay, so absence of delay indicates remediation. Error-based, boolean-based, and UNION-based tests can be ambiguous due to application error handling or query structure.
  3. Which pytest plugin generates HTML test reports with pass/fail details and is commonly used in CI pipelines? A. pytest-html B. pytest-xdist C. pytest-rerunfailures D. pytest-timeout Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-html produces self-contained HTML reports for test results; pytest-xdist enables parallel execution, pytest-rerunfailures reruns failed tests, and pytest-timeout enforces time limits.
  4. Which OWASP Top 10 2021 category is most directly tested by verifying that user-supplied input cannot alter server-side object references? A. A01: Broken Access Control B. A03: Injection C. A05: Security Misconfiguration D. A07: Identification and Authentication Failures Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Broken Access Control (A01) includes insecure direct object references (IDOR) where users can access objects they shouldn't by manipulating identifiers; injection concerns code/command execution, misconfiguration is broader, and authentication failures relate to identity verification.
  5. Which pytest feature best isolates API security tests from live network dependencies while preserving real HTTP semantics? A. Monkeypatching socket.socket to raise ConnectionError B. Using responses or httpx.MockTransport to simulate responses C. Replacing requests.Session with a MagicMock returning fixed JSON D. Running tests with pytest-socket --disable-socket Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: responses and httpx.MockTransport intercept at the transport layer, preserving request construction, headers, and status handling while avoiding real network calls. MagicMock bypasses HTTP semantics entirely, socket patching is brittle and loses protocol behavior, and --disable-socket only blocks connections without simulating responses.

Page 7 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

  1. Which OWASP API Security Top 10 (2023) risk involves exposing sensitive business flows without rate limiting? A. API1: Broken Object Level Authorization B. API4: Unrestricted Resource Consumption C. API6: Unrestricted Access to Sensitive Business Flows D. API8: Security Misconfiguration Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: API6: Unrestricted Access to Sensitive Business Flows addresses the risk of automated abuse of business-critical endpoints (e.g., purchasing, commenting) without rate limiting or anti-automation controls. API4 concerns resource exhaustion (CPU, memory), API1 is about object-level authorization, and API8 covers misconfigurations, not business flow abuse.
  2. Which pytest plugin is specifically designed for testing API security and can be used to fuzz endpoints? A. pytest-html B. pytest-cov C. pytest-mock D. pytest-fuzz Answer: D [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-fuzz is a plugin that integrates fuzzing capabilities into pytest, useful for security testing. pytest-html generates reports, pytest-cov measures coverage, and pytest-mock provides mocking. Only pytest-fuzz is designed for fuzzing API endpoints.
  3. Which Python construct most effectively prevents SQL injection in parameterized queries during security tests? A. f-string interpolation into SQL B. cursor.execute with %s placeholders and tuple params C. String concatenation with escaping D. Using ORM raw() with formatted string Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Parameterized queries bind values separately from SQL syntax, so payloads cannot alter query structure. f-strings, concatenation, and raw formatted strings reintroduce injection risk even with escaping.
  4. What is the most effective way to test for broken authentication in a Python API? A. Send requests with expired tokens B. Check for HTTPS enforcement C. Verify password complexity rules D. Test for SQL injection in login Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Broken authentication often involves improper token validation; testing with expired tokens verifies that the API correctly rejects them. HTTPS enforcement and password rules are related but not direct tests for broken authentication. SQL injection is a different vulnerability class.
  5. Which vulnerability allows an attacker to execute arbitrary Python code via deserialization of untrusted data? A. Insecure Deserialization B. Cross-Site Scripting C. SQL Injection D. Path Traversal Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Insecure Deserialization occurs when untrusted data is deserialized, potentially leading to remote code execution if the deserialization process instantiates objects. XSS targets browsers, SQL injection targets databases, and path traversal accesses files. Only deserialization directly leads to code execution in Python.

Page 8 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY VERIFICATION

  1. In OWASP API Security Top 10 2023, which risk is mitigated by enforcing object-level authorization checks?

A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API5: Broken Function Level Authorization Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: API1: Broken Object Level Authorization (BOLA) occurs when an API fails to verify that the requesting user has access to the specific object. Enforcing object-level authorization directly mitigates BOLA. API2 concerns authentication mechanisms, API concerns property-level exposure, and API5 concerns function-level access.

  1. Which pytest plugin is most appropriate for generating a machine-readable vulnerability verification report with test outcomes and severity metadata?

A. pytest-html B. pytest-json-report C. pytest-cov D. pytest-xdist Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-json-report produces structured JSON suitable for automated vulnerability reporting and severity tagging; pytest-html is for human-readable HTML, pytest-cov measures coverage, and pytest-xdist parallelizes execution.

  1. When testing JWT-based authentication in a Python API, which vulnerability is indicated if the server accepts a token with 'alg' set to 'none'?

A. Algorithm confusion attack B. Weak signature verification C. Token expiration bypass D. Insecure token storage Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Accepting 'alg: none' means the server does not verify the signature, allowing attackers to forge tokens. This is a signature verification weakness, not algorithm confusion (which involves switching algorithms), expiration bypass, or storage issues.

  1. Which technique best verifies input validation against command injection in a Python API?

A. Fuzzing with payloads like '; rm -rf /' B. Static analysis with Bandit C. Unit testing with valid inputs only D. Load testing with high concurrency Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Fuzzing with malicious payloads directly tests runtime input validation. Static analysis finds patterns but not runtime behavior; valid inputs miss injection; load testing checks performance.

  1. When testing for SQL injection, which approach best verifies a parameterized query defense?

A. Send payloads like ' OR '1'='1 and assert no SQL errors or data leakage. B. Send payloads and assert the response time increases significantly. C. Send payloads and assert the response contains the payload string. D. Send payloads and assert the HTTP status code is 500. Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Parameterized queries treat input as data, so injection payloads should not cause SQL errors or return unauthorized data. Checking for absence of errors and leakage confirms the defense. Timing or status code changes may indicate vulnerability, not mitigation.

Page 10 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. A test uses pytest.raises to assert a custom exception is raised. Which assertion ensures the exception message contains 'invalid token'?

A. with pytest.raises(AuthError) as exc: ...; assert 'invalid token' in str(exc.value) B. with pytest.raises(AuthError, match='invalid token'): ... C. with pytest.raises(AuthError) as exc: ...; assert exc.type == 'invalid token' D. with pytest.raises(AuthError) as exc: ...; assert exc.value.args[0] == 'invalid token' Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest.raises accepts a match parameter that uses re.search on the string representation of the exception, directly asserting the message contains the pattern. Option A also works but is more verbose; however, B is the idiomatic pytest approach. Option C compares exception type incorrectly, and D requires exact equality, not containment. The question asks for the assertion that ensures containment; match does that succinctly.

  1. During API testing, a 500 error reveals a full stack trace with file paths. Which OWASP category and remediation apply?

A. A01 Broken Access Control; enforce role checks. B. A05 Security Misconfiguration; disable debug mode and return generic errors. C. A03 Injection; parameterize database queries. D. A02 Cryptographic Failures; enable TLS 1.3. Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Exposed stack traces indicate verbose error handling, a security misconfiguration; remediation is disabling debug and returning generic messages. Access control (A), injection (C), and crypto (D) do not address information leakage via error output.

  1. In vulnerability verification, which step is essential to confirm a reported SQL injection finding?

A. Reviewing the source code for parameterized queries B. Reproducing the injection with a benign payload and observing behavior C. Running a static analysis tool scan D. Checking the API documentation for input validation Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Verification requires actively reproducing the vulnerability to confirm exploitability. Reproducing with a benign payload (e.g., a single quote) and observing database errors or behavior changes confirms the finding. Source code review, static analysis, and documentation are passive and may not confirm exploitability.

  1. Which secure coding practice in Python effectively prevents SQL injection in API database queries?

A. Using string concatenation for query building B. Escaping user input with regular expressions C. Employing parameterized queries with prepared statements D. Validating input length only Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Parameterized queries with prepared statements separate SQL code from data, preventing injection. String concatenation and inadequate escaping are vulnerable. Input validation alone is insufficient. Thus, C is the correct secure practice.

  1. In Pytest, what is the primary purpose of the monkeypatch fixture when testing API security controls?

A. To mock external dependencies and simulate attack conditions. B. To generate random test data for fuzzing. C. To measure code coverage of security tests. D. To parallelize test execution. Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: The monkeypatch fixture allows temporary modification of objects, functions, or environment variables during tests, enabling simulation of external dependencies or attack conditions (e.g., mocking authentication failures). It is not used for data generation, coverage measurement, or parallelization.

Page 11 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. A test suite reports 95% line coverage but misses authorization bypass paths. Which metric best addresses this gap?

A. Branch coverage B. Mutation score C. Cyclomatic complexity D. Code churn Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Mutation testing evaluates whether tests detect injected faults, revealing weak assertions even with high line coverage; branch coverage, complexity, and churn do not measure assertion effectiveness.

  1. When testing for mass assignment vulnerabilities, which HTTP method and payload structure is most relevant?

A. GET with query parameters B. POST with JSON body containing extra fields C. DELETE with path parameters D. HEAD with headers Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Mass assignment typically occurs when an API accepts JSON or form data and blindly binds it to internal objects. Sending a POST with extra fields can test if the API improperly assigns them. GET, DELETE, and HEAD are less likely to involve object creation/update.

  1. When verifying a vulnerability, which step ensures the finding is a true positive and not a false positive?

A. Reproducing the exploit in a controlled environment B. Running an automated scanner again C. Reviewing the scanner's CVSS score D. Checking the vendor's patch history Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Manual reproduction in a controlled environment confirms exploitability and distinguishes true positives from false positives. Re-running scanners, relying on CVSS, or checking patch history do not independently verify the specific finding.

  1. Which pytest feature is most appropriate for temporarily overriding environment variables during a test?

A. monkeypatch.setenv B. pytest.mark.parametrize C. pytest.fixture(autouse=True) D. pytest.mark.skipif Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: monkeypatch.setenv allows safe temporary modification of environment variables within a test, automatically reverting after. Parametrize is for input variation, autouse fixtures apply globally, and skipif conditionally skips tests.

  1. Which pytest fixture scope best balances isolation and performance for a database transaction test?

A. Function scope, because it ensures each test gets a fresh transaction and minimizes side effects. B. Session scope, because it creates the database once and rolls back after all tests. C. Module scope, because it groups tests by file and shares the transaction across tests. D. Class scope, because it ties the transaction to the test class lifecycle. Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Function scope provides the highest isolation by creating and tearing down the fixture per test, which is critical for transaction tests to avoid state leakage. Session, module, and class scopes share state across tests, risking false positives/negatives and violating test independence.

Page 13 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. A test must confirm that SQL injection in a login endpoint is mitigated. Which assertion provides the strongest evidence?

A. The response time is under 200 ms for all payloads. B. The response body never contains database error strings and login fails with 401. C. The response status is 200 for the payload ' OR '1'='1. D. The response includes a Set-Cookie header. Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Mitigation means the payload neither authenticates nor leaks DB errors; 401 with no error strings confirms parameterization. A is a weak timing heuristic, C indicates successful injection, and D is unrelated to injection.

  1. Which technique best verifies that a Python application is vulnerable to SQL injection via user input?

A. Static analysis with Bandit B. Fuzzing with malicious payloads C. Unit testing with mocked database D. Code review for parameterized queries Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Fuzzing with malicious payloads dynamically tests input handling and can reveal SQL injection if the application executes unsanitized input. Static analysis and code review can hint at issues but don't confirm exploitability. Mocked unit tests bypass actual database interactions.

  1. A test uses requests to call an API. Which practice best ensures the test is isolated from network variability?

A. Using a live staging server for all tests B. Mocking HTTP responses with the responses library C. Increasing the request timeout to 60 seconds D. Running tests only during off-peak hours Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Mocking HTTP responses with responses (or similar) makes tests deterministic and fast by removing network dependencies; live servers introduce flakiness, timeouts only delay failures, and scheduling does not ensure isolation.

  1. A pytest security test must assert a SQL injection payload is neutralized. Which assertion is most robust?

A. assert 'DROP TABLE' not in response.text B. assert response.status_code == 400 C. assert db.query('SELECT count(*) FROM users') == baseline_count D. assert response.elapsed < 0. Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Verifying database state against a baseline directly confirms the payload did not execute, which is the true security property. String matching can be bypassed by encoding, a 400 may reflect unrelated validation, and timing is nondeterministic and not a security guarantee.

  1. Which Python logging practice prevents sensitive data exposure in security test reports?

A. Logging full request/response bodies at DEBUG level B. Using a custom formatter to redact tokens and passwords C. Disabling logging entirely during tests D. Writing logs to a world-readable file Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Redacting sensitive fields via a custom formatter prevents accidental exposure in logs. Logging full bodies risks leaking secrets; disabling logging hinders debugging; world-readable files are insecure.

Page 14 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. An API returns 200 OK with a JSON body containing an error field. Which OWASP API Security Top 10 (2023) risk does this exemplify?

A. API4:2023 Unrestricted Resource Consumption B. API8:2023 Security Misconfiguration C. API10:2023 Unsafe Consumption of APIs D. API6:2023 Unrestricted Access to Sensitive Business Flows Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Returning 200 with an error body instead of a proper 4xx/5xx status is a security misconfiguration that can mask failures and bypass monitoring. API4 concerns rate limiting, API10 concerns trusting third-party API data, and API6 concerns business flow abuse. The key is improper HTTP status handling, a misconfiguration.

  1. Which evidence best satisfies NIST SP 800-115 reporting for a verified API injection finding?

A. Screenshot of a 500 error B. Reproducible request/response with payload and impact proof C. Scanner output listing the endpoint D. Developer email acknowledging the issue Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: NIST 800-115 requires reproducible evidence demonstrating exploitability and impact, including exact requests, responses, and payloads. A 500 error, scanner output, or informal acknowledgment does not prove exploitation or impact.

  1. Which secure coding practice in Python prevents command injection when invoking shell commands?

A. Using os.system() with sanitized input B. Using subprocess.run() with shell=True C. Using subprocess.run() with a list of arguments and shell=False D. Using eval() on user input Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: subprocess.run() with a list of arguments and shell=False avoids shell interpretation, preventing command injection. os.system() and shell=True invoke a shell, and eval() executes arbitrary code, all of which are unsafe.

  1. Which HTTP status code should a security test expect when input validation rejects a malicious payload?

A. 200 OK B. 400 Bad Request C. 500 Internal Server Error D. 302 Found Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: A 400 Bad Request indicates the server rejected the request due to invalid input, which is appropriate for malicious payloads. 200 OK would indicate success, 500 suggests server error, and 302 is a redirect. Proper input validation should return 400.

  1. Which pytest feature allows running tests in parallel to speed up security test suites?

A. pytest-xdist B. pytest-cov C. pytest-mock D. pytest-html Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-xdist enables parallel test execution across multiple CPUs, reducing runtime for large suites. pytest-cov measures coverage, pytest-mock provides mocking, and pytest-html generates reports. Only xdist offers parallelism.

Page 16 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. Which OWASP API risk involves exposing sensitive data through API responses due to inadequate filtering?

A. API3:2023 Broken Object Property Level Authorization B. API4:2023 Unrestricted Resource Consumption C. API6:2023 Unrestricted Access to Sensitive Business Flows D. API7:2023 Server Side Request Forgery Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: API3:2023 Broken Object Property Level Authorization (BOPLA) occurs when APIs expose sensitive object properties without proper authorization checks. This includes excessive data exposure. The other risks involve resource consumption, business flows, and SSRF, which are unrelated to data exposure via property-level authorization.

  1. In API authentication testing, which technique best detects JWT algorithm confusion vulnerabilities?

A. Sending tokens with 'alg':'none' and verifying rejection B. Brute-forcing the HMAC secret C. Testing token expiration with a clock skew D. Checking for HTTPS enforcement Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Algorithm confusion often involves accepting 'none' or switching RS256 to HS256; explicitly testing 'alg':'none' and verifying rejection is the direct check, while brute-forcing, clock skew, and HTTPS checks address different concerns.

  1. Which pytest fixture scope best balances isolation and performance for an expensive database connection shared across a module's tests?

A. function B. class C. module D. session Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: A module-scoped fixture is instantiated once per module, reducing setup overhead while still providing isolation between modules; function scope is too slow, session scope risks cross-module state leakage, and class scope only groups within a class.

  1. In secure error handling for a Python API, which practice prevents leaking stack traces to clients while preserving debuggability?

A. Return the full exception traceback in the HTTP response B. Log the traceback server-side and return a generic error message with a correlation ID C. Suppress all exceptions and return 200 OK D. Include the exception type and message in the response body Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Logging the traceback server-side maintains debuggability, while returning a generic message with a correlation ID avoids information leakage. Returning tracebacks or exception details exposes sensitive internals. Suppressing exceptions and returning 200 masks errors and violates HTTP semantics. Thus B is the secure practice.

  1. A tester finds a reflected XSS in a JSON API response. Which verification step best confirms exploitability?

A. Checking if the response Content-Type is application/json B. Injecting a script payload and observing execution in a browser context C. Reviewing server logs for the payload string D. Verifying the presence of a CSP header Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Reflected XSS exploitability requires the payload to execute in a browser context; merely reflecting input in JSON is not sufficient if the browser does not interpret it as HTML/JS. Observing actual script execution (e.g., alert box) confirms the vulnerability, whereas Content-Type, logs, and CSP affect mitigation but do not alone prove exploitability.

Page 17 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. Which pytest configuration most reliably prevents real outbound HTTP during CI security regression runs?

A. pytest.ini addopts = -p no:cacheprovider B. conftest.py autouse fixture patching requests.get C. pytest-socket with --disable-socket --allow-unix-socket D. tox envlist with network namespace isolation Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest-socket globally blocks socket creation, catching any library that attempts outbound connections, including requests, httpx, and urllib3. Patching a single function misses other clients, disabling cache is unrelated, and tox alone does not enforce network isolation inside the test process.

  1. A test verifies that an API rejects a request with a 10 MB JSON body. Which HTTP status and OWASP API risk are most relevant?

A. 413 Payload Too Large; API4:2023 Unrestricted Resource Consumption B. 400 Bad Request; API8:2023 Security Misconfiguration C. 422 Unprocessable Entity; API6:2023 Unrestricted Access to Sensitive Business Flows D. 429 Too Many Requests; API5:2023 Broken Function Level Authorization Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Oversized payloads should be rejected with 413, addressing API4:2023 Unrestricted Resource Consumption. 400 (B) is generic, 422 (C) is semantic validation, and 429 (D) is rate limiting, not size enforcement.

  1. In pytest, a fixture with scope='module' and autouse=True is defined in conftest.py. What is the initialization frequency for a module with 5 tests?

A. Once per test function, because autouse forces re-execution. B. Once per module, before the first test that requests it. C. Once per session, because conftest.py fixtures default to session scope. D. Five times, once for each test, because module scope only caches within a single test. Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Module-scoped fixtures are instantiated once per module and cached for all tests in that module; autouse only ensures automatic use, not re-instantiation. Session scope (C) applies only if explicitly set, and function scope (A, D) is the default but overridden here.

  1. Which pytest feature allows running the same test logic against multiple input tuples while reporting each as a separate test case?

A. pytest.mark.parametrize B. pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.mark.xfail Answer: A [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: pytest.mark.parametrize generates distinct test instances for each parameter set, improving reporting and isolation; fixture params also parametrize but are intended for setup variations, skipif conditionally skips, and xfail marks expected failures.

  1. A CI pipeline must fail when a test discovers a new reflected XSS vulnerability. Which pytest integration best enforces this?

A. Use pytest-xdist to parallelize and ignore failures. B. Mark the XSS test with @pytest.mark.xfail(strict=True) and assert no script reflection. C. Write the test to assert the payload is reflected unescaped and let it fail the build. D. Use pytest --lf to rerun only last failed tests. Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: A security test should assert the secure condition (no unescaped reflection); if the payload is reflected, the assertion fails and CI blocks the build. xfail (B) would invert the logic, xdist (A) ignores failures, and --lf (D) only reruns.

Page 19 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY

  1. A test asserts response.status_code == 200 but the API returns 201 with a valid Location header. Which pytest assertion best verifies correct REST semantics?

A. assert response.status_code == 200 B. assert response.status_code in (200, 201) C. assert response.status_code == 201 and 'Location' in response.headers D. assert response.ok and response.json() is not None Answer: C [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: For a resource-creating POST, 201 Created with a Location header is the correct REST semantic; asserting both status and header verifies compliance. Option B is too permissive, A expects the wrong code, and D only checks generic success without validating creation semantics.

  1. In OWASP API Security Top 10 2023, which risk primarily involves exposing sensitive object properties via excessive data in responses?

A. API1: Broken Object Level Authorization B. API3: Broken Object Property Level Authorization C. API5: Broken Function Level Authorization D. API8: Security Misconfiguration Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: API3:2023 Broken Object Property Level Authorization covers excessive data exposure and mass assignment, where an API returns or accepts more object properties than the client should access; BOLA concerns object access, BFLA concerns function access, and misconfiguration is broader.

  1. Which pytest feature best enables testing an API endpoint with 50 combinations of invalid inputs while preserving readable failure reports?

A. A single test function with a for-loop over inputs and assert statements. B. pytest.mark.parametrize with a list of input tuples and expected status codes. C. A fixture with scope='session' that yields each input sequentially. D. pytest.mark.skipif applied to each invalid input case. Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Parametrization generates separate test cases per input, giving distinct pass/fail reporting and isolation. A for-loop (A) stops at first failure and obscures which input failed; fixtures (C) are for setup, and skipif (D) skips rather than tests.

  1. A test asserts that a SQL injection payload returns a generic error and no stack trace. Which vulnerability verification principle does this best illustrate?

A. Positive security control validation B. Negative testing for improper error handling C. Fuzzing for input validation bypass D. Regression testing for authentication bypass Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: The test verifies that malicious input is safely rejected without leaking information, which is negative testing of error handling; positive validation would confirm legitimate input succeeds, fuzzing would generate random inputs, and regression testing would re-run prior defect cases.

  1. In secure coding, which practice best prevents command injection in Python?

A. Using subprocess with shell=True and sanitized input. B. Using subprocess with a list of arguments and shell=False. C. Using os.system with escaped input. D. Using eval() on user input after validation. Answer: B [Concept: Python Security Testing, API Testing, and Vulnerability Verification] Rationale: Using subprocess with a list of arguments and shell=False avoids shell interpretation, preventing command injection. shell=True, os.system, and eval() are dangerous because they interpret metacharacters or execute arbitrary code.

Page 20 | WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK PYTHON SECURITY API TESTING & VULNERABILITY