






















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!























50 QUESTIONS
1 Design and implement secure unit tests using pytest advanced features (fixtures, parametrization, mocking) 2 Identify and verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated tests 3 Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions 4 WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests 5 Python Security 6 API Testing & Vulnerability Verification 2026 7 Foundations of Software Security & Python Testing 8 Applied Software Security & Python Testing 9 Advanced Software Security & Python Testing 10 Software Security & Python Testing Review
This study document brings together 50 carefully worded exam questions drawn from WGU D Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API Testing & Vulnerability Verification 2026, with the strongest emphasis placed on Design and implement secure unit tests using pytest advanced features (fixtures, parametrization, mocking), Identify and verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated tests and Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.
A. Change the fixture to function scope and use a transaction rollback per test. CORRECT B. Use @pytest.mark.flaky to retry failed tests automatically. C. Set --dist=loadscope to group tests by module and share the session fixture. D. Replace the session fixture with a global variable initialized at import time. RATIONALE: A function-scoped fixture with transaction rollback isolates each test, preventing shared-state races. Flaky retries mask the issue; loadscope still shares state across workers; global variables worsen isolation.
A. Decode the JWT payload and assert the 'alg' header is 'none'. B. Use a known secret to re-sign a modified payload and assert the server rejects it with 401. CORRECT C. Check that the token contains an 'exp' claim and is base64-encoded. D. Assert the token length is greater than 100 characters. RATIONALE: Re-signing with the correct secret and expecting rejection tests signature verification integrity. Option A tests for a vulnerability (alg none); C and D are superficial checks that don't validate tamper resistance.
A. Replace with subprocess.run without shell and add a test asserting no shell metacharacters are interpreted. CORRECT B. Add # nosec comment and write a test that the command executes successfully. C. Switch to os.system and test with a benign command. D. Use shlex.quote on arguments and test only with alphanumeric input. RATIONALE: Removing shell=True prevents injection; a test with metacharacters verifies safety. Nosec ignores the risk; os.system is also unsafe; shlex.quote without testing special chars is incomplete.
A. Query for your own user ID and assert fields are returned. B. Query for another user's ID using your token and assert access is denied. CORRECT C. Send an introspection query to list all types. D. Test that the API returns 200 for a valid query. RATIONALE: BOLA occurs when a user can access another user's data by changing the ID. Testing cross-user access with your token directly verifies the flaw. A and D only test normal operation; C checks introspection, not authorization.
A. The mock is not asserting the call arguments correctly. B. The test is patching the wrong module path. C. The header is added after the mock call. D. The test uses assert_called_once() without checking call args. CORRECT RATIONALE: assert_called_once() only checks the call count, not arguments. To verify headers, you must inspect call_args. The other options could be issues but D directly explains the false positive.
A. Generate random JSON payloads with large arrays and measure response time. CORRECT B. Send a single request with a very long string. C. Use @given(st.text()) and assert the endpoint returns 200. D. Mock the database and test with empty input. RATIONALE: Large arrays can trigger algorithmic complexity or memory issues; measuring response time detects DoS. A single long string may not stress; C only checks status; D bypasses real resource usage.
A. Session-scoped fixtures are re-instantiated per worker; the fix is to promote the fixture to module scope so each test module gets a fresh cache. B. Each xdist worker runs in a separate process, so the 'shared' cache is actually per-worker; the fix is to make the fixture function-scoped or use a truly shared external store. CORRECT C. pytest-xdist serializes fixture setup via a global lock, so the failures stem from a race on teardown ordering; the fix is to add autouse=True. D. The failures are caused by pytest caching bytecode; the fix is to disable the cache provider with -p no:cacheprovider. RATIONALE: pytest-xdist distributes tests across separate worker processes, so an in-memory session fixture is duplicated per worker and cannot provide cross-test shared state; making it function-scoped or using an external shared store restores determinism. The other options misattribute the cause to scope promotion, teardown locking, or bytecode caching, none of which address process isolation.
A. Assert that jwt.decode(token, options={'verify_signature': False})['sub'] equals the expected subject. B. Assert that re-encoding the decoded header and payload with the server's public key reproduces the original token. C. Assert that jwt.decode(token, public_key, algorithms=['RS256']) raises InvalidSignatureError after a single byte of the payload is flipped. CORRECT D. Assert that the token's exp claim is in the future and the algorithm header equals 'RS256'. RATIONALE: Only verifying the signature against the public key and confirming that a payload mutation triggers InvalidSignatureError actually tests cryptographic integrity. Options A and D bypass signature verification or only inspect claims, while B misuses the public key (signing requires the private key), so it cannot reproduce a valid token.
A. The patch target was requests.get globally instead of the name as imported into the module under test (e.g., mymodule.requests.get). CORRECT B. patch cannot mock functions from third-party libraries; only patch.object works on external modules. C. The mock was created with spec=True, which disables call interception. D. The test lacked autouse=True, so the patch was never applied during the call. RATIONALE: patch replaces the name where it is looked up; patching requests.get globally does not affect a module that bound the reference via from requests import get or that resolves the attribute through its own namespace. The other options misstate mock capabilities (B), confuse spec behavior (C), or misunderstand autouse scoping (D).
A. Line coverage instruments only statements, so branch coverage would have caught the bug. B. Coverage measures execution, not assertion strength; mutation testing would reveal that the tests fail to detect the defect. CORRECT C. The threshold should be raised to 100% to guarantee correctness. D. pytest-cov under-reports assertions, so the metric is unreliable by design. RATIONALE: Coverage quantifies which code executed, not whether outputs were verified, so assertion-free tests inflate it without detecting defects; mutation testing measures the suite's defect-detection power. Branch coverage (A) can help but does not address missing assertions, 100% (C) is no guarantee, and D misstates what pytest-cov measures.
A. Assert status == 200 because a valid token was presented. B. Assert status == 401 because authentication failed. C. Assert status == 403 because the token is authenticated but insufficiently scoped. CORRECT D. Assert status == 400 because the request body is malformed. RATIONALE: A valid but under-scoped token is an authorization failure, correctly mapped to 403 Forbidden; 401 denotes authentication failure and 400 denotes a malformed request. Accepting 200 (A) would encode a privilege-escalation vulnerability into the test oracle.
A. pytest.raises matches subclasses, and TypeError is a subclass of ValueError. B. The mock's side_effect was set to a callable that swallows the exception before it propagates. C. pytest.raises suppresses all exceptions unless match is provided. D. The function under test wraps any exception in ValueError, masking the injected TypeError. CORRECT RATIONALE: If the function under test catches broad exceptions and re-raises ValueError, the injected TypeError is masked and the assertion passes for the wrong reason. TypeError is not a subclass of ValueError (A), side_effect callables propagate normally (B), and pytest.raises does not suppress without match (C).
A. The test omitted negative cases where the header is present but the token is invalid or absent. CORRECT B. The test used requests instead of httpx, which cannot test CSRF. C. The test should have asserted a 200 response to confirm the endpoint works. D. The test should have disabled TLS verification to expose the vulnerability. RATIONALE: By only exercising the no-header path, the suite never checks the branch where the header exists but the token is missing or forged, which is exactly the vulnerable condition. The HTTP client choice (B), asserting success (C), and disabling TLS (D) are irrelevant to CSRF token validation logic.
A. Assert status code equals 200 for a known ID and 404 for an unknown ID B. Assert that response time, status, and body schema are indistinguishable for existing and non-existing IDs CORRECT C. Assert that the endpoint rejects SQL metacharacters in the ID path parameter D. Assert that the Content-Type header is application/json for all requests RATIONALE: User enumeration is detected by verifying that responses for valid and invalid identifiers are indistinguishable across timing, status, and body shape. Checking only 200 vs 404 or content type ignores the leak, and SQL metacharacter rejection tests injection, not enumeration.
A. The root fixture, because conftest resolution is global B. The security fixture, because the nearest conftest.py takes precedence CORRECT C. Both fixtures, merged by pytest at runtime D. Neither; pytest raises a duplicate fixture error RATIONALE: Pytest resolves fixtures from the closest conftest.py in the directory hierarchy, so the security-local fixture overrides the root one. This matters because a security conftest can inject hardened clients or mocks without affecting unrelated tests. Duplicate names across conftest files are not errors; the nearer definition wins.
A. Assert the hash equals bcrypt.hashpw output with a fixed salt B. Assert that bcrypt.checkpw returns True for the correct password and False otherwise, without asserting the digest CORRECT C. Assert the SHA-256 digest length is 64 characters D. Assert the hash changes when the password changes RATIONALE: Modern password storage requires salted, adaptive hashing (bcrypt/argon2), and tests should verify verification behavior rather than fixed digests. Asserting a fixed bcrypt salt or SHA-256 properties does not validate the security property. The checkpw round-trip test captures correctness without brittle or insecure assertions.
A. Patch requests.get with autospec=True B. Patch requests.Session.get instead of requests.get CORRECT C. Use monkeypatch.setattr(requests, 'get', ...) in a fixture D. Assert the call count using mock.call_count RATIONALE: The test mocks the wrong attribute; production uses Session.get, so patching requests.get leaves the real call unmocked. autospec on requests.get still patches the wrong symbol, monkeypatch has the same target problem, and call_count assertions do not fix the target.
A. Parametrize over all endpoints and assert 401 for each B. Parametrize over protected endpoints asserting 401 and separately assert /health returns 200 without credentials CORRECT C. Assert only that /health returns 200 D. Assert that the 401 response body does not reveal server version RATIONALE: Correct coverage distinguishes protected endpoints (401 without credentials) from intentionally public ones (/health 200), avoiding both false positives and false negatives. Asserting 401 for all endpoints would incorrectly fail /health, and testing only /health or response body hygiene misses the auth boundary.
A. Line coverage percentage B. Branch coverage percentage C. Mutation score from a mutation testing tool CORRECT D. Number of assertions per test RATIONALE: Mutation testing introduces faults and measures whether tests detect them, exposing tests that execute code without meaningful assertions. Line and branch coverage can be inflated by trivial tests, and assertion count is a weak proxy for test strength.
A. Add match= with a regex matching the expected message CORRECT B. Wrap the call in a try/except and assert the exception type C. Use pytest.warns instead of pytest.raises D. Assert the function returns None on invalid input RATIONALE: Using match= constrains the exception to the expected message, distinguishing the intended error from unrelated ValueErrors. try/except replicates the unconstrained check, pytest.warns targets warnings not exceptions, and asserting None changes the expected behavior.
A. The conftest fixture is instantiated once per session, so rollback occurs only after all modules finish, leaking state across modules. B. The conftest fixture wraps the module-scoped db; its transaction is created per test function, preserving function-level isolation while reusing the connection. CORRECT C. Because db is module-scoped, the conftest fixture must also be module-scoped; pytest raises a ScopeMismatch error otherwise. D. The conftest fixture overrides db and forces function scope, silently ignoring the module scope declaration. RATIONALE: A function-scoped fixture may depend on a broader-scoped fixture; the narrower scope controls setup/teardown frequency, so the transaction is per-test while the connection is reused. Option C is wrong because pytest allows narrower fixtures to depend on broader ones, not the reverse. A and D misstate scope resolution rules.
A. Assert the output starts with $2b$12$ and that two calls with the same password differ. CORRECT B. Assert the output length is exactly 60 characters and contains a salt. C. Assert the function calls bcrypt.hashpw exactly once using a mock. D. Assert the output equals a precomputed hash of the password. RATIONALE: Checking the bcrypt prefix encodes algorithm and cost, and differing outputs verify salting-both are security properties. B is weak (length alone), C couples to implementation, and D breaks with salting.
A. st.integers(min_value=-(2**63), max_value=2**63-1) with a check that round-trip equality holds. CORRECT B. st.integers() with a check that no exception is raised. C. st.text() with a check that the function returns a string. D. st.floats(allow_nan=False) with a check that the result is finite. RATIONALE: Boundary integers at 64-bit limits expose overflow/underflow during serialization round-trips. B lacks bounds, C tests wrong type, and D targets floats, not integer overflow.
A. Send a token with header {"alg":"none"} and no signature; assert 401 Unauthorized. CORRECT B. Send a token signed with HS256 using the correct secret; assert 200 OK. C. Send an expired token; assert 401 Unauthorized. D. Send a token with an invalid signature; assert 401 Unauthorized. RATIONALE: The alg=none attack exploits libraries accepting unsigned tokens; asserting rejection specifically validates mitigation. B tests valid auth, C tests expiry, and D tests signature verification-none isolate the none-algorithm bypass.
A. Use pytest-socket with --disable-socket and a @pytest.mark.enable_socket marker on integration tests. CORRECT B. Use pytest-httpserver to stub all external endpoints globally. C. Use responses to mock requests, and rely on developers to register mocks. D. Use pytest-xdist to parallelize tests so network calls time out faster. RATIONALE: pytest-socket blocks sockets by default and allows opt-in via marker, enforcing isolation. B requires stubbing every endpoint, C is opt-in and leaky, and D does not block network access.