
















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















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).
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
A. function B. class C. module 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.
A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API5: Broken Function 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.
A. pytest.mark.parametrize B. pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.mark.xfail
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.
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
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.
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
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.
A. requests B. urllib C. httpx D. aiohttp
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.
A. @pytest.mark.skip B. @pytest.mark.xfail C. @pytest.mark.skipif D. @pytest.mark.filterwarnings
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.
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
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.
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
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.
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
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.
A. Statement coverage B. Function coverage C. Branch coverage D. Line 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.
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
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.
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
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.
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
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.
A. session-scoped autouse fixture B. function-scoped fixture with yield teardown C. parametrize with indirect=True D. monkeypatch.setenv in conftest
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.
A. branch coverage B. mutation score C. statement coverage D. cyclomatic complexity
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.
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
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.
A. Broken Object Level Authorization B. Broken Authentication C. Server-Side Request Forgery D. Mass Assignment
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.
A. function B. class C. module 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.
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
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.
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
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.
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
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.
A. Statement coverage B. Function coverage C. Branch coverage D. Line 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.
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
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.
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
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.
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
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.
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
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.