Docsity

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

Toggle sidebar
bg1
Page 1
WGU D385 PYTEST & SECURITY UNIT TESTING
WORKBOOK PYTHON SECURITY API TESTING &
VULNERABIL, Exams of Computer Security - Questions and
Answers Already Graded A+ Premium Exam Tested And
Verified
GRADED A+
ABSTRACT
This exam assesses advanced competency in Python-based security testing workflows:
pytest design (fixtures, parametrization, mocking), API testing with requests
(authentication, status codes, input validation), vulnerability identification and
remediation aligned to OWASP API Security Top 10 (2023) and OWASP Top 10
(2021), secure coding practices, and interpretation of coverage and test results. Items
require synthesis across testing, security, and Python implementation concepts at a
level consistent with WGU D385 course competencies (2026 version).
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

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!

WGU D385 PYTEST & SECURITY UNIT TESTING

WORKBOOK PYTHON SECURITY API TESTING &

VULNERABIL, Exams of Computer Security - Questions and

Answers Already Graded A+ Premium Exam Tested And

Verified

GRADED A+

ABSTRACT

This exam assesses advanced competency in Python-based security testing workflows:

pytest design (fixtures, parametrization, mocking), API testing with requests

(authentication, status codes, input validation), vulnerability identification and

remediation aligned to OWASP API Security Top 10 (2023) and OWASP Top 10

(2021), secure coding practices, and interpretation of coverage and test results. Items

require synthesis across testing, security, and Python implementation concepts at a

level consistent with WGU D385 course competencies (2026 version).

1. A pytest fixture uses yield to open a DB connection. A test raises before

cleanup. What guarantees teardown?

A. Wrap the test body in try/finally inside the test function. B. Use yield fixtures; pytest runs code after yield even if the test fails. C. Set autouse=True on the fixture; teardown then always executes. D. Add a session-scoped finalizer via request.addfinalizer only.

Answer: B. Use yield fixtures; pytest runs code after yield even if the test

fails.

Pytest yield fixtures execute post-yield teardown regardless of test outcome, ensuring cleanup. try/finally in the test duplicates logic and is not required; autouse controls invocation, not teardown guarantee; addfinalizer works but is not the mechanism that makes yield fixtures safe.

2. An API returns 200 with a generic error body on invalid input. Which

OWASP API 2023 risk is most directly indicated?

A. API4:2023 Unrestricted Resource Consumption B. API8:2023 Security Misconfiguration C. API6:2023 Unrestricted Access to Sensitive Business Flows D. API9:2023 Improper Inventory Management

Answer: B. API8:2023 Security Misconfiguration

Returning 200 with an error body instead of a proper 4xx status is a classic security misconfiguration (API8:2023) that obscures failures and can mask injection attempts. Resource consumption, business-flow abuse, and inventory management concern rate/flow limits and asset tracking, not status-code misuse.

5. A parametrized test covers 4 inputs but branch coverage stays 50%. What is

the most likely cause?

A. Parametrization does not affect branch coverage metrics. B. The test inputs never exercise the untaken branch condition. C. Branch coverage requires statement coverage to be 100% first. D. pytest-cov cannot measure branch coverage for parametrized tests.

Answer: B. The test inputs never exercise the untaken branch condition.

Branch coverage measures whether both outcomes of each decision are taken; if inputs never trigger the false (or true) path, coverage remains partial. Parametrization does influence coverage; branch coverage is independent of statement coverage thresholds; pytest-cov supports branch coverage for parametrized tests.

6. A test asserts response.status_code == 200 for a POST that should reject

malformed JSON. Which test design flaw is present?

A. The assertion encodes the wrong expected behavior, masking a validation defect. B. The test should use pytest.raises instead of status assertions. C. The test must mock the JSON parser to be deterministic. D. The test should assert response.text is empty.

Answer: A. The assertion encodes the wrong expected behavior, masking a

validation defect.

A malformed-JSON POST should yield 400 (or 422); asserting 200 bakes in incorrect behavior and hides a validation flaw. pytest.raises is for exceptions, not HTTP status; mocking the parser is unnecessary; asserting empty text is not the correct control.

7. A pytest suite passes but a security review finds SQL injection. Which

testing gap best explains this?

A. Tests used parameterized queries, so injection was impossible. B. Tests only covered happy paths and never supplied malicious payloads. C. Coverage was 100%, so all vulnerabilities must be caught. D. The suite used fixtures, which prevent security defects.

Answer: B. Tests only covered happy paths and never supplied malicious

payloads.

Passing tests reflect only the inputs exercised; without adversarial payloads (e.g., ' OR 1=1--), injection paths remain untested. Parameterized queries would prevent injection, contradicting the premise; 100% coverage does not imply security; fixtures are unrelated to defect prevention.

8. Which pytest feature best supports testing the same auth endpoint across

many role/scope combinations?

A. A single test with a loop over roles inside the function body. B. @pytest.mark.parametrize with tuples of (role, scope, expected_status). C. A session-scoped fixture that logs in as admin only. D. Using pytest.skip for non-admin roles.

Answer: B. @pytest.mark.parametrize with tuples of (role, scope,

expected_status).

Parametrization generates distinct test cases per role/scope tuple, giving granular pass/fail reporting and isolation. A loop hides which combination failed; admin-only fixtures miss authorization cases; skipping non-admin roles eliminates coverage.

11. In pytest, which fixture scope best balances isolation and performance for a

read-only database connection pool?

A. function B. class C. module D. session

Answer: D. session

A session-scoped fixture creates the pool once per test session, maximizing performance for read-only resources while avoiding per-test overhead. Function scope ensures isolation but is slow; class and module scopes offer intermediate reuse but still recreate the pool multiple times.

12. Which OWASP API Security Top 10 (2023) risk is most directly 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. API1: Broken Object Level Authorization

API1: Broken Object Level Authorization (BOLA) occurs when an API fails to verify that the authenticated user owns or is authorized to access the requested object. Enforcing object-level authorization directly addresses BOLA. API concerns authentication mechanisms, API3 concerns property-level exposure, and API5 concerns function-level access.

13. Which pytest feature allows running the same test logic against multiple

input sets without duplicating code?

A. pytest.mark.parametrize B. pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.mark.xfail

Answer: A. pytest.mark.parametrize

pytest.mark.parametrize is the canonical decorator for parameterizing test functions with multiple argument sets, generating separate test cases. Fixture params also parameterize but are intended for fixture setup variations; skipif and xfail control test execution, not input variation.

14. When testing an API endpoint that returns a 401 Unauthorized, which

assertion best verifies proper authentication enforcement?

A. assert response.status_code == 401 B. assert response.json()['error'] == 'Unauthorized' C. assert 'WWW-Authenticate' in response.headers D. assert response.status_code == 403

Answer: C. assert 'WWW-Authenticate' in response.headers

Per RFC 7235, a 401 response must include a WWW-Authenticate header indicating the authentication scheme. Asserting on this header verifies the server is correctly challenging unauthenticated requests. Status code alone is insufficient; 403 indicates authenticated but forbidden; error message body is implementation-specific.

18. When using unittest.mock.patch to replace a function, what does the patch

decorator do by default?

A. Replaces the target with a MagicMock and restores it after the test B. Permanently replaces the target for the entire test session C. Only patches if the target exists, otherwise raises an error D. Patches all instances of the target across modules

Answer: A. Replaces the target with a MagicMock and restores it after the

test

patch temporarily replaces the target with a MagicMock (or specified mock) during the test and restores the original afterward. It does not permanently replace, does not automatically patch all instances, and will raise an error if the target does not exist unless create=True is specified.

19. Which Python library is commonly used to make HTTP requests in API

security tests?

A. requests B. urllib C. httpx D. aiohttp

Answer: A. requests

The requests library is the de facto standard for synchronous HTTP requests in Python and is widely used in API testing for its simplicity. urllib3 is lower-level, httpx supports async and sync but is less ubiquitous, and aiohttp is primarily for asynchronous requests.

20. In pytest, which marker is used to indicate that a test is expected to fail and

should not cause the test suite to fail?

A. @pytest.mark.skip B. @pytest.mark.xfail C. @pytest.mark.skipif D. @pytest.mark.filterwarnings

Answer: B. @pytest.mark.xfail

pytest.mark.xfail marks a test as expected to fail; if it fails, the test is reported as xfailed and does not fail the suite. skip and skipif unconditionally or conditionally skip tests; filterwarnings controls warning capture.

21. Which pytest fixture scope best isolates a database transaction while

sharing an expensive connection pool across a module?

A. function-scoped fixture that opens a new connection per test B. module-scoped fixture for the pool, function-scoped fixture for the transaction C. session-scoped fixture for both pool and transaction D. class-scoped fixture for the pool, session-scoped fixture for the transaction

Answer: B. module-scoped fixture for the pool, function-scoped fixture for

the transaction

A module-scoped fixture can create the pool once per module, while a function-scoped fixture wraps each test in a transaction that is rolled back, preserving isolation. Function-scoped connections (A) are correct but inefficient, session-scoped transactions (C) leak state, and session-scoped transactions (D) violate isolation across tests.

22. An API returns 200 with a JSON error body for invalid input. Which

OWASP API Security Top 10 2023 category is most directly violated?

A. API4:2023 Unrestricted Resource Consumption B. API8:2023 Security Misconfiguration C. API6:2023 Unrestricted Access to Sensitive Business Flows D. API3:2023 Broken Object Property Level Authorization

Answer: B. API8:2023 Security Misconfiguration

Returning a success status for a failed request reflects improper error handling and security misconfiguration (API8:2023). Resource consumption (A), business-flow abuse (C), and object property authorization (D) concern different failure modes.

26. A JWT uses alg:none and is accepted by the API. Which CWE most

precisely classifies this weakness?

A. CWE-798 Use of Hard-coded Credentials B. CWE-347 Improper Verification of Cryptographic Signature C. CWE-522 Insufficiently Protected Credentials D. CWE-384 Session Fixation

Answer: B. CWE-347 Improper Verification of Cryptographic Signature

Accepting an unsigned token means the signature is not properly verified, which is CWE-347. Hard-coded credentials (A), credential protection (C), and session fixation (D) describe different weaknesses.

27. Which coverage metric most directly reveals untested branches in

conditional authorization logic?

A. Statement coverage B. Function coverage C. Branch coverage D. Line coverage

Answer: C. Branch coverage

Branch coverage measures whether both outcomes of each decision point are exercised, exposing untested authorization paths. Statement, function, and line coverage can all report high percentages while missing untaken branches.

28. Which requests-based test best detects a server-side request forgery

vulnerability in a URL-fetch endpoint?

A. Send a URL pointing to 169.254.169.254 and assert the response lacks metadata B. Send an invalid URL and assert 400 C. Send a URL with a long query string and assert 200 D. Send a URL to example.com and assert content type

Answer: A. Send a URL pointing to 169.254.169.254 and assert the response

lacks metadata

SSRF testing targets internal link-local metadata endpoints; asserting the metadata is not returned detects the flaw. Invalid URLs (B), long queries (C), and benign external URLs (D) do not exercise SSRF.

29. Which pytest feature best prevents test pollution when patching a

module-level constant used across many tests?

A. A session-scoped autouse fixture that restores the original value B. monkeypatch.setattr, which automatically undoes changes after each test C. A global variable reassigned in a module-level setup D. mocker.patch without a context manager

Answer: B. monkeypatch.setattr, which automatically undoes changes after

each test

monkeypatch.setattr records and reverts changes automatically at test teardown, preventing pollution. Session-scoped restoration (A) is too late, module-level reassignment (C) persists, and unmanaged patching (D) leaks state.

30. In a test suite, which fixture pattern correctly yields a temporary API key

and guarantees cleanup even on test failure?

A. Return the key from a function-scoped fixture and delete it in a finalizer B. Yield the key and delete it after the yield inside a function-scoped fixture C. Create the key in setup_module and delete it in teardown_module D. Create the key in a session-scoped fixture without teardown

Answer: B. Yield the key and delete it after the yield inside a function-scoped

fixture

A yield fixture runs teardown code after the yield even if the test fails, guaranteeing cleanup. Finalizers (A) work but are less idiomatic, module-level teardown (C) is not failure-safe per test, and no teardown (D) leaks keys.

31. Which pytest feature most directly enables isolated API security tests that

avoid shared auth state?

A. session-scoped autouse fixture B. function-scoped fixture with yield teardown C. parametrize with indirect=True D. monkeypatch.setenv in conftest

Answer: B. function-scoped fixture with yield teardown

A function-scoped yield fixture creates and tears down auth tokens per test, preventing cross-test leakage. Session-scoped autouse persists state across tests, indirect parametrization controls inputs not isolation, and monkeypatch.setenv alters environment but not shared object state.

35. A test suite reports 100% line coverage but misses broken authorization.

Which metric best exposes this gap?

A. branch coverage B. mutation score C. statement coverage D. cyclomatic complexity

Answer: B. mutation score

Mutation testing introduces faults; a high mutation score indicates tests detect logic changes like auth bypass. Line/branch/statement coverage only measure execution, and cyclomatic complexity measures code structure, not test effectiveness.

36. Which pytest parametrization correctly tests SQL injection payloads across

multiple endpoints without duplicating test code?

A. @pytest.mark.parametrize('payload', PAYLOADS) with a fixture for endpoint B. @pytest.mark.parametrize('endpoint,payload', [(e,p) for e in E for p in P]) C. A loop inside the test body iterating endpoints and payloads D. @pytest.fixture(params=PAYLOADS) returning endpoint

Answer: B. @pytest.mark.parametrize('endpoint,payload', [(e,p) for e in E

for p in P])

Cartesian parametrization of both endpoint and payload generates independent test cases with clear IDs. Option A only varies payload, C hides failures in one test, and D mislabels payloads as endpoints.

37. An API accepts a JWT but never verifies the signature. Which

vulnerability class does this represent?

A. Broken Object Level Authorization B. Broken Authentication C. Server-Side Request Forgery D. Mass Assignment

Answer: B. Broken Authentication

Skipping signature verification allows forged tokens, a broken authentication flaw (API2:2023). BOLA concerns object access, SSRF concerns server-side fetches, and mass assignment concerns binding extra fields.

38. Which pytest fixture scope should a database container use to balance

speed and isolation for API security tests?

A. function B. class C. module D. session

Answer: D. session

A session-scoped container starts once, maximizing speed; per-test isolation is achieved via transactions or truncation. Function/class/module scopes restart the container frequently, incurring heavy overhead without added security isolation.

39. When testing rate limiting, which assertion best verifies the API returns

429 after exceeding the threshold?

A. Assert the 101st request status is 429 and Retry-After header present B. Assert all requests return 200 C. Assert response time increases linearly D. Assert 401 is returned after 100 requests

Answer: A. Assert the 101st request status is 429 and Retry-After header

present

A correct rate-limit test confirms the over-threshold request yields 429 and includes Retry-After per RFC 6585. B ignores limiting, C is unrelated, and D confuses authorization with throttling.

40. Which secure Python practice prevents mass assignment when binding

JSON to an ORM model?

A. model.update(request.json) B. Explicitly whitelist allowed fields before assignment C. Use setattr for every key in request.json D. Rely on ORM default column types

Answer: B. Explicitly whitelist allowed fields before assignment

Whitelisting permitted fields blocks attackers from setting privileged attributes like is_admin. Options A and C bind arbitrary keys, and D addresses typing, not authorization of fields.

44. A test mocks requests.get but the code under test uses

requests.Session().get. Why does the mock fail to intercept?

A. requests.Session bypasses monkeypatching by design B. Session.get is a bound method resolved on the instance, not the module attribute C. requests.get is immutable in Python 3.12+ D. unittest.mock cannot patch C-extension functions

Answer: B. Session.get is a bound method resolved on the instance, not the

module attribute

Patching requests.get alters only the module-level function; Session().get is looked up on the Session instance/class. Correct interception requires patching requests.Session.get or injecting a transport adapter.

45. Which coverage metric most directly reveals untested branches in

input-validation logic?

A. Statement coverage B. Function coverage C. Branch coverage D. Line coverage

Answer: C. Branch coverage

Branch coverage measures whether both outcomes of each decision (e.g., valid/invalid input) execute, exposing untested validation paths. Statement, line, and function coverage can be 100% while branches remain untested.

46. An endpoint concatenates a user-supplied sort parameter into SQL. Which

test most effectively detects the injection vulnerability?

A. Parametrize with payload "name; DROP TABLE users--" and assert no 500 B. Send a 10 MB payload and assert 413 C. Request without Authorization and assert 401 D. Send duplicate query keys and assert 400

Answer: A. Parametrize with payload "name; DROP TABLE users--" and

assert no 500

Injecting a SQL metacharacter payload and asserting the server does not error or execute it detects concatenation-based SQL injection. Size, auth, and duplicate-key tests address unrelated controls.

47. Which Python practice best mitigates CWE-89 in a data-access layer?

A. Escaping quotes with str.replace before concatenation B. Using parameterized queries with bound placeholders C. Validating input with a regex allowlist only D. Disabling detailed database error messages

Answer: B. Using parameterized queries with bound placeholders

Parameterized queries separate code from data, structurally preventing SQL injection (CWE-89). Manual escaping is error-prone, allowlists alone are insufficient, and suppressing errors only hides symptoms.

48. A test asserts response.status_code == 201 but the API returns 200 with a

Location header. What is the most rigorous fix?

A. Loosen the assertion to status_code in (200, 201) B. Assert 201 and treat the API as buggy per RFC 9110 C. Assert 200 and remove the Location check D. Skip the test with pytest.mark.skip

Answer: B. Assert 201 and treat the API as buggy per RFC 9110

Successful resource creation should return 201 with Location per RFC 9110; the test correctly encodes the contract and should fail, flagging an API defect. Loosening or skipping the assertion masks a real spec violation.

49. Which pytest feature best enables exhaustive testing of an input-validation

matrix without duplicating test code?

A. pytest.mark.parametrize with tuples of payloads and expected outcomes B. A single test looping over payloads with try/except C. pytest.fixture(scope='session') returning payloads D. pytest.mark.xfail on invalid payloads

Answer: A. pytest.mark.parametrize with tuples of payloads and expected

outcomes

parametrize generates distinct test cases per payload/outcome pair, giving isolated pass/fail reporting. A loop collapses failures into one result; a fixture only supplies data; xfail suppresses genuine failures.